# terrainData
A landscape's baked data, as one asset.
A terrain is never a single image. It is a heightfield, the control textures
saying which surface covers where, a mask of where there is no ground at all,
the water surface standing over it, and the table of what those surfaces are.
Every one of those is an ordinary `.texture` the renderer already knows how to
sample; this container holds them together and names their roles, so a `Terrain`
component references a **landscape** rather than a handful of loose images, and a
heightfield never turns up in the picker beside an albedo map.
```
dunes.terrainData/
terrain.yaml the manifest: where the ground stands, and role -> child (required)
README.md what landscape this holds (required)
.metadata description and tags (required)
height.texture/ rgba32f: R metres, G/B gradient, A coverage
normal.texture/ uastc with mips: the ground normal, R x, G z, B y as n * 0.5 + 0.5
ground.texture/ uastc with mips: R the sky the ground sees, G wetness, B convexity, A deposit
macro.texture/ uastc with mips, sRGB: the colour of the far ground
holes.texture/ uastc with mips: R non-zero where there IS ground
water.texture/ rgba32f: R the surface's world Y, G its coverage
water_shade.texture/ uastc with mips: R the water column over the deepest column, G coverage
control0.texture/ uastc with mips: four layer weights, one per channel
control1.texture/ uastc with mips: layers 5-8
slice_albedo_0.texture/ uastc with mips: one layer texture per distinct albedo
slice_normal_0.texture/ uastc with mips: one per distinct normal map
slice_mask_0.texture/ uastc with mips: one per distinct mask map
surfaces/ the textures a graph made for the layers: <layer>_<role>.texture (optional)
graphs/ the graph that makes this ground and the parts it calls: .procGraph assets (optional)
```
The children are written by the same `asset.create` every other texture goes
through and placed inside the container by `dest`, the way a bundle carries the
meshes it assembles. A container holds `holes`, `water` and the `slice_*` children
only when the landscape has them.
## A landscape that carries its graph
`asset.create("terrainData", "Vale")` makes a container with a starter graph under `graphs/` (256 by 256 m at one metre a
cell, the inputs `seed` and `relief`), names it in the manifest (`graph: "~.graphs.ground"`, version 2) and cooks it when it
registers. `~` inside the container means the container.
Where it lands: at the source root as `Vale.terrainData`, in a folder with `folder`, or at a path of its own with `dest`.
`dest` is the path of the container itself, so it ends in `.terrainData`; a `dest` that names a plain folder is refused,
naming the `folder` that places the container inside it.
```lua
asset.create("terrainData", "Vale") -- /source/Vale.terrainData
asset.create("terrainData", "Vale", { folder = "terrain" }) -- /source/terrain/Vale.terrainData
asset.create("terrainData", "Vale", { dest = "/source/terrain/Vale.terrainData" }) -- the same, by full path
```
`terrainRef:cook()` runs the graph and writes what it makes into
the container itself, the children in place and the manifest once at the end, on the background lane a slice of each frame
at a time, so the ground standing in a scene is drawn until the new one lands and each `Terrain` standing on it rebuilds
once. `terrainRef:inputs()` states the graph's inputs with the values the manifest gives them, `setInputs({ relief = 80 })`
changes them, and in edit mode a change to the inputs or the graph cooks once, a moment after the last edit.
`bakeState()` says where the ground stands (`state`, `revision`, `stale`). `terrain.write` into a container that names a
graph is refused: its ground is what the graph makes. `asset.create("terrainData", name, { graph = false })` makes the
bake-only container `terrain.write` fills, which is version 1 and never cooks.
```yaml
version: 2
graph: "~.graphs.ground" # the graph that makes this ground
output: landscape # the graph output the cook takes (landscape when left out)
inputs: { relief: 55 } # values for the graph's inputs, by name
bake: { revision: 7, graph: 3141592653, inputs: 271828182 } # what the children were cooked from
```
## The manifest
```yaml
version: 1
size: [4000, 4000] # metres of ground, along world X and Z
origin: [0, 0] # world centre of that rect
heightRange: [-8.1, 63.4] # the vertical reach the geometry declares
height: height.texture
normal: normal.texture
ground: ground.texture
macro: macro.texture
holes: holes.texture
water: water.texture
waterShade: { file: water_shade.texture, depthMax: 12.5 }
controls: [control0.texture, control1.texture]
layers:
- { name: sand, tint: [0.62, 0.56, 0.42], tiling: 12, albedoSlice: 0, normalSlice: 0, maskSlice: -1 }
- { name: rock, tiling: 8, albedoSlice: 1, normalSlice: -1, maskSlice: -1 }
slices:
albedo: [slice_albedo_0.texture, slice_albedo_1.texture]
normal: [slice_normal_0.texture]
size: [1024, 1024]
```
Children are named **relative to the container**, so a landscape that is moved
or renamed carries its own textures with it.
## The payloads
**The heightfield** is `rgba32f`: R the height in **metres**, G and B its
gradient along world X and Z, A coverage. Metres and not a normalized 16-bit
ramp, because relief is often a few metres inside a range of hundreds and eight
or sixteen bits band that into terraces. The gradient is what a surface normal
comes out of without differencing the height four more times.
**The control textures** are `uastc` with mips, one channel per surface layer, four layers
a texture and another texture for every four after that. A texel holds how much
of each layer covers it, and the weights are **normalized to sum to one** when
they are written: a texel covered half by sand and half by rock reads 128/128,
whatever the two masks happened to evaluate to. A uastc block holds the four
channels to within a step of that sum, so the surface renormalizes the weights
it samples. Layer `n` is channel `((n - 1) % 4) + 1` of control texture
`ceil(n / 4)`; `:layerSlot(name)` answers that for a named layer.
**The holes mask** is `uastc` with mips, R non-zero where there **is** ground. Terrain a
cave mouth or a quarry has been cut out of has holes, and a hole is absence
rather than a height of zero.
**The water surface** is `rgba32f`: R the world Y the surface stands at, in
metres, G whether a surface covers that texel. A sea, a lake and a river are the
same thing here: a level and where it reaches. `water_shade` is its filterable
`uastc` companion that the water's material reads per pixel, R the column over
`depthMax` and G coverage.
**The layer table** says what each control channel stands for: its tint, its
albedo, its normal map, its mask map (R metallic, G ambient occlusion, B height,
A smoothness), and the metres one repeat of them covers (`tiling`).
**The layer slices** are the layers' own textures, one child per distinct texture
per role (albedo, normal, mask), all resampled to one square edge (`slices.size`).
Every slice is written `uastc` with mips, `srgb` for the albedo and linear for the
normal and mask maps. A surface binds each role's slices as one texture array, and each layer's
`albedoSlice`, `normalSlice` and `maskSlice` says which slice it reads (0-based,
-1 for none). A slot per layer per map would be twenty-four sampled textures in
one bind group, past what a fragment stage is guaranteed; three arrays cost three
slots whatever the layer count, and every slice wraps on its own.
## Filling one
`terrain.write` in a procgen graph writes the manifest and every child in one
step, and answers the reference to the container. It takes:
- `raster`: the ground; its `height` layer becomes the heightfield.
- `name`: the container's identity, a bare identifier (`dunes` writes
`dunes.terrainData`). `folder` or `dest` places it.
- `layers`: the names of the raster layers holding each surface's coverage, in
channel order, separated by commas (`"sand, rock"`). Coverage per surface is an
ordinary mask layer written by `terrain.mask`.
- `surfaces`: optional records of `{ name, tint?, albedo?, normal?, mask?, tiling? }`
matched to a layer by `name`, saying what each surface is shaded with. `albedo`,
`normal` and `mask` each take a texture the graph made (a `texture.*` node wired straight
in, or the `Texture` value a Luau script gives the `terrain.write` op: the bake writes it as
`surfaces/<layer>_<role>.texture`, and a re-bake removes the `surfaces/` textures and slice
children it no longer writes), an `AssetRef<texture>`, the identity, guid or path of a
texture asset, or nothing. Any other value is refused naming the layer and the role.
- `holes` / `solid`: a mask layer marking where ground is cut out, or where it
exists.
- `height`, `water`, `waterMask`: the raster layers read for the heightfield and
the water surface.
- `resolution` and `layerResolution`: the texel size of the maps and the edge of
one layer slice.
A surface that names no texture is shaded by its `tint`. Writing the same name
again re-bakes in place and keeps the guid, so every reference already pointing
at that landscape stays resolved.
## Reading one
| Method | |
|---|---|
| `:placement()` | `{ size, origin, heightRange }`: where the ground stands and how far it reaches. |
| `:height()` | The heightfield texture. |
| `:normal()` | The ground normal texture, or nil for a landscape written without one. |
| `:ground()` | The ground masks texture (R the sky the ground sees, G wetness, B convexity, A deposit), or nil for a landscape written without one: `asset.validate` warns `terrainData.no_ground` for a cooked graph that has none. |
| `:macro()` | The colour of the far ground, or nil for a landscape written without one or with no layer. |
| `:holes()` | The holes mask, or nil when the ground is solid everywhere. |
| `:water()` | The water surface texture, or nil when the landscape is dry. |
| `:waterShade()` | `{ texture, depthMax }`, or nil for a landscape carrying no water. |
| `:control(i)` / `:controls()` | The weight textures, in channel order. |
| `:layers()` | The surface table. |
| `:slices()` | `{ albedo?, normal?, mask?, size }`: the layer textures per role, or nil when no layer carries a texture. |
| `:layerSlot(name)` | Which control texture and channel a named layer is in. |
| `:manifest()` | The whole thing, decoded. |
| `:instantiate(target?, opts?)` | An entity carrying a `Terrain` component bound to this asset. |
| `:setChild(role, file)` / `:setPlacement(p)` / `:setLayers(t)` / `:setSlices(s)` / `:setWaterShade(file, depthMax)` | What `terrain.write` fills it through. |
The placement travels with the landscape, so a `Terrain` component standing on
one does not re-state how big it is.
## Validation
`asset.validate` (and the publish gate) refuse a container whose manifest does
not decode, that does not say where its ground stands, that names a child which
is not there, or that declares more layers than its control textures can carry. A file in
`surfaces/` that is not a `.texture` is reported as `terrainData.surfaces_foreign`.
A landscape whose heightfield is missing is ground nothing can stand on, and
that is worth catching before it is published rather than when an entity tries
to load it.
## In the Inspector
Selecting a terrain opens its **Terrain** section: its size, origin and height range, the heightfield's resolution once one is written, a table of its material layers (name, tiling, whether it has an albedo), and a link to each child texture (heightfield, holes, water, control maps). A terrain not yet sculpted says it has no child textures.
# Terrain (component)
Ground, as scene content. Part of the
[terrainSystem package](../../README.md) — every terrain entity in a scene
carries exactly one of these.
An entity carrying this component IS a landscape: a `.terrainData` standing over
a rect of world, drawn through a quadtree of LOD nodes that
refines under whichever camera is looking at it, with a collider the default
avatar can walk.
```luau
-- The whole of it: one reference. The landscape says how big it is.
entity(id).component.add("Terrain", { terrain = dunes })
```
A landscape is held whole: every texel of it, on the CPU and on the GPU, for as
long as the entity stands. A map larger than that (many kilometres, an open
world, a driving or flight game, ground that must not all be in memory at once
on a phone) is a [`TerrainStream`](../TerrainStream.component/README.md): the
same ground streamed in tiles that load, draw and collide around the player,
the camera and every vehicle, from a `height(x, z)` function or one baked
`.terrainData` a tile.
## Properties
| Name | Type | Default | Description |
|------|------|---------|-------------|
| `terrain` | `AssetRef<terrainData>` | `nil` | The landscape this entity IS — the heightfield, the control textures, the holes mask and the layer table, held together as one asset. It states the rect it covers and the reach it declares. |
| `material` | `AssetRef<material>` | `nil` | What the ground is shaded with. Left empty, the landscape's own layer table is drawn by the layered surface; a landscape with no layers falls back to the package's `terrainStandard`. A named material replaces the layer table. A material whose shader declares the terrain surface contract properties (`terrain_field_min`, `terrain_normal`, ...) is worn as a copy with the landscape's values bound; see the terrain guide. |
| `sharpen` | `number?` | unset | Tuning of the layered surface that draws the landscape's own layer table: the power every surface weight is raised to before renormalising. Unset is 1, the stack as baked. |
| `normalStrength` | `number?` | unset | How far the layered surface takes the ground normal the landscape carries: 0 keeps the vertex normal, 1 the baked one. Unset is 1. |
| `heightBlend` | `number?` | unset | How sharply a surface's own relief settles a contested pixel on the layered surface. Unset is 8 where the landscape carries layer relief, else 0. |
| `size` | `vec2` | `{ 0, 0 }` | Where the ground stands, when it should stand somewhere other than where the landscape says. Left at zero, the container's own placement is used. |
| `origin` | `vec2` | `{ 0, 0 }` | World centre of that rect, same rule. |
| `heightRange` | `vec2` | `{ 0, 0 }` | The vertical reach the geometry declares — `x` the lowest metre, `y` the highest. Left at zero, the landscape's own reach is used. |
| `collision` | `boolean` | `true` | A static heightfield collider over the whole rect. Each painted layer collides as the surface named after it (`Physics.defineSurface`): a sample of the collider names the layer covering it most, so contacts and ray and shape casts on the ground report that layer as `surface`, and a surface defined under a layer's name gives that ground its friction, restitution and rolling resistance. |
| `collisionResolution` | `number` | `0` | Collider samples along each axis. Zero collides on the ground's own texels, exactly where `heightAt` answers; a count coarser than the ground trades fidelity for cells. |
`heightRange` is the mesh's bounding box, so a range smaller than the ground
culls the terrain away at grazing angles and the symptom is nothing at all on
screen.
By default the collider's samples stand on the ground's texel centres, read as
they are, with a half-texel strip out to each edge, and each cell splits into
the same two triangles `heightAt` reads it as
(`terrainHeightfield.colliderTiles`). A ray onto the collision meets the height
`heightAt` answers anywhere on the rect. The mesh stands every vertex on a
stop of that same lattice, and its cut is counted on it: the finest node is 32
texels across with a vertex at every texel centre, whatever the texel size,
and every other node is a power of two of that. The finest node draws the
collider's own triangles, so a body rests on the ground a player sees; the one
strip of cells along an edge it stitches to a coarser neighbour follows that
neighbour's edge instead. A larger node draws a subset of the lattice and
stands off the collider by its level of detail. The collider is tiled, at most
512 samples a side a tile, so a landscape of up to 2048 x 2048 texels collides
at its own resolution;
past that the collider is coarsened evenly and the component reports it. A
`collisionResolution` coarser than the ground samples the rect at that count
instead, which costs fewer cells and puts the collision away from the drawn
ground by however much the ground bends between samples.
The heightfield's own texel count sets how finely the ground is described inside
the rect; the landscape's `size` sets how much world that description covers.
## Where the ground stands
The landscape's coordinates are the entity's local space. The mesh is drawn
through the entity's transform and every collider tile is a child of the entity
standing in those same coordinates, so moving, turning, tilting or scaling the
entity (a positive scale along each of its own axes) carries the
drawn ground and its collision together, and a ray onto the collision meets the
ground where it is drawn.
The queries below name a WORLD point and answer for that same ground: `heightAt`
is the world Y a ray cast straight down at (x, z) meets it at, `normalAt` and
`slopeAt` are the world's normal and slope there (on a tilted entity the tilt is
part of the slope), and `hasGroundAt`, `waterAt` and `depthAt` read the point of
the landscape under (x, z). Under an entity turned on its side or past it no
ground faces up, and each query answers as it does off the ground: nil, false or
0. `field()` is the heightfield itself, which answers in the landscape's own
coordinates.
## Where the landscape comes from
A graph. It opens a rect of ground with `terrain.source`, shapes it with the terrain
nodes (`fbm`, `cone`, `ridge`, `erode`, ...), writes the coverage of each surface as a
mask layer with `terrain.mask`, and ends in `terrain.write`, which bakes the manifest and
every child texture in one step and answers the reference to the `.terrainData`. That is
the same move every other procgen family makes to persist what it made. The reference is
what the component's `terrain` property holds:
`entity(id).component.add("Terrain", { terrain = ref })`.
A heightmap made anywhere else (an 8-bit image, a downloaded elevation tile) comes in
through `terrain.from_texture` and back out through `terrain.write`.
What a surface is shaded with is a texture per role (`albedo`, `normal`, `mask`): a
`texture.*` node wired straight in, an `AssetRef<texture>`,
the identity, guid or path of a texture asset, or none (the layer's `tint` carries it). The
terrain guide's "Surfaces" section gives each form.
## Lifecycle
- `awake` — opens the landscape, builds the LOD pool, binds it to the entity,
adds the `Model` and the collider.
- `update` / `editorUpdate` — follows the on-screen camera with the cut, in edit
and in play alike.
- `onPropertyChanged` — a `material`, `sharpen`, `normalStrength` or `heightBlend` change swaps the Model's
material in place; anything else describes the ground itself, so the ground is rebuilt.
- `onDestroy` — releases the mesh, the pool and the heightfield's pixels.
## Methods
| Method | |
|---|---|
| `:heightAt(x, z)` | World Y at world (x, z): the surface the collision holds and the mesh is drawn on. |
| `:normalAt(x, z)` | Unit surface normal in the world, three numbers. |
| `:slopeAt(x, z)` | Degrees from the world's level; 0 is flat. |
| `:field()` | The heightfield itself: the value every `terrainHeightfield` verb takes, in the landscape's own coordinates. |
| `:reload()` | Read `terrain` again and rebuild what the entity draws, on the component's next frame; the rebuild is the component's own work and records nothing on the scene. A standing Terrain takes a new bake of its landscape by itself. |
| `:errors()` | What the component has reported: a landscape that never validated, a contract name of the wrong type, a named material that replaces the layer table or cannot be given the landscape's weights, a shader that failed to compile. |
The queries answer from the same texels the geometry is built out of, so what a
script is told and what a player walks on cannot disagree.
Re-baking the landscape and calling `:reload()` moves every terrain standing on
that asset, without a restart and without touching the scene graph —
the mesh keeps its guid, so the Model is never re-bound.
## One draw
Every node of the LOD cut is one range of one index buffer, so the whole
terrain — at every level, however large — is a single indexed draw on a single
entity. Nodes are never entities. `modules/terrainMesh` is the whole surface.
# TerrainStream (component)
Ground many kilometres across, streamed. Part of the
[terrainSystem package](../../README.md).
A `Terrain` is one heightfield standing whole. An entity carrying
`TerrainStream` is a landscape divided into square tiles that load, draw and
collide around the places it is needed and are let go of behind them, within a
per-frame budget, so the memory it holds follows the radius it streams rather
than the size of the map.
```luau
-- The ground, as a module: any function of x and z.
-- /source/modules/mountains.module returns { height = function(x, z) ... end }
entity(id).component.add("TerrainStream", {
size = { 8192, 8192 }, tileSize = 512, resolution = 2,
source = "modules.mountains",
})
-- Or at runtime, with no module at all.
local t = entity(id).component.get("TerrainStream")
t:setSource({
height = function(x, z) return 60 * math.noise(x / 900, z / 900) end,
layer = function(x, z) return if math.abs(z) < 4 then "asphalt" else "grass" end,
layers = {
asphalt = { tint = { 0.06, 0.06, 0.07 } },
grass = { tint = { 0.30, 0.45, 0.20 } },
},
})
```
The tiles stream around every entity carrying `StreamingSource` (the player, a
vehicle), around the on-screen camera (the editor camera in edit, the gameplay
camera in play), and around what `addFocus` names; `focusPoints()` lists those
places this frame, so content that streams beside the landscape (a road
surface, scenery) streams around the same ones. The ground near an entity
focus collides, in blocks of `colliderCells` cells; the camera only draws.
A procedural source's `layer(x, z)` names the surface each point is, and the
one function decides both what the ground is and how it looks: contacts and
casts on the ground report it, `layerAt` answers it, `Physics.defineSurface`
gives it its grip, and every tile draws it, at every level of detail, meeting
the tile beside it the way the heights do. A road painted into `layer` is
drawn as road where it collides as road, to within one sample spacing. A
surface is read once a sample, so its drawn edge runs midway between the
samples and steps with them: a finer `resolution` draws it finer, and a tile
held at a coarser level of detail draws it at that level's spacing.
The source's `layers` states what each surface looks like, in the shape a
baked landscape's layer table takes: `{ asphalt = { tint = { r, g, b } },
grass = { tint = ..., albedo = texture, normal = texture, mask = texture,
tiling = 4 } }`, where `tint` multiplies the `albedo` texture and `tiling` is
the metres one repeat of the textures covers (an array of names and
`{ name = ..., tint = ... }` entries works too). A surface `layers` does not
describe is drawn in a colour of its own. Where `layer` names no surface, the
ground is drawn the way `terrainStandard` draws it, by height and slope, so a
source can name the road alone and leave the hillside as it was. One tile
draws the eight surfaces covering most of it, and says so in the log when it
names more. A source without `layer` is drawn by `terrainStandard`, a baked
tile by its own layer table, and `material`, when given, shades every tile
instead.
The tiles stand under the entity, in its local space: the landscape
moves, turns, tilts and scales with it, and the queries below take world X and
Z and answer for the ground drawn under that point, the ground a ray cast
straight down there meets: `heightAt` its world Y, `normalAt` its normal in the
world.
## Properties
| Name | Type | Default | Description |
|------|------|---------|-------------|
| `size` | `vec2` | `{ 4096, 4096 }` | The rect the landscape covers, in metres along X and Z. A whole number of tiles each way. |
| `origin` | `vec2` | `{ 0, 0 }` | The rect's centre. |
| `tileSize` | `number` | `512` | Metres along a tile's side. |
| `resolution` | `number` | `2` | Metres between two samples of the ground. A tile is cut into nodes of 32 quads, so `tileSize` is `32 * 2^k` samples across; any other pair holds its samples at the nearest such spacing, with one warning naming both. |
| `source` | `string` | `""` | The identity of a module returning `{ height = function(x, z) -> metres, layer? = function(x, z) -> surface name, layers? = { name = { tint, albedo?, normal?, mask?, tiling? } } }`: a module of the world's source by its identity (`modules.mountains` for `/source/modules/mountains.module`, `myGame.landscape` for `/source/myGame.package/landscape.module`), or a library module by its `@builtin::` identity. |
| `tiles` | `table` | `{}` | One baked `.terrainData` a tile, `{ ["tx:tz"] = path or guid }`, each baked over `terrainStream.tileSource`. |
| `material` | `AssetRef<material>` | `nil` | What every tile is shaded with. Empty: a baked tile by its own layer table, procedural ground by the surfaces its `layer` names, and by `terrainStandard` where it names none. |
| `collision` | `boolean` | `true` | Collider blocks around entity focus points. |
| `loadRadius` | `number` | `1500` | Tiles within this distance of a focus are drawn. |
| `unloadRadius` | `number` | `0` | Tiles past this distance from every focus are let go of. Zero is 1.25 x `loadRadius`. |
| `colliderRadius` | `number` | `160` | Collider blocks within this distance of an entity focus collide. |
| `budgetMs` | `number` | `4` | Milliseconds a frame may spend on tiles. |
| `colliderCells` | `number` | `32` | Cells along a side of one collider block. |
Distances are measured from a focus to the nearest edge of a tile, the way
`spatialStreaming` measures a cell, and the band between `loadRadius` and
`unloadRadius` keeps a focus resting on a tile boundary from loading and
releasing the same tile every frame.
## What a frame does
- Every tile within reach of a focus is wanted; a tile past `unloadRadius` of
all of them is let go of: its entity, its colliders, its mesh pool and its
heights.
- The collider block under each entity focus is stood up the frame it is
missing, whatever the budget: a body over ground that is not there falls.
`isReadyAt(x, z)` says whether it stands.
- The LOD cut is selected once across every tile standing, so it is balanced
across tile edges and every edge between two tiles is stitched the way an
edge between two nodes is.
- The rest of the work is spent inside `budgetMs`, the ground bodies collide
with first: the collider blocks around entity focus points, one block of
`colliderCells` cells at a time, nearest block first. A procedural block
reads its samples from the source, so collision never waits on drawing; a
baked tile is opened before its blocks, which read its texels. Then the
drawn ground, nearest tile first: sampling a tile's heights (a run of
samples at a time, stopping at the budget), putting them on the GPU and
meshing it. A piece of work that cannot be cut short starts only when what
that kind of work has cost so far fits in what is left of the frame; a
frame after one that ran nothing for that reason starts its first piece
anyway, so work larger than the budget still lands. A far tile's heights
are held only as finely as its finest node draws them.
- A collider block is let go of once it is a block's span further than
`colliderRadius` from every entity focus.
## Seams
Every tile samples one grid of points, `resolution` metres apart from the
rect's corner. Two tiles sharing an edge carry the same samples along it, and
two collider blocks share their edge row, so the drawn surfaces and the
colliders of neighbouring tiles meet sample for sample.
## Several peers
The tiles are local to each engine. Every peer streams the same source, so
peers agree on the ground under every body; a peer that simulates a vehicle
puts a `StreamingSource` on it (or names it with `addFocus`) so the ground
under it collides on that peer.
## Methods
- `stream()`: the `terrainStream` object (`tiles`, `stats`, ...).
- `setSource(source)`: the ground as a table of functions or a module identity.
A ground given in edit stands through play; one given while play runs
stands until play ends. The ground follows its source: editing the module it
comes from (named by `source`, or given to `setSource` by identity or as the
table `require` returns), or replacing a function of the table it was given,
stands the ground again from the new code.
- `heightAt(x, z)`, `normalAt(x, z)`, `layerAt(x, z)`: the ground at a point,
whether or not its tile is standing.
- `isReadyAt(x, z)`: whether the collider under a point stands.
- `addFocus(target)`: stream around an entity or point too: an entity id, an
entity, or a position (`vector.create(x, y, z)`, `{ x, y, z }` or
`{ x = x, y = y, z = z }`). A table is read every frame, so moving the table
moves the focus: the ground ahead of a fast body, say.
- `removeFocus(target)`: stop streaming around a target `addFocus` added.
- `focusPoints()`: every place the landscape streams around this frame, in
world coordinates, as `{ x, y, z, kind, collides }` (`kind` is `"source"`,
`"entity"`, `"point"` or `"camera"`).
- `stats()`: tiles standing, drawn and colliding, bytes held, the frame time
spent and its worst, and the cost of each kind of work.
- `standingTiles()`: every tile standing, with the detail its heights are held at (the `tiles` field names the baked ground).
·computeshader · born here
❒asset # terrain_apply_delta
Folds an erosion pass's accumulated fixed-point deltas into a channel and
clears the accumulator.
An erosion pass never writes height. Every gram of material it moves
accumulates into an integer accumulator in units of 1/65536 m, because integer
addition commutes and float addition does not — the summed result of thousands
of droplets landing on one cell is the same whatever order the threads resolved
in. This pass is where that sum becomes terrain.
It runs once per erosion iteration, after the gather that brings in the
material neighbouring tiles moved across the seam. `atomicExchange` reads and
zeroes in one step, so the accumulator is empty for the next iteration without
a second clearing pass.
One thread per stored cell, apron included. An apron cell's own delta is
applied here as well: the following apron exchange overwrites it wherever a
neighbour owns the cell, and where the field ends and no neighbour does, the
applied value is what keeps the border apron a plausible continuation of the
terrain rather than a step.
·computeshader · born here
❒asset # terrain_apron
Copies a rectangular block of a neighbour tile's stored cells into this tile.
A tile's apron holds a second copy of cells its neighbour owns. An op that is a
pure function of world position writes both copies to the same value on its
own; an op whose result depends on what the tile already held — erosion above
all — leaves the two copies disagreeing, and every neighbourhood read at the
seam then sees a different surface depending on which tile it came through.
This pass makes the apron read what the neighbour computed.
The block is given in stored-cell coordinates (`dstX0, dstZ0`, `srcX0, srcZ0`,
`blockWidth`, `blockHeight`) rather than as an edge index, so one shader moves
an edge band and a corner square. The caller issues one dispatch per neighbour
that exists: eight of them tile a tile's apron ring exactly, with no cell
written twice.
A block facing off the edge of the field has no neighbour and no dispatch. Its
apron keeps whatever the generating op wrote there, which for a world-space op
is the correct extrapolation of the landscape past the field boundary.
Run it after any op whose result is not a pure function of world position, and
between erosion batches — a droplet may walk at most `apron` cells before the
neighbourhood it is reading is no longer the neighbourhood its neighbour has.
·computeshader · born here
❒asset # terrain_coast
Pulls the ground outside a landmass down to a seabed altitude, by a radial
falloff about a point.
The land weight is 1 inside `radius`, falls to 0 across `falloff` metres beyond
it, and the height is interpolated between the seabed and whatever the stack
already built:
```
value = mix(seabed, prev, landWeight)
```
The interior keeps its landscape untouched, the rim slopes off it, and
everything past the rim sits at the seabed. Put the seabed below the sea level
and the result is an island — the terrain ends before the field's rect does,
and the rect goes on carrying the sea.
`shapeMode` picks the metric: 0 is a disc, 1 is the Chebyshev square.
This op covers the **whole field**, not the disc it is centred on: the ground
it changes is the ground outside that disc, and an op that only touched its own
radius would leave the far corners standing above the water.
It is an ordinary op in the stack, so an erosion below it weathers the
coastline it drew, a flatten cuts a harbour into it, and a river carves a mouth
through it.
`terrain_coast_mask` is the same operation driven by a painted raster instead of
a radius, for a coastline whose outline is drawn rather than described.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there — multiplied in, or subtracted out — so the op applies only where
the mask lets it and a cell the mask holds out keeps exactly what it already
held, at every blend mode. An op that names no mask writes at full strength
everywhere.
·computeshader · born here
❒asset # terrain_coast_mask
Pulls the ground outside a landmass down to a seabed altitude, with the
landmass given by a painted raster rather than a radius.
The raster is a layer co-registered with the field — one texel is one cell — so
the outline an author paints is the outline the coast follows. The value is the
land weight directly:
```
value = mix(seabed, prev, clamp(mask * gain, 0, 1))
```
1 is land and keeps the landscape untouched, 0 is open water and sits at the
seabed, and the values between are the shoreline slope: the softness of the
brush is the softness of the coast. `gain` scales the raster before the clamp,
so a stroke painted at a fraction of full strength can still read as solid land.
Like the radial form, this covers the **whole field** — the ground it changes
is the ground the mask does not cover.
`terrain_coast` is the same operation driven by a radius, for a coastline
described rather than drawn.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there — multiplied in, or subtracted out — so the op applies only where
the mask lets it and a cell the mask holds out keeps exactly what it already
held, at every blend mode. An op that names no mask writes at full strength
everywhere.
·computeshader · born here
❒asset # terrain_delta_gather
Adds a neighbour tile's apron-ring erosion deltas into this tile's interior.
A droplet spawned in one tile's interior may walk into that tile's apron and
deposit there. Those apron cells belong to the neighbour — the neighbour's
interior is what carries the field's value for them — so the deposit has to
reach the neighbour's accumulator before either tile folds its accumulator into
height. Without this pass, every cell within a droplet's reach of a seam
collects less material than the same cell away from one, and the seam shows as
a band running through the eroded terrain.
The block is described in stored-cell coordinates, the same description
`terrain_apron` takes, so the two passes address the same geometry from
opposite ends: this one reads the neighbour's apron ring and adds into this
tile's interior band; `terrain_apron` reads the neighbour's interior and
overwrites this tile's apron ring.
The accumulation is a fixed-point integer add. Integer addition commutes, so a
corner cell reached from three neighbours at once sums to the same value
whichever dispatch lands first — which is what keeps a tiled erosion run
reproducible.
·computeshader · born here
❒asset # terrain_erode_droplet
Droplet hydraulic erosion over one tile, one batch at a time.
Each thread carries one droplet. It is placed by a hash of its index, the op's
seed, the batch number and the tile's field-wide base cell, then runs downhill:
it picks up material where it moves fast over steep ground and drops it where
the ground flattens or rises. That is what cuts channels into a ridge and lays
the fans out below them, and it is why the result looks like water shaped it
rather than like a filter ran over it.
## Reproducibility
The pass never writes height. Every change accumulates into `delta` as
fixed-point integers, 1/65536 m per unit, through `atomicAdd`. Integer addition
commutes; float addition does not. Thousands of droplets landing on one cell
therefore sum to the same total whatever order the threads resolve in, and the
same seed over the same stack gives the same terrain every run — on any GPU,
with any scheduling.
A float accumulator would be a few last bits different each run, and everything
downstream that assumes a seed names a landscape (storage, streaming, a shared
world) would drift.
## What one batch may move
A batch works out every droplet's change from the ground as it stood when the
batch began and adds them all at the end, so nothing in a batch can see what
the rest of it is doing to the cell it is standing on. Two bounds are what keep
that from running away.
`share` is the part of one cell's rainfall a droplet carries. A batch rains
`dropletCount` droplets over the interior and each walks up to `apron` cells, so
a cell is stepped on `dropletCount * apron / interiorCells` times a batch and
every one of those steps adds into the same accumulator. Scaling each droplet's
change by the reciprocal is what makes `rain` a sampling density: doubling it
resolves the flow better and moves the same material. Rain too sparse to step on
every cell gives a droplet one cell's rainfall and no more, because a droplet
carrying several cells' worth would put a whole batch's cut into a single step
and reopen the swing below. A run below that density — fewer than
`interiorCells / apron` droplets a batch — therefore samples the flow sparsely
and moves proportionally less; above it the result stops changing with `rain`.
`MAX_SHARE` is the most of the drop below a cell one batch may cut, and the most
of the rise above it one batch may fill. Without it a droplet cuts the whole
drop, which leaves the cell level with the one it drains into — and every other
droplet in the batch cuts that same drop from the same starting ground, so the
cell ends the batch far below its neighbour. The next batch finds the pair
reversed and cuts back further, and the swing grows every batch until the
fixed-point accumulator wraps. `terrain_erode_thermal` names the same bound; a
quarter rather than a half, because water gathers where the ground funnels it
and a cell along a channel is stepped on several times over what an average
cell gets.
## Tiling
A droplet takes at most `maxSteps` steps, and the caller keeps that at or below
the apron width. Past that it would read cells whose real owner is a
neighbouring tile and whose contents have not been exchanged since the batch
began, and the two tiles would disagree about the ground at their seam.
Droplets spawn in the interior only. A spawn in the apron would place a second
droplet on ground the neighbouring tile has already rained on, doubling the
rainfall in a band along every seam. Material a droplet carries out of the
interior and into the apron is not lost: `terrain_delta_gather` adds it into
the neighbour's interior before either tile folds its accumulator into height.
What a droplet is still carrying when its walk ends goes with it. A run
therefore lowers the ground it cuts: material leaves the uplands, and a field
has no basin outside itself for it to arrive in. The fall in the field's mean
is a small fraction of the depth the channels reach.
## Parameters
Lane 1 carries `seed, batch, dropletCount, maxSteps`; lane 2
`solubility, deposition, evaporation, inertia`; lane 4
`minSlope, capacity, gravity, apron`. Heights are metres and horizontal
distances are cells, so `capacity` and `minSlope` read as metres of fall per
cell of run.
Every op carries a mask, and for a simulation it bounds what a step MOVES. The
mask scales both what a step cuts and what it lays down, and the material a step
declines to move stays where it was — in the ground, or in the droplet — so a
droplet carries its load ACROSS ground the mask holds out rather than losing it
there.
What a droplet still holds when its walk ends lands where the walk ended,
whatever the mask reads there. The ground it walked is already lighter by
exactly that much, so scaling that last drop would leave the difference nowhere
and the pass would remove material instead of moving it. The mask therefore
bounds where a run cuts exactly, and where it deposits everywhere except the
cell a walk ends on. An op that names no mask erodes at full strength
everywhere.
·computeshader · born here
❒asset # terrain_erode_stream
Stream-power erosion on a grid of at most a few hundred cells a side, the step `terrain.erode` runs for `model = "stream"`.
One dispatch is one step, picked by the `MODE` specialization, and each step writes one cell per thread from the buffers of the step before, so a run gives the same ground every time.
| `MODE` | One thread per | Writes |
|---|---|---|
| `down` | work cell | the mean of the field cells it covers |
| `sum` | work cell | the sum of the weights of its drops to its neighbours, the edge draining outward |
| `area` | work cell | one Jacobi pass of the drainage area in cells: one plus what each higher neighbour sends it, each neighbour sharing its area among its lower neighbours by `drop ^ power` |
| `incise` | work cell | the height after the implicit step `(h + F * h_r) / (1 + F)` toward the steepest lower neighbour, `F = K * A^m * dt / run`, plus the uplift step; `K` varies by `variation` over `variationSize` metres by the `seed`; with `keep` 1 the step lowers a cell and never raises it |
| `relax` | work cell | the height after the talus limit (`rest`, `rate`) and `creep` between the four neighbours; with `keep` 1 the limit is the steeper of `rest` and the slope the two cells had when the run began, and creep evens out only the change |
| `up` | held cell of the field | the work grid read bilinearly, `src * scale - subtract * aux` |
The step never lowers a cell past the neighbour it drains to, so a long run settles instead of running away. A depression with no lower neighbour keeps its water: its area stays in it and nothing cuts it.
With `keep` 1 the run keeps the shape it started from wherever the cutting does not reach: a closed basin holds its depth, since the filled surface steers the drainage across it without raising its floor, and a face steeper than the talus limit stands.
·computeshader · born here
❒asset # terrain_erode_talus
Debris shed by steep faces and settled at its angle of repose, on a grid of at most a few hundred cells a side: the passes `terrain.erode` runs for `model = "talus"`.
The ground is rock under a layer of loose debris. Rock holds any slope; debris holds the angle of repose and no steeper. A face steeper than the repose turns some of its rock to debris in place, and the debris runs down to the ground below it and piles there into fans and aprons whose slope is the repose. What a cell sends is exactly what its neighbours receive, so the debris neither grows nor shrinks as it moves.
One dispatch is one pass, picked by the `MODE` specialization, and each pass writes one cell per thread from the buffers of the pass before, so a run gives the same ground every time.
| `MODE` | One thread per | Writes |
|---|---|---|
| `shed` | work cell | the share per metre of excess slope that the cell's debris sends toward each lower neighbour: at most `rate` of the largest excess over the repose, and no more than the debris it holds once `weathering` has turned its share of rock |
| `settle` | work cell | the height (`which` 0) or the debris depth (`which` 1) after the pass: the cell's own debris out, its higher neighbours' in |
A face at or above `cliff` (rise per metre of run) turns all of `weathering` metres of rock to debris each pass that weathers; one between the repose and `cliff` turns its share. The amount varies over the ground by `variation` over `variationSize` metres by the `seed`, so the debris gathers into separate fans below the faces that shed most.
·computeshader · born here
❒asset # terrain_erode_thermal
Talus-angle relaxation over one tile, one iteration per dispatch.
Loose material resting on a slope steeper than its angle of repose slides down.
Repeat that and cliffs grow scree fans at their feet while the crests a droplet
pass leaves knife-edged round off — which is why this is usually the finishing
pass over hydraulic erosion rather than a substitute for it.
The rest angle is a world angle. A cell may stand `tan(talus) * cellSize`
metres above a four-neighbour and still rest, so refining the grid resolves the
same slope rather than changing which slopes are stable.
Each iteration is one dispatch: a cell above the rest angle sheds a fraction of
its excess, split across the neighbours below the angle in proportion to how
far below each one is. Half the excess is the ceiling per iteration, above
which the two cells either side of a step trade places every step instead of
settling.
Changes accumulate through the same fixed-point integer path droplet erosion
uses, so the result is equally independent of the order threads land in.
One thread per INTERIOR cell. The apron is read and never written: an apron
cell belongs to the neighbouring tile, which relaxes it itself, and relaxing it
here as well would move its material twice. Material that slides out of the
interior lands in the apron, and `terrain_delta_gather` carries it into the
neighbour before either tile folds its accumulator into height.
Every op carries a mask, and for a relaxation the mask gates the cell that
SHEDS. A cell the mask holds out keeps its own material, and what it still
receives from an unmasked neighbour is the scree that slope throws past the
mask's edge — material moving downhill, which is what this pass does. An op that
names no mask relaxes at full rate everywhere.
·computeshader · born here
❒asset # terrain_fbm
Domain-warped fractal noise written into one scalar channel of one tile.
Gradient noise with quintic interpolation. Sample positions come from the
field-wide cell index, the field's minimum corner, and the seed, so a tile
evaluated on its own is identical to the same tile evaluated as part of the
whole field — and a cell reached as one tile's apron lands on exactly the
world position it has as its neighbour's interior.
`featureSize` is the world size in metres of the largest noise feature.
Halving `resolution` therefore refines the same landscape instead of
producing a different one.
`warp` is a world distance: how far the domain is displaced by two
lower-octave fields before the main fractal is sampled. Non-zero warp is what
turns isotropic lumps into ridgelines and basins.
`ridge` folds the fractal about zero and squares it, giving sharp crests and
rounded valleys.
`blend` decides how the contribution meets what the channel already holds:
`replace`, `add`, `max`, or `min`.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there — multiplied in, or subtracted out — so the op applies only where
the mask lets it and a cell the mask holds out keeps exactly what it already
held, at every blend mode. An op that names no mask writes at full strength
everywhere.
·computeshader · born here
❒asset # terrain_index
Writes one node's triangles into the terrain's shared index buffer. One thread
per quad, six indices each.
The node's vertices live at `vertexSlot` in the vertex pool and its triangles
land at `writeSlot` in the index buffer. Keeping the two apart is what makes a
cut change cheap: a node that survives a cut keeps its vertex slot, so a cut
that only adds, drops or reorders nodes rewrites indices without re-meshing a
vertex, and re-meshing a node for a moved camera rewrites vertices without
touching an index.
The active cut's indices are written as one contiguous run from index 0, so the
whole terrain — every node, at every level — draws as a single indexed draw.
Winding is CCW seen from +Y, the outward side of a heightfield.
·computeshader · born here
❒asset # terrain_layer
Blends a co-registered raster layer into a scalar channel.
A layer shares the field's grid exactly — same tile, same cell, same apron — so
there is no sampling and no transform involved, only a blend. Compare
`terrain_stamp`, which samples a texture through a world-space transform
because the source has a grid of its own.
That exactness is what lets freehand editing live inside a parametric stack.
Brush strokes accumulate into a layer, the layer is one `layer` op among the
others, and changing an op above it re-runs the stack with the strokes still in
place. Painting is an edit to the layer's raster rather than a bake over the
terrain the ops produced.
`opacity` scales the layer before the blend, so the same raster can be dialled
in and out without repainting it. `blendMode` follows the numbering every
terrain op shares: 0 replace, 1 add, 2 max, 3 min.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there — multiplied in, or subtracted out — so the op applies only where
the mask lets it and a cell the mask holds out keeps exactly what it already
held, at every blend mode. An op that names no mask writes at full strength
everywhere.
·computeshader · born here
❒asset # terrain_layer_weights
Evaluates a material layer stack's rules into two RGBA weight textures — layers
0-3 in one, 4-7 in the other, with the eight shares at a texel summing to one.
One thread per destination weight texel. The dispatch is per tile: a tile writes
the texels whose centres fall inside its interior, reading the field through its
own apron-inclusive buffer. Because every read is placed from the field minimum
and the texel size in world metres — never from the tile's own origin — the
texels one tile writes agree exactly with its neighbour's along the seam.
## The six inputs
| input | unit | where it comes from |
|---|---|---|
| `height` | metres, world Y | the `height` channel, bilinear |
| `slope` | degrees, 0 flat / 90 vertical | central difference of `height` over `gradientStep` metres |
| `curvature` | 1/metres, + gully / − ridge | Laplacian of `height`, magnitude ≈ 1/radius |
| `mask` | 0..1 | a bound `mask.<name>` channel, bilinear |
| `noise` | 0..1 | `terrain_fbm`'s gradient noise over world position |
| `channel` | the channel's own stored values | any bound field channel, bilinear |
`slope` and `curvature` are derived here rather than stored, so they cost no
channel and can never fall behind the ground they describe.
`mask` and `channel` both read a named channel through the same four slots and
the same bilinear tap; they differ in what the band is written against. A mask
channel holds 0..1, so its band is in that range. A `channel` band is in the
values the channel stores — cubic metres of deposited sediment, metres of water
depth, whatever the op that wrote it produces — with no rescaling on the way in.
That is what lets a layer put sand where the water actually dropped it and wet
shore where water actually stands.
## A rule is a band, whatever it reads
Every rule carries `min`, `max`, `softness` and `jitter` **in the unit of its own
input**. A layer covers the ground by its `strength` times the product of its
rules; a layer with no rules covers unconditionally. `invert` takes the
complement of the band, which is how "anywhere but here" is written.
`softness` is a feather half-width and `jitter` is how far noise is allowed to
move the value before it is banded — metres on a height rule, degrees on a slope
rule. Each rule draws its jitter from its own noise offset, so two rules on one
layer do not wander in step.
## The layers are a stack
Working from the top down, each layer takes its coverage share of whatever is
still showing. A cliff rule that fully passes therefore leaves nothing of the
grass under it, a layer at half coverage lets half the layer below through, and
whatever no layer claimed goes to layer 0 — the ground the stack stands on. The
eight shares add to one by construction, with nothing divided by a sum, and an
unclaimed texel is a surface rather than a hole.
Rules are numbered bottom-up across the whole stack and each layer reads its own
range of them, so covering downward moves no rule's noise offset.
## Bindings
`params` carries the whole stack: four head lanes, eight layer lanes, then three
lanes per rule. `height` is the field's height tile. `chan0`..`chan3` are the
field channels the stack's rules name, in sorted order — a slot no rule reads is
bound to the height tile and never sampled. Four is what the kernel declares; a
compute stage carries eight storage buffers and `params` and `height` take two,
so six is the ceiling a stack could be given.
`weightsLo` and `weightsHi` are `rgba8` storage targets, which is the widest
format a material slot can sample: a material reads every slot through a
filtering sampler, and the 32-bit float formats are not filterable.
·computeshader · born here
❒asset # terrain_mask
A soft-band rule over one feature of a raster, written into a named layer.
| input kind | value | unit |
|---|---|---|
| 0 height | the surface's own value | world metres |
| 1 slope | the angle of its gradient | degrees from flat |
| 2 curvature | its Laplacian — positive in a gully, negative on a ridge | 1/metre |
| 3 noise | gradient noise over world position | 0..1 |
| 4 curve | distance to a polyline's sampled control points | world metres |
A band is `min .. max`, feathered by `feather` — a soft half-width in the
input's own unit — on either edge; a side left open (`±1e29`) is not a bound
at all. `jitter` perturbs the sampled value before the band, by up to
`jitter` over a gradient-noise field sized `jitterSize`, so the boundary
wanders instead of tracing a contour. `invert` swaps what the band selects.
The `height`/`slope`/`curvature` inputs are derived from the raster's own
"height" layer, read through `op_source` at the same resolution as the layer
this op writes — one indexed read per cell, no resampling. `slope` and
`curvature` are central differences over `step` world metres.
The `curve` input reads a polyline's sampled control points off `op_payload`
— the same array `terrain.project` rides — and measures distance to it in
the ground plane; a control point's height plays no part in the distance.
`blend` decides how the band's weight meets what the layer already holds:
`replace`, `add`, `max`, or `min`. A layer written fresh is usually
`replace`; combining two masks into one accumulated layer is `add` or `max`.
The written value is a weight in 0..1 — a layer this op writes is what
`terrain.mask`'s `name` param names, and any other raster kernel op's own
`mask` param can reference it by that name, multiplied in or subtracted out,
through the generic `op_mask`/`op_common` contract every raster kernel op
already carries.
·computeshader · born here
❒asset # terrain_mesh
Builds one quadtree node's vertices from the heightfield's texels, in the
engine's 23-word vertex layout, straight into the shared vertex pool the
terrain draws from. One thread per node vertex.
Every vertex stands on a stop of the collider's lattice: the field's two edges
and its texel centres along each axis, the stops the terrain's collider holds
its samples at. The cut is counted on that lattice: a vertex is placed from
whole indices counted from the grid corner, a cell step apart along each axis,
and for a pool over the field's own rect the corner is half a texel outside the
rect and the cell step the texel spacing times a power of two, so a vertex is
already a lattice point and the snap onto the lattice moves none of the
interior ones. A node whose cell step is the texel spacing draws exactly the
collider's cells, split along the diagonal from the corner one texel along +Z
to the corner one texel along +X, which is the split the collider and
`terrainHeightfield.cellHeight` make. Every vertex is held to the rect the cut
tiles, so the vertices past an edge stand on it and draw triangles with no area.
Along an edge stitched to a coarser neighbour, the strip of cells next to the
edge follows the neighbour's edge. A coarser node draws a subset of the same
lattice.
The height of a node at the field's own density is read from the four texels of
the cell around a stop through that same split, and the normal from the
gradient the texels carry, blended across them. A node whose vertices stand
`2^k` stops apart reads level `k` of the heightfield's lattice pyramid instead
(`terrain_pyramid`): one height at every `2^k`-th stop, each a tent over the
level below, with the gradient taken as the central difference of the level over
`2^k` texels. The far end of a vertex's morph is the parent's vertex at the same
stop, one level up, so a node that has finished morphing draws what its parent
holds.
Two edge behaviours make an LOD cut renderable:
- **Stitching.** `coarseMask` names the edges whose neighbour is one level
coarser. On such an edge the odd-indexed vertices snap onto the previous even
one, so the fine edge becomes the polyline through the coarse neighbour's own
vertices. The crack closes because the two edges are then the same line, not
because something covers it.
- **Geomorphing.** Over the far end of the distance band a node is a leaf
across, every vertex slides onto the position it would hold one level coarser.
By the time the cut merges the node into its parent, the node is already
drawing the parent's geometry, so the merge moves nothing. The morph runs off
each vertex's own distance to the camera rather than the node's, so a vertex
two nodes share is placed identically by both.
A vertex stands at one height however many nodes hold it. Along an edge a
coarser neighbour shares, a vertex reads the neighbour's level at both ends of
its morph, so it is the neighbour's own vertex at that point. A corner reads
the coarsest level among the nodes that meet there, which the caller states
for each corner: a node two levels coarser can meet a fine one at a single
point, with no edge between them.
A vertex is placed from its whole index alone, so every node that holds it, and
every child whose vertex morphs onto it, computes the same bits for it and the
same lattice point.
·computeshader · born here
❒asset # terrain_project
A curve drives the ground: the points of the curve a geometry holds ride
`op_payload`, and every cell's height is banded by its ground-plane distance
to the resulting polyline — one dispatch, so the channel it cuts has no seam
where a chain of stamps would have met.
Inside `width`, falling to zero across `falloff` metres beyond it, a cell
blends toward a target height:
- `useCurveHeight` set: the curve's own y at the nearest point on the
polyline — a road or a riverbed that follows the curve's authored
elevation.
- otherwise: `fromHeight` .. `toHeight`, interpolated by how far along the
polyline (ground-plane arc length, 0 at the first control point, 1 at the
last) the nearest point falls — a ramp that runs the whole curve's length
in one dispatch instead of one `ramp` stamp per segment.
`blend` decides how the target height meets what the layer already holds:
`replace`, `add`, `max`, or `min`.
The polyline is open — segment `i` to `i+1` for every consecutive pair of the
curve's sampled points — and distance and arc length are both measured in
the ground plane; a point's height does not distort either.
·computeshader · born here
❒asset # terrain_pyramid
Writes one level of a heightfield's lattice pyramid from the level below it,
one thread per level point.
The heightfield's texels are level 0, read along the lattice the terrain's
collider stands its samples on (the field's two edges and every texel centre
between them, or, for a field whose first and last texel stand on the edges of
the rect it is drawn over, the texels themselves). Level `k` holds one height
at every stop `m * 2^k` of that lattice. Each is the separable tent
[1/4, 1/2, 1/4] over the previous level's stops `2m - 1`, `2m` and `2m + 1`, and
a stop past an end of a level reads the level's last one. A level's stops are
stops of the level below, so a coarse node of the mesh draws the even vertices
of the node one level finer, filtered over the ground between them.
A stop on the field's own edge filters along the edge only, so two fields that
meet along an edge and hold the same heights there hold one value at every
coarse stop of it. The four corners keep the corner texel's height.
A dispatch writes the rect of destination points its parameters state: the
whole level when the pyramid is built, and the points an edit reaches when it
is rebuilt. Levels are dispatched in order, each reading the one the dispatch
before it wrote.
·computeshader · born here
❒asset # terrain_scatter_density
Evaluates one scatter rule into a density channel: **instances per square
metre** at every cell of one tile.
The unit is what makes a rule portable. An author asks for one tree per fifty
square metres and gets that count whether the field is sampled at half a metre
or at four, and whether the terrain is 512 m across or 4 km.
## The rule inputs are the material stack's inputs
| Input | Where it comes from |
|---|---|
| height | the surface channel's own value, world metres |
| slope | the angle of its gradient, radians |
| curvature | its laplacian, 1/m — positive in gullies, negative on ridges and crests |
| mask | a co-registered raster, multiplied in or subtracted out |
| noise | gradient FBM over world position, so a forest edge is not a contour line |
Each band contributes a weight in `0..1` and the weights multiply. A rule that
sets one band and leaves the rest open is exactly that one band, so an author
who understands one understands all of them.
The density written is the peak density times the product of the weights.
## The region
`atX/atZ`, `radius` and `falloff` bound where the rule applies at all, in world
metres. A radius of **zero** covers the whole field — what a ground cover
wants. Outside the region the shader writes nothing, so a second rule's density
on that cell stands.
## The mask slot
`maskMode` picks what the mask raster does:
| mode | effect |
|---|---|
| 0 | multiply — the rule applies only where the mask is painted |
| 1 | subtract — the rule is kept OUT of where the mask is painted |
| 2 | none — the binding is not read |
Subtract is how an authored `place` op's `clearing` keeps a scattered forest
out of the ground a landmark stands on: the placement writes its footprint into
the `placement` channel and the scatter rule subtracts it.
A binding has to point somewhere, so at mode 2 the caller binds the height
channel into the mask slot and the shader never reads it.
One thread per cell, apron included. The cell's world position comes from the
field-wide cell index and the field's minimum corner, so a cell reached as one
tile's apron resolves to the same density as the same cell reached as its
neighbour's interior.
## The op contract's mask
This kernel carries no `op_mask` / `op_common`. Those bind the mask every op
that writes GROUND is scaled by, and this one writes a density channel — it has
the `mask` binding above, with modes and a gain of its own, which is the mask a
scatter rule reads. The two are separate surfaces on purpose.
·computeshader · born here
❒asset # terrain_scatter_place
Turns one tile's density channel into instance transforms in the shared pool
`renderer.mesh.drawInstanced` reads.
One thread per candidate **site**, not per cell.
## Sites are world-anchored
The sites are a grid of `spacing` world metres running from the field's minimum
corner. A site belongs to exactly one tile — the one its centre falls in — so
the same field produces the same sites whatever the tiling, whatever the
resolution, and however much of the field is being re-evaluated.
A site carries an instance with probability `density * spacing^2`. That is what
makes the density channel mean **instances per square metre**: summed over the
sites of an area, the expected count is the integral of the density over it.
One site carries at most one instance, so `1 / spacing^2` is the densest cover
a spacing can express. `terrainScatter` derives the spacing from the density
the rule actually reaches rather than letting a caller find that ceiling by
hitting it.
## Determinism
Acceptance, the jitter inside the site, the yaw and the scale are all hashes of
the site's integer grid indices and the seed. The instance a site carries is
therefore the same instance every run: a reload does not reshuffle a forest,
and re-evaluating one corner of the field leaves the rest of the population
exactly where it stood.
Slots in the pool are handed out by an atomic, so **which** slot an instance
lands in varies between runs. The set of instances and each one's matrix do
not.
## Overflow is a resize, not a short forest
When the accepted count runs past `capacity` the counter keeps counting and the
extra instances are not written. The total it reports is what the caller grows
the pool to before running the pass again, which is how a population that grew
past its reservation ends up complete rather than silently clipped.
## The matrix layout
Column-major 4x4, four `vec4` columns per instance, tightly packed — the layout
a vertex shader reads as `array<mat4x4<f32>>`. Columns 0..2 are the basis
scaled by the instance's scale; column 3 is the translation.
## The op contract's mask
This kernel carries no `op_mask` / `op_common`. Those bind the mask every op
that writes GROUND is scaled by, and this one writes instance transforms. Where
a population may grow is already decided by the density channel it reads, and
`terrain_scatter_density` is where a mask shapes that. The separation is on
purpose.
·computeshader · born here
❒asset # terrain_shape
Blends an analytic shape into one scalar channel of one tile.
One shader covers every placed primitive, selected by a mode lane:
| mode | shape | what it draws |
|---|---|---|
| 0 | disc | a circular pad held at one altitude |
| 1 | square | the same, measured in the Chebyshev metric |
| 2 | cone | a rounded hill, cosine profile, tangent to flat at the rim |
| 3 | ridge | that profile swept along a segment |
| 4 | ramp | an altitude interpolated along a segment |
| 5 | terrace | the existing height quantized into steps |
A negative height on a `ridge` cuts the same profile downward, which is how a
valley or a sunken road corridor is drawn.
The shape's coverage at a cell is a weight in 0..1 — full inside `radius`,
falling to zero across `falloff` metres beyond it — and that weight is what the
blend is applied through. A flatten therefore settles into the terrain rather
than stamping a cliff-edged plateau into it.
Every coordinate is world metres. A shape about a point puts that point in both
segment endpoints; a shape along a line puts the two ends in them. `radius` is
the half-width for the segment shapes. Because nothing here is in cells, the
same op covers the same ground at any resolution.
`blend` decides how the shape's value meets what the channel already holds:
`replace`, `add`, `max`, or `min`. The rounded shapes read best with `add`,
which lays a hill on top of the terrain instead of replacing it; the level
shapes read best with `replace`.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there — multiplied in, or subtracted out — so the op applies only where
the mask lets it and a cell the mask holds out keeps exactly what it already
held, at every blend mode. An op that names no mask writes at full strength
everywhere.
·computeshader · born here
❒asset # terrain_stamp
Blends a source texture into a scalar channel under a world-space transform.
The source is an ordinary `.texture`. That is the point: importing a real-world
elevation model and placing an authored shape are the same operation, so there
is one path for both and no separate importer.
Sampling runs in world space. Each destination cell's world position is carried
into the stamp's local square — translated to `at`, rotated by `rotation`,
scaled so the square spans `radius * 2` metres — and the texture is read there.
A cell outside that square is left untouched, so the op's declared extent is
exact and the evaluator dispatches only the tiles the stamp reaches.
`channelIndex` picks which of the texture's four channels carries the value;
`amplitude` scales it into metres and `bias` offsets it, so an 8-bit greyscale
heightmap in 0..1 becomes real elevation. `falloff` feathers the disc inscribed
in the square, which is what lets a stamp meet the surrounding terrain without
a seam.
Compare `terrain_layer`, which blends a raster that already shares the field's
grid and therefore needs no sampling at all.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there — multiplied in, or subtracted out — so the op applies only where
the mask lets it and a cell the mask holds out keeps exactly what it already
held, at every blend mode. An op that names no mask writes at full strength
everywhere.
·computeshader · born here
❒asset # terrain_water
Fills a water surface over a region of one tile, into the `water` and
`waterMask` channels.
One shader covers every water body, selected by a region-mode lane:
| mode | region | what fills |
|---|---|---|
| 0 | disc | a round body about a point — a lake |
| 1 | square | the same, measured in the Chebyshev metric |
| 2 | path | a body swept along a segment, its surface running from one end's level to the other's — a river |
| 3 | everywhere | the whole field — a sea |
A cell takes the surface only where the ground stands **below** it, so a body
fills the basins its region reaches and leaves ground that rises out of it dry.
That is the whole difference between a lake and a sea: the region an op is
applied to.
## The two channels are one thing
| channel | what it holds |
|---|---|
| `water` | the world-space Y of the surface covering that cell |
| `waterMask` | 1 where a surface covers the cell, 0 where none does |
A mask of 0 is what "no water here" IS — there is no height in the `water`
channel standing in for it, so no authored water level can ever be mistaken for
an absence. Everything that reads water reads the pair.
## Bodies meet through `blend`
Where two bodies reach one cell, the second meets the first through `blend` —
`replace`, `add`, `max` or `min`. The default `max` makes the meeting
independent of authoring order: the higher surface wins whichever op ran first,
so a lake in a coastal basin reads the same whether it was placed before or
after the sea.
Every coordinate and every level is world metres, so a body keeps its size, its
place and its altitude when the field's resolution changes.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there, and here the water mask channel is what carries that coverage: a
cell the mask holds out keeps both channels as they stand, and a partly covered
cell holds part of the surface it already had. An op that names no mask fills at
full strength everywhere.
·computeshader · born here
❒asset # terrain_water_kernel
Fills a water surface over a region of one tile, into the `water` and
`waterMask` layers of a `proc.raster` `Raster` — `terrainOps.water`'s
`lake`, `river` and `sea` share this one dispatch.
One shader covers every water body, selected by a region-mode lane:
| mode | region | what fills |
|---|---|---|
| 0 | disc | a round body about a point — a lake |
| 1 | square | the same, measured in the Chebyshev metric |
| 2 | path | a body swept along a segment, its surface running from one end's level to the other's — a river |
| 3 | everywhere | the whole raster — a sea |
A cell takes the surface only where the ground stands **below** it, so a body
fills the basins its region reaches and leaves ground that rises out of it dry.
That is the whole difference between a lake and a sea: the region an op is
applied to. The ground it reads is `op_source`, bound to the raster's
`height` layer.
## The two layers are one thing
| layer | what it holds |
|---|---|
| `water` | the world-space Y of the surface covering that cell |
| `waterMask` | 1 where a surface covers the cell, 0 where none does |
A mask of 0 is what "no water here" IS — there is no height in the `water`
layer standing in for it, so no authored water level can ever be mistaken for
an absence. Everything that reads water reads the pair.
## Bodies meet through `blend`
Where two bodies reach one cell, the second meets the first through `blend` —
`replace`, `add`, `max` or `min`. The default `max` makes the meeting
independent of authoring order: the higher surface wins whichever op ran
first, so a lake in a coastal basin reads the same whether it was placed
before or after the sea.
Every coordinate and every level is world metres, so a body keeps its size,
its place and its altitude when the raster's resolution changes.
Every op carries a mask. The op's weight at a cell is scaled by what the mask
reads there, and here the water mask layer is what carries that coverage: a
cell the mask holds out keeps both layers as they stand, and a partly covered
cell holds part of the surface it already had. An op that names no mask fills
at full strength everywhere.
·computeshader · born here
❒asset # terrain_water_mesh
Builds one node of the water surface from the `water` / `waterMask` channels,
into the same 23-word vertex layout and the same slot-addressed pool
`terrain_mesh` writes.
## The baked column
Alongside altitude, each vertex bakes the WATER COLUMN — how far the surface
stands above the bed — into the vertex colour's red channel (word 19):
`max(water - height, 0)` where covered, `0` where not, and a sentinel standing
for open ocean on a flat skirt vertex, which has no channel to measure
against. `terrainWater.shader` reads it back as an interpolated attribute
instead of reconstructing it from the scene depth buffer, which a plain
material draws with no depth copy behind it.
## Where a vertex's altitude comes from
| the cell under the vertex | y |
|---|---|
| covered by water | `water` — the surface itself |
| not covered | `min(water, height - sink)` |
The uncovered branch is what ends the surface at the shore. `height - sink` is
under the terrain by construction, so a vertex with no water above it is buried
whatever the water channel holds there; taking the lesser of the two keeps the
plane flat right up to the last covered vertex, so the waterline falls where
the plane and the ground cross rather than on a node boundary.
Coverage is read from the nearest cell rather than interpolated: a cell either
carries a surface or it does not, and half-covered is not a state the surface
has.
## The skirt
A node with `flat` set reads no channel and sits at `flatLevel`. That is the
outer skirt — the ring of nodes carrying the sea from the field's rect out to
the horizon, so an island has water all the way around it instead of stopping
at the grid. Skirt vertices meet the rect's edge vertices at exactly the sea
level, which is what makes the join seamless rather than merely close.
Because the skirt's edge pieces are as long as the field and as deep as the
horizon is far, a node here is a **rectangle**: `nodeSizeX` and `nodeSizeZ` are
separate.
## Stitching
Boundary stitching is the same rule as `terrain_mesh`: on an edge whose
neighbour is one level coarser, the odd boundary vertices snap onto the
previous even one. There is no geomorph — a level surface has nothing to pop.
# terrain guide
The terrain system's reference guide: a landscape composed in code as a procgen graph
— the `Raster` the `terrain.*` ops pass along, the source → shape → mask → realize
shape of a terrain graph, every op in the family, and a worked valley with a river.
Surfaced through `guides { query: "terrain" }` and
`guides { path: "systems/terrainSystem/documentation/terrain" }` (likewise `man`). The
content lives in `guide.md`; this README is the asset summary.
The hand-authoring face of the same system is the `terrain` toolbox
(`search_tools terrain`), which carries its own README.
# terrainSplat (material)
The eight-layer terrain surface. Blends three layer atlases — albedo, normal,
mask — by the two RGBA weight textures the landscape was baked with.
## You normally do not apply this material yourself
`terrainSurface.forLandscape(data)` instances it per landscape: the
`.terrainData`'s control textures bound as the weight maps, its rect as
`terrain_field_min` / `terrain_field_size`, its layer slices as the three atlases, and its
layer table as the per-layer tints and tilings. What you apply is the handle
that call returns — and a `Terrain` component does even that for you.
This asset is the same shader with defaults, so it is inspectable and it is what
a hand-authored variant starts from. Applied by hand it has no weight textures
and no field rect, so it renders **layer 0 everywhere** — an unbound stack looks
unbound rather than looking broken.
## Properties
| Property | Unit | What it does |
|---|---|---|
| `terrain_field_min`, `terrain_field_size` | metres | the rect the weight textures cover; zero size means no weight map |
| `terrain_normal`, `terrain_normal_strength` | — | the landscape's own normal per pixel, and how far a pixel takes it over the vertex normal (1 takes it, 0 keeps the vertex normal) |
| `terrain_morph_band_start` | — | where a vertex begins sliding onto its parent's position, as a fraction of its distance band |
| `terrain_cut_eyes_a`, `terrain_cut_eyes_b`, `terrain_cut_eye_count` | — | the points the ground's LOD cut was taken for, which the geomorph measures each vertex from |
| `terrain_weights_lo`, `terrain_weights_hi` | — | layers 0-3 and 4-7, normalised to sum to one; read through a cubic B-spline, so an edge between two layers is a smooth curve through the texels |
| `layer_atlas_albedo` / `_normal` / `_mask` | — | 4x2 atlases, layer N at (N mod 4, N div 4) |
| `atlas_size` | texels | atlas dimensions, for the half-texel inset between cells |
| `layerN_tint` | — | multiplies layer N's albedo sample |
| `layerN_size` | metres | world metres one repeat of layer N's texture covers |
| `weight_sharpen` | — | 1 is the stack as evaluated; higher narrows every transition without moving it |
| `height_blend` | — | 0 blends by weight alone; higher gives a contested pixel to whichever layer stands highest at its weight plus its relief, sharing it with the layers within `1 / height_blend` of that |
| `normal_strength` | — | scales the blended tangent-space XY; 0 is flat |
| `smoothness`, `metallic` | — | scale the mask atlas's alpha and red |
## The mask atlas
Each cell is a mask MAP in the usual channel order: **R metallic, G ambient
occlusion, B height, A smoothness**. White is the neutral one — no occlusion, a
level height, and metallic and smoothness left to the two scalars.
The height channel is what makes a transition look like two materials meeting
rather than a crossfade: where the weights come near a tie, `height_blend`
gives the pixel to the layer standing highest at its weight plus its height
there, so sand settles into the gaps between cobbles instead of fading evenly
across their faces. A layer standing within `1 / height_blend` of the highest
shares the pixel by how near it stands, which is what keeps the edge soft.
A layer's height is read as RELIEF: about the slice's own mean (its coarsest
mip), so the edge falls where the weights cross and wanders across that
crossing along both surfaces' shapes, whatever scale each texture states its
height on. A layer with no mask map reads its relief from its albedo's light
and shade about the slice's mean luminance — light faces stand proud, dark
cracks sink — so a rock without a mask still takes sand into its cracks.
Layers standing level meet along the line where their weights cross.
## Three atlases, not twenty-four slots
A slot per layer per map would put twenty-four sampled textures in one bind
group, which is past what WebGPU guarantees a shader stage. The atlas keeps the
cost at three whatever the layer count is. `terrain.write` packs the sheets when
it bakes a landscape — a layer names its own `albedo` / `normal` / `mask`
textures and they are resampled into that layer's cell — so the packing is not
something an author does by hand.
A stack with no atlas at all renders its eight `layerN_tint` colours, which is
enough to see every rule working.
# terrainStandard (material)
The default material for the terrain system. It is the
`~terrainSystem.shaders.terrainSplat` shader with `ground_fill` at 1 and no
layer bound, so the whole ground is the share no layer claims and is painted by
altitude and slope: four colour bands climbing with height, a cliff over steep
faces, noise breaking each band's edge and a slow macro variation
(`zero_terrain_ground_bands`). A landscape that states its vertical reach (a
`.terrainData` does) has the bands begin at fractions of it (`ground_altitudes`,
0.18, 0.5 and 0.78 of the relief), so the same ground reads alike on a hill and
on a massif; the peak's snow is drawn only where the ground lies down. It carries the shader's geomorph hook and shades
with the landscape's own normal per pixel.
## Bands
| Slot | Property | Default | Role |
|------|----------|---------|------|
| 0 (valley) | `layer0_color` | green | Low ground, grass, valley floor. |
| 1 (mid) | `layer1_color` | tan | Mid-band: dry grass / scrub between grass and rock. |
| 2 (high) | `layer2_color` | grey | High band: rock, exposed cliff face. |
| 3 (peak) | `layer3_color` | white | Peaks: snow, ice. |
| cliff | `cliff_color` | dark brown | Steep faces, whatever the altitude. |
## Tunables
| Property | Role |
|----------|------|
| `ground_altitudes` | Fractions of the landscape's relief where the mid, high and peak bands take over. |
| `layer1_height`, `layer2_height`, `layer3_height` | World Y where the bands take over, for a landscape that states no relief. |
| `blend_width` | Width of each altitude transition, for a landscape that states no relief. |
| `slope_start`, `slope_end` | Cosine of the surface normal's Y where the cliff blend begins and where it fully overrides. |
| `detail_scale`, `detail_amp` | Frequency and strength of the noise breaking each band's edge. |
| `macro_scale` | Frequency of the macro variation. |
| `smoothness`, `metallic` | Surface response. |
Authors who want different colours or heights override the respective
`floats.` / `colors.` blocks in their own material on `terrainSplat`.
## Customizing per terrain
```lua
asset.create("material", "alpine_meadow", {
shader = "@builtin::systems.terrainSystem.shaders.terrainSplat",
properties = {
ground_fill = 1,
layer0_color = { 0.18, 0.45, 0.22, 1 }, -- meadow green
layer1_color = { 0.35, 0.42, 0.30, 1 }, -- scrub
layer2_color = { 0.55, 0.55, 0.55, 1 }, -- granite
layer1_height = 12, layer2_height = 24, layer3_height = 38,
},
})
```
# terrainWater
The material a terrain field's water surface draws with — lakes, rivers, the
sea, and the skirt that carries the sea past the field's rect.
It is a plain transparent PBR body of water with no simulation behind it, which
is what makes it correct at every scale the surface is used at: a pond, a river
reach and a horizon all read the same. `terrainSystem.spawn` applies it to a
terrain's water entity unless `waterMaterial` names another.
It draws in the transparent queue after the terrain, with both faces, so the
ground under the surface is already in the frame and the same material is the
underside once the camera goes below the waterline.
Reach for the Tidewater water kit on ZeroMind (package `tidewater`) instead when
the water is the subject — its `WaterBody` with `kind = "ocean"` simulates a
spectrum, whitecaps and shore foam, and wants an ocean rather than a terrain's
water table.
# terrainHeightfield
A `.texture` standing over a rect of world, read as ground.
The durable form of a landscape is an ordinary texture asset — one with a guid,
that a component references, that travels with a world, that the renderer
already knows how to sample. `terrain.to_texture` is what puts a graph's raster
into one and `texture.write` persists it. This module is the other end: what a
runtime holds while that ground is on screen.
```lua
local terrainHeightfield = require("~terrainSystem.modules.terrainHeightfield")
-- A `.terrainData` states the rect it covers, so opening one needs nothing else.
local hf = terrainHeightfield.open("/zero/source/terrain/dunes.terrainData")
-- The heightfield alone can be read too; then the caller says where it stands.
local bare = terrainHeightfield.open(tex, { size = { 4000, 4000 }, origin = { 0, 0 } })
local y = hf:heightAt(120, -60) -- metres
local nx, ny, nz = hf:normalAt(120, -60)
local slope = hf:slopeAt(120, -60) -- radians
hf:close()
```
## The texels
`rgba32f`, in the layout `terrain.to_texture` writes:
| Channel | Holds |
|---|---|
| R | the height, in METRES — it goes negative |
| G | the gradient along world X |
| B | the gradient along world Z |
| A | coverage |
A height's interesting relief is often a few metres inside a range of hundreds,
so eight bits band it into terraces; that is what the precision is for. The
gradient is what a surface normal comes out of without differencing the height
four more times, and it is why `terrain_mesh` costs four texel reads a vertex
rather than twenty.
A heightmap authored anywhere else — an 8-bit image, a downloaded elevation
tile, a raster an earlier graph baked — becomes one of these by going through a
graph: `terrain.from_texture` reads it as ground, and `terrain.to_texture`
writes the result back out at this precision.
## The lattice pyramid
A heightfield also holds a pyramid of coarser levels, built when it opens on the
GPU from the texels (`terrain_pyramid`). Level 0 is the texels, read along the
lattice the terrain's collider stands its samples on; level `k` holds one height
at every `2^k`-th stop of that lattice, each the tent [1/4, 1/2, 1/4] of the
level below at the three stops it spans. A mesh node whose vertices stand `2^k`
stops apart draws level `k`, so far ground is the filtered ground around each
vertex. A stop on the field's own edge filters
along the edge only, so two fields that meet along an edge and hold the same
heights there hold one value at every coarse stop of it.
The stops stand on one of two anchors. `"lattice"`, the default, is the field's
own lattice: stop 0 the near edge of its rect, stop `i` the centre of texel
`i - 1`, the far edge stop `texels + 1`. `"texel"` is a field whose first and
last texel stand on the edges of the rect that is drawn, as a streamed tile's
do: stop `i` is texel `i`. `open` and `fromHeights` take `anchor`; a field that
meets the other kind of mesh builds that pyramid when `pyramidFor` asks.
`hf.pyramid` is the pyramid the field opened with, `hf.pyramidLevels` its levels
from level 1 as `{ offset, cols, rows }`, and `hf.pyramids` every one held by
anchor. A field of 832 x 832 texels holds ten levels in 0.9 MiB, and one of
4096 x 4096 about 22 MiB. `setHeights` filters again only the points an edit
reaches, a point more on every side at each level; `refresh` filters all of
them; `close` frees them.
## Two carriers, one set of texels
An open heightfield holds the texture in both forms the runtime reads it in:
- **`hf.texels`** — a GPU buffer of the texel bytes, which the
`terrain_mesh` compute kernel builds vertices out of.
- **`hf.cpu`** — the pixels, which `heightAt` / `normalAt` / `slopeAt` /
`sampleGrid` answer from.
Both are the same texels, uploaded from one read, so what the ground LOOKS like
and what a query SAYS about it cannot drift apart.
The pixels are the heightfield's own copy, decoded from the asset when it opens
and held in a buffer for as long as it stands, and so are its holes mask, its
water surface and its layer weights. A heightfield answers in edit, in play and
after play, whatever else loads or unloads the same texture. The cost is one
copy a heightfield: 16 bytes a texel for the heights and the water, 4 for the
holes mask and each layer-weight texture. Two heightfields open on one landscape
hold two copies, which is also what keeps an edit to one (`setHeights`) to
that one.
## The surface
| Verb | |
|---|---|
| `open(ground, opts?)` | Read a `.terrainData` — or the heightfield `.texture` alone — as ground. A container carries its own `{ size, origin, heightRange }`; a bare texture takes them from `opts`, and an explicit opt outranks the container either way. |
| `hf:heightAt(x, z)` | Metres: the texel cell around the point read through `cellHeight`, the surface the terrain's collider holds. |
| `hf:normalAt(x, z)` | Unit normal, three numbers, from the carried gradient. |
| `hf:slopeAt(x, z)` | Radians; 0 is flat. |
| `hf:sampleGrid(cols, rows)` | Row-major heights over the whole rect at any sample count, read through `heightAt`. |
| `hf:colliderTiles(perTile?)` | The heightfield collider tiles that hold this ground exactly: samples on the texel centres, a half-texel strip out to each edge. Each tile is `{ minX, minZ, sizeX, sizeZ, xs, zs }`. |
| `hf:texelLattice(xs, zs)` | Row-major heights of the texels at the named columns and rows, as they are: a tile's grid from `colliderTiles`. |
| `terrainHeightfield.cellHeight(h00, h10, h01, h11, fx, fz)` | The ground inside one cell from its four corner heights. |
| `hf:hasGroundAt(x, z)` | Whether there is ground at all — false over a hole. |
| `hf:refresh()` | Read the texture's pixels again and put them back on the GPU. Bumps `gen`. |
| `hf:close()` | Let go of the pixels and the GPU buffer. The asset is untouched. |
`heightRange` is the vertical reach the geometry declares, which becomes the
mesh's bounding box — a range smaller than the ground culls the terrain away at
grazing angles. Left out, it is read off the pixels, which costs one pass over
them.
## One surface
The ground between texel centres is two flat triangles a cell, split along the
diagonal from the cell's corner one texel along +Z to its corner one texel along
+X: the split a Rapier heightfield collider makes, so a collider built from
`colliderTiles` meets a ray at the height `heightAt` answers there, to float
precision. The `terrain_mesh` kernel stands every vertex on a stop of the
collider's lattice (the rect's edges and the texel centres), and the mesh cuts
that lattice, so its finest node, a vertex at every texel centre, draws the
collider's own triangles (save the strip along an edge stitched to a coarser
neighbour, which follows that neighbour's edge), and a coarser one differs from
it only by the level of detail it is cut to.
Past the outermost texel centres the ground runs level out to the rect's edge,
for the query, the collider and the mesh alike.
## Holes
A landscape can be CUT OUT — a cave mouth, a quarry, a shaft — and its holes
mask is carried the same two ways the heightfield is: on the GPU for the index
kernel, which writes the quads it cuts out as degenerate triangles, and on the
CPU for `hasGroundAt`. Same pixels, so a place with no surface to draw is a
place nothing can be stood on either, and scatter that asks before it places
never drops a tree into a shaft.
A landscape with no mask is solid everywhere and answers `hasGroundAt` true
without reading anything. The edge of a hole follows the mask at the density the
node is meshed at, so a hole is quad-shaped at the LOD it is seen from.
## Generations
`hf.gen` counts the times the texels have been read. `terrainMesh` records the
generation each node was meshed at, so re-authoring the ground under a standing
terrain and calling `hf:refresh()` brings the geometry with it — nobody has to
say which nodes changed.
# terrainMesh
Puts a heightfield on screen as **one draw**.
## What it is
A vertex **pool** of `maxNodes` slots, each a fixed `nodeVerts` square grid
(33x33 by default). A quadtree **cut** decides which parts of the ground are
drawn at which density: near nodes are small and dense, far nodes large and
sparse, and every node meshes to the same grid, so a node costs the same
wherever it is and the cut stays a few hundred nodes at any camera distance.
`terrain_mesh` fills the slots the cut needs; `terrain_index` writes the index
run over them; `renderer.mesh.create { vertexBuffer, indexBuffer }` turns the
pair into one mesh. One entity carries one `Model` bound to it, so the whole
terrain — every node, at every level — is one indexed draw.
**Nodes are never entities.** Entity count is the binding constraint on this
renderer; a per-chunk entity would put a hundred draws where this puts one. A
step that seems to need one is a step that has the design backwards.
A cut change calls `renderer.mesh.update` under the **same guid**, so the Model
is never re-bound and the scene graph is never touched.
## Using it
```luau
local terrainHeightfield = require("~terrainSystem.modules.terrainHeightfield")
local terrainMesh = require("~terrainSystem.modules.terrainMesh")
local hf = terrainHeightfield.open(groundTexture, { size = { 2048, 2048 } })
local mesh = terrainMesh.create(hf, { camera = terrainMesh.cameraPosition() })
terrainMesh.updateCut(mesh, hf, { x = 900, y = 30, z = 900 })
```
The `Terrain` component does all of this from a `.texture` on an entity and
follows the on-screen camera with the cut every frame, in edit and in play
alike. Reach for the module directly only when the ground is not an entity's.
## The vertices
`terrain_mesh` writes the engine's 23-word vertex layout, one thread per node
vertex, positions in WORLD space — so the entity carrying the mesh stands at the
world origin with no transform of its own.
It reads the heightfield's texels as one array over the whole rect. The height
is the texel cell around a position read as two flat triangles, split along the
diagonal from its corner one texel along +Z to its corner one texel along +X:
the surface `terrainHeightfield.cellHeight` answers and the terrain's collider
holds.
Every vertex stands on a stop of the collider's lattice: the rect's two edges
and the texel centres along each axis. A pool over the field's own rect cuts
that lattice. Index `i` along an axis stands at `fieldMin + (i - 0.5) * step`:
index 0 is the near edge, 1 to N the texel centres, N + 1 the far edge. The
finest node is `nodeVerts - 1` (32) lattice steps across and every other node,
and every root (`quadtree.latticeRoots`), is that times a power of two, so
every vertex of every level is a lattice point and the kernel's snap onto the
lattice moves none of them. The finest level draws exactly the collider's
cells, split along the diagonal the collider splits them along, and a point
anywhere on its triangles stands at the height a body rests at and `heightAt`
answers, save the strip of cells along an edge stitched to a coarser
neighbour, which follows that neighbour's edge. A coarser node draws a subset
of the same lattice, and differs from the ground by its level of detail alone.
A vertex past the rect's edge stands on the edge, so the half-texel strips are
level and a node of a root grid that reaches past the rect draws only the part
the rect holds.
That cut counts lattice steps from the lattice's corner: `state.grid` is that
corner in metres (half a texel outside the rect), `state.unit` the metres to
one step along each axis, and `terrainMesh.nodeRect(state, node)` a node's rect
in metres. A pool over a `rect` of the field (a tile of a streamed landscape,
whose edge texels stand on its edges) counts metres from that rect's corner.
A vertex is placed from whole indices counted from the corner of the grid the
cut stands on, in steps of its node's vertex spacing, so a vertex two nodes
share (across an edge, or a child's vertex and the parent's it morphs onto) is
computed from the same numbers by both and lands on the same lattice point. A
cut whose nodes do not stand on that grid is refused by name. A cut that
overruns the pool at the split distance asked for is taken again at a lower
one, down to 1.5, before any level is dropped, so the finest level stays under
the camera and the far ground coarsens; the distance the cut used is
`cut.splitDistance`, and the geomorph band of each vertex follows it. The
normal comes from the gradient those same four texels already carry, blended
across them: four reads a vertex rather than the twenty a central difference of
the height would cost.
## Holes
`terrain_index` writes one node's triangles, and a quad whose ground the
landscape cuts out is written DEGENERATE — six copies of one index — rather than
left out. The run is a fixed stride per node, so a quad that vanished would
shift every quad after it; a triangle whose three corners are one point covers
no pixels and is discarded before it rasterises. A hole therefore costs the
index slots it already owned and nothing else.
The quad's own centre decides, so the edge of a hole follows the mask at the
density the node is meshed at. The run carries the heightfield's generation as
well as the slot order, so a mask re-read under a standing terrain moves the
hole with it.
## Cracks and popping
Two things happen at node edges, and both are in `terrain_mesh`:
- **Stitching.** The cut is *balanced* — no leaf borders a neighbour more than
one level coarser — and each node carries the mask of which of its four edges
do. On such an edge the fine node's odd-indexed vertices snap onto the
previous even one, so the fine edge becomes the polyline through the coarse
neighbour's own vertices. The two edges are then the same line.
- **Geomorphing.** Over the far end of the distance band a node is a leaf
across, its vertices slide onto the positions they would hold one level
coarser. By the time the cut merges the node into its parent, the node is
already drawing the parent's geometry. The morph runs off each vertex's own
distance to the camera, so a vertex two nodes share is placed identically by
both.
- **Filtering.** A node whose vertices stand `2^k` lattice steps apart reads
level `k` of the heightfield's pyramid, so far ground is a smoothed surface.
A vertex on a stitched edge reads the coarser
neighbour's level at both ends, and a corner reads the coarsest level of the
nodes that meet there, so every node that holds a vertex draws it at one
height. A pool over a `rect` reads the pyramid stood on the field's texels.
## What re-meshes, and when
A node is re-meshed when it is new to the cut, when its coarse-neighbour mask
or the levels at its corners change, when the camera moves (the geomorph is camera-relative), or when the
heightfield's `gen` has moved past the generation that node was last built at.
Nothing else touches it — `updateCut` from a viewpoint the cut was already taken
from remeshes zero nodes and reports `changed = false`.
`terrainMesh.invalidate(state, rect)` marks the nodes overlapping a world rect,
for when something changed the ground in one place.
## Nodes that are not drawn
`create` takes a `keep` predicate — `(node) -> boolean` — and the cut then
covers whatever it keeps rather than the whole rect. That is what lets the
terrain END before the grid does: an island's seabed is ground nobody can see,
and ground nobody can see is ground nothing has to mesh.
The predicate is a parameter of selection rather than a filter applied
afterwards, because the node budget is spent on what is **drawn**: a cut that
coarsened to fit nodes it then threw away would be spending the budget on
seabed. It runs after the tree is balanced, so what it drops cannot unbalance
what remains, and a node whose coarser neighbour was dropped has nothing on
that side to crack against.
## Ground that is not square
A pool over the field's own rect roots its lattice: `width + 1` by `height + 1`
steps, in squares of `nodeVerts - 1` times a power of two steps, the smallest
whose grid holds at most a quarter of the pool (an 832-texel field at 1 m roots
as seven 128-step squares a side). What follows is the metres rects: a pool
given a `rect`, and `quadtree.select` without a `unit`.
The quadtree tiles the rect with square **root** nodes, and every rect of any
width and depth has a root grid (`quadtree.rootGrid`). A square rect is one
root. An oblong one roots on the largest measure both sides divide into while
that measure is at least `minNodeSize` and the grid holds at most a quarter of
the pool (an 800 x 600 m rect roots as twelve 200 m squares). Otherwise the
root is the shorter side, or the longer side over that quarter if larger, and
the grid **covers** the rect: its last row or column reaches past the far
edge. A cut leaves out every node standing wholly past the rect, a node
across its edge refines by the distance to the part of it the rect holds, and
the mesh puts that node's vertices past the edge on the edge, so the ground
ends exactly where the rect does. A 210 x 170 m rect roots as two 170 m
squares, 2048 x 3000 m as two of 2048 m, and 1000 x 3700 m as four of
1000 m. A pool given a `rect` cuts and roots that rect the same way, and
the mesh holds every vertex to it, so the ground it draws ends on that rect's
edges. The water surface cuts the field's lattice the same way, at two steps a
quad.
`rootSize` states the square instead. A stated square past the pool is
refused, naming the size, the squares it makes and the pool.
## The bounding box
The mesh's box is the heightfield's rect by its declared `heightRange`. It is
taken from the declaration rather than reduced from whatever is drawn, because a
box that is too small culls the terrain away at grazing camera angles and the
symptom is nothing at all on screen.
## Entity binding
`terrainMesh.bind(entityId, hf, state)` records that an entity's geometry IS this
heightfield drawn through this pool. `forEntity` reads it back, `isBound` asks,
and `unbind` releases the mesh, the pool and the heightfield's pixels together.
`followCamera(entityId)` is the per-frame entry the `Terrain` component calls.
# terrainOps
The `terrain.*` procgen op family: a whole landscape (a valley, a mountain
range, an island ending in a coastline, a plateau cut into terraces) built as
a procgen graph.
`M.ops` is the family, keyed by registry id. `procPacks/terrain.procPack`
returns it, and that asset's registration is what puts every op in the proc
registry, the same `.procPack` path any author outside this package uses to
contribute a family. The procgen toolbox's `searchNodes` lists them and `describeNode`
gives one's inputs, params and outputs. The nodes a graph calls as `g.terrain.<name>`
are this package's `terrain.nodebox`.
| Movement | Ops |
|---|---|
| source | `terrain.source`: the rect of ground, in metres, at a resolution |
| shape | `terrain.fbm` · `terrain.cone` · `terrain.ridge` · `terrain.ramp` · `terrain.flatten` · `terrain.terrace` · `terrain.stamp` · `terrain.layer` · `terrain.project` · `terrain.erode` · `terrain.coast` · `terrain.sea` · `terrain.lake` · `terrain.river` |
| mask | `terrain.mask` writes a named layer; every raster kernel op reads one through `mask` / `maskMode` / `maskGain` |
| bake | `terrain.write`: the whole landscape as a `.terrainData`: heightfield, control textures, holes mask, layer table |
| carry | `terrain.to_texture` · `terrain.from_texture`: one layer in and out of a `.texture` |
| stand | `terrain.scatter` · `terrain.drape`: points onto the surface, and anyone else's points back down onto it |
The value every op takes and returns is a `proc.raster` **`Raster`**: a tiled
GPU grid carrying named scalar layers (`height`, `water`, `waterMask`, and
whatever `terrain.mask` names).
## What is in here
| File | Role |
|---|---|
| `init.luau` | Assembles the family into `M.ops`. Owns `terrain.source`. |
| `shape.luau` | The placed shapes: `flatten`, `cone`, `ridge`, `ramp`, `terrace`. |
| `noise.luau` | `terrain.fbm`: multi-octave, optionally domain-warped fractal relief. |
| `mask.luau` | `terrain.mask`: a soft band over one feature, written to a named layer. |
| `project.luau` | `terrain.project`: a curve driving the ground by distance to its polyline. |
| `surface.luau` | `layer`, `stamp`, `coast`: an external source blended into height. |
| `water.luau` | `lake`, `sea`, `river`: one water body over three regions. |
| `erosion.luau` | `terrain.erode`: droplet and thermal erosion batched over the tiles. |
| `convert.luau` | `to_texture`, `from_texture`: a raster layer and a texture are the same field in two carriers. |
| `write.luau` | `terrain.write`: the whole landscape as one `.terrainData` container. |
| `scatter.luau` | `terrain.scatter`, `terrain.drape`: a point cloud off the ground, and points put back on it. |
| `scene.luau` | `terrain.ground`: the ground the scene's Terrain entities stand on, which `drape` sets points on. |
| `curve.luau` | A `Curve`'s control points flattened for the payload binding, shared by `project` and `mask`. |
| `lanes.luau` | The eight vec4 dispatch lanes a placed-shape kernel's numbers are packed into. |
| `modes.luau` | The shader numberings the ops declare. |
`M.packers` and `M.payloads` expose each kind's dispatch numbers with no GPU
dispatch and no readback, which is what a test verifies the maths through.
## Out of the graph
A landscape leaves as a `.terrainData`: the heightfield, the control textures
saying which surface covers where, the holes mask, the water surface and the
table of what those surfaces are, held together as one asset. `terrain.write`
takes the raster, a `name`, and the `layers` (the mask layer names holding each
surface's coverage, in channel order), and answers the reference to the container.
Its children are ordinary `.texture` assets written inside the container, so
nothing here is a private format and a material samples a control texture the
way it samples any texture. A `Terrain` component standing an entity on that
container is what puts the ground in a scene.
`terrain.to_texture` carries ONE layer out on its own, for a raster that is
feeding something other than a landscape; `terrain.from_texture` is the way back
in, and it is how a heightmap made anywhere else becomes ground these ops can
carve.
# terrain
Ground as nodes. `terrain.source` opens a rect of ground as a tiled raster with a `height` layer; every other node
takes that raster, changes it and hands it on.
| Part | Nodes |
|---|---|
| the ground | `source`, `from_texture`; a landscape asset comes in through `io.import` |
| landforms | `flatten`, `cone`, `ridge`, `ramp`, `terrace`, `strata`, `coast`, `layer`, `stamp`, `project`, `fbm` |
| rules | `mask` writes a soft band over height, slope, curvature, noise, a curve, the drainage area (`flow`) or any layer of the raster (`layer`, such as `deposit`) into a named layer; any node's `mask` input names it |
| water | `lake` (floods the seed's basin until it is dry), `sea`, `river` |
| weather | `erode`: stream-power erosion over a drainage network (`stream`, the default), scree shed by steep faces and settled at the repose (`talus`), droplets walked on the device with integer sums, or thermal relaxation |
| standing on it | `scatter`, `drape` |
| out of the graph | `landscape` (one element standing as the ground, the `Terrain` component on it), `write` (the same landscape saved as a named `.terrainData`), `to_texture` |
The landforms are one pattern: a coverage weight (`footprint`), a profile of the distance (`dome`) or a value, and
`core.raster.blend`. Parts the nodes share: `footprint`, `dome`, `mask_weight`, `nearest` (the nearest point of a
curve), `surface` (height, normal and slope under a position), `bilinear` (a grid of samples read between the four
around a point), `texel` and `image` (a layer read per texel of an image, and the image's texels), `dimensions`, `wet`
(water into a region), `control` (normalized surface weights packed as 8-bit words).
The raster holds more ground than its rect: the tiles store the cells of a border tile past the rect and a ring of
cells around the tiles, and every landform and every blend writes them at their own world positions, as the tiles of
the ops did. A node that reads at an offset (`cell` with `dx`, `dz`, the slope and curvature of `mask`, thermal
`erode`, the walk of a droplet) reads those cells, so ground beside the edge slumps, drains and washes into them.
The water floods (`lake` fill) stay inside the rect.
A call answers a node's output directly when it has one (`g.terrain.cone({ ... })` is the raster) and a record when it
has several (`g.terrain.footprint({ ... }).weight`).
`nearest` holds the module that reads a curve's polyline. `landscape` and `write` name the landscape record kind
(`records/terrain.procRecord` of this package), whose module declares the surfaces and writes the container.
The noise terrain's relief and masks are made of is the noise prelude of `kernels/` (`zero_angle_fbm_damped2` and
`zero_angle_warped2` for `fbm`, `zero_angle_gradient2` for `terrace` and the noise mask), called through `field.call`.
Erosion droplets are a step Field handed to the `walk` kernel, their changes summed with the `scatter` kernel.
## Landforms from large to small
A landscape reads as ground when it is built from its largest form down: the design (ramps, ridges and cones along the
map's high ground and valleys), one `fbm` a third of the map across, `erode` with `model = "stream"` for the drainage,
a damped `fbm` of at most a tenth of the relief on the gentler ground, `strata` for the rock bands of the faces,
`erode` with `model = "talus"` for the scree below them, and surfaces from `mask` bands over `slope`, `height`, `flow`
and the `deposit` the scree left. "Crafted ground, large to small" in the
terrain guide (`guides { path = "systems/terrainSystem/documentation/terrain" }`) states each step with its scale.
- **`fbm`** sums its layers down to features 8 cells wide when `octaves` is 0, warps its position by a quarter of
`featureSize` when `warp` is left out, and divides each layer's height by `1 + detailDamping * s^2`, `s` the slope of
the layers below it, so slopes keep to the large forms and the flats keep their fine relief (`detailDamping` 0 sums
every layer at full height).
- **`erode`** `model = "stream"` finds where water gathers over the whole ground and cuts a branching network of
valleys into it. The terrain is averaged down to a working grid of at most `workResolution` cells a side, eroded by
the `terrain_erode_stream` kernel (drainage area by Jacobi passes over the ground with its depressions filled, an
implicit stream-power step toward the steepest lower neighbour, the talus limit and creep), and what changed is
added back to the raster by bilinear reads. It writes the drainage area, in square metres, to the layer named by
`writeFlow` (`flow`); `uplift` names a layer the ground rises by over the run. A seed gives the same ground on every
run. `droplet` and `thermal` work as they did. With `keepShape` (the default) the step never raises a cell, the
talus limit lays back only the slope the cutting made steeper and creep evens out only what the run changed, so a
cirque, valley or lake hollow carved before the erosion keeps its depth and its faces: carve the landform, then
erode it. `keepShape = false` fills every closed basin to the level it spills at and lays every face back to
`talus`; there, when a cell rises past `fillNotice` metres (3 by default), the log names the node, how many cells
rose and the deepest rise.
- **`erode`** `model = "talus"` lets steep faces shed rock that runs down and settles at the angle of repose
(`talus`, 34 degrees by default) into fans at their foot and on their ledges. It runs on the same working grid as
`stream` (the `terrain_erode_talus` kernel: rock under a layer of debris, each pass a face turns a share of `shed`
metres to debris and the debris moves toward the lower neighbours past the repose, exactly conserved), adds what
changed back to the raster and writes the debris depth, in metres, to `writeDeposit` (`deposit`). `cliff` is the
slope a face sheds all of `shed` at; `fans` and `fanSize` make some stretches of face shed more than others, so the
debris gathers into separate fans instead of one even apron.
- **`strata`** steps steep ground into rock bands: a near-vertical riser, then a narrow ledge sloping out from its
foot (keeping `ledge` of the face's slope), band after band `step` metres apart. The bands lie at irregular heights
(`irregularity`), wander up and down across the face (`jitter`, `jitterSize`), tilt with the beds (`dip`,
`dipDirection`) and break off in patches (`breakup`, `breakupSize`). They engage from `minSlope` to full at
`fullSlope`, so flats keep their shape, and a riser spans at least `riserCells` cells; a band too thin to hold a
riser and a ledge on a face that steep fades back to the face, so lay faces at 45 to 70 degrees and give a steeper
face thicker bands. The profile stays at or below the face, so a band cuts into the ground and never stands proud
of it.
- **`mask`** `input = "flow"` bands the base-10 logarithm of that drainage area (2 is a hundred square metres of
catchment, 4 a hectare) read from the layer named by `source`. `altitude` bands the height as a share of the raster's
relief, `aspect` the angle between the way the ground falls and the compass `axis`, `shore` the metres above the
nearest water within `reach` and `convexity` the ridge-or-gully measure at `radius` metres; they are measured by
`modules/terrainMeasure`, which `terrain.occlusion` and `terrain.landscape` share.
- **`occlusion`** writes the sky visibility of each cell: four azimuth slices (eight directions) of horizon over six
distances doubling out to `reach`, integrated against the ground's normal.
- **`terrace`** takes `sharpness` (1 puts each rise within two cells, below 1 the last share of each step is an eased
rise) and `jitter` (metres the levels wander by, over features of `jitterSize` metres); `mask` confines it. It
quantizes the height inside a disc, flats included: paddies, quarry benches, a stepped mesa. Bedded rock on steep
faces is `strata`.
# Landscape (procNode)
The last node of a terrain graph: the ground as one element. It is
`terrain.landscape` under the name a graph ends a landscape with: the raster goes
in, and one point comes out carrying the `Terrain` component, its `terrain` a
landscape record holding the heightfield, the control textures, the holes mask,
the water surface and the table of what the surfaces are.
`io.output` stands the element as an entity with the ground, its water and its
colliders, and `io.export` saves it with its `.terrainData` inside the asset it
writes. A terrain among other elements is merged and parented like any element.
## Inputs
- `raster` (Raster): the ground.
- `name` (String, default `"landscape"`): the entity's name, the element's `name`.
- `height` (String, default `"height"`): the raster layer written as the
heightfield.
- `water` (String, default `"water"`) and `waterMask` (String, default
`"waterMask"`): the raster layers holding the water surface and where it covers.
- `layers` (String, default empty): the surfaces, in channel order, as the names
of the raster layers holding their coverage, separated by commas:
`"sand, grass"`.
- `surfaces` (List of records, optional): what each surface in `layers` is
shaded with, `{ name, tint?, albedo?, normal?, mask?, tiling? }`, matched to a
layer by `name`.
- `holes` and `solid` (String, default empty): a mask layer marking where ground is
cut out, or where it exists.
- `resolution` (Int, default 0): texels across the longer axis; 0 takes one texel
per raster cell.
- `layerResolution` (Int, default 0): the edge of one layer slice; 0 takes the
largest edge any layer map carries.
- `fields` (Record, optional): fields of the `Terrain` component beside the
ground: `material`, `waterMaterial`, `collision`, `collisionResolution`, `size`,
`origin`, `heightRange`, `water`.
## Output
- `terrain`: one element carrying `Terrain`, standing as a landscape.
# terrain
Ground, as procedural operations. `terrain.source` opens a rect of ground as a
tiled `Raster` with a `height` layer; every other op in the family takes that
`Raster`, changes it, and hands it on — so a valley, a mountain range, an
island and a coastline are all the same graph with different nodes in it.
`terrain.write` carries the result back out — into a `.terrainData` that a
`Terrain` component stands an entity on.
Every op is an ordinary procgen op, so any graph can reach them and they
compose with the rest of the registry: the shaping ops take a `Raster` and hand
one on, and the ops that stand things on the ground hand back points.
## Ops
**The ground**
- `terrain.source` — the rect a terrain graph starts from: a tiled raster with
a height layer, at a chosen resolution.
**Shapes and noise**
- `terrain.fbm` — fractal noise over the height layer; ridged or plain.
- `terrain.flatten` — level the ground inside a placed shape.
- `terrain.cone` — a cone or crater at a placed centre.
- `terrain.ridge` — a raised or cut ridge along a placed line.
- `terrain.ramp` — a graded slope between two heights.
- `terrain.terrace` — quantize height into steps.
**Rules and blending**
- `terrain.mask` — write a soft band over one feature (height, slope, or
distance to a curve) into a named layer.
- `terrain.project` — band height by distance to a curve.
- `terrain.layer` — blend a painted layer into height.
- `terrain.stamp` — blend a texture into height at a placement.
- `terrain.coast` — pull the ground outside a landmass down to the shore.
**Water**
- `terrain.lake` — fill a basin to a water level.
- `terrain.river` — carve and fill a channel along a curve.
- `terrain.sea` — flood everything below a level.
**Erosion**
- `terrain.erode` — hydraulic (droplet) or thermal erosion, batched over the
raster's tiles.
**Standing things on it**
- `terrain.scatter` — points across the surface, weighted by a mask layer and
banded by slope and height, each carrying the normal and slope under it.
- `terrain.drape` — anyone else's points put down onto the ground: a graph's
own `raster`, or the scene's `ground`.
- `terrain.ground` — the ground the scene's Terrain entities stand on, as a
graph value read afresh every frame. Wired into `terrain.drape`, points land
on it wherever the graph stands, each marked `grounded`, and a Generator sets
them again when the ground is rebuilt or the Generator moves.
**Out of the graph**
- `terrain.write` — the whole landscape as a `.terrainData`: the heightfield
(`rgba32f`, R metres, G/B gradient), the control textures saying which surface
covers where (`rgba8`, four layers a texture, weights normalized to sum to
one), the holes mask, and the table of what those surfaces are.
- `terrain.to_texture` — ONE layer as a Texture on its own, for a raster feeding
something other than a landscape.
- `terrain.from_texture` — the way back in, and how ground made anywhere else
becomes something these ops can carve.
```luau
g:node("bake", "terrain.write"):input("raster", ground)
:param("name", "dunes"):param("layers", { "sand", "rock" })
```
Then a `Terrain` component standing on that landscape is what puts it in a scene.
# landscape (procRecord)
The landscape record kind: the ground a raster becomes, with every texture it needs read back from the device (the
heightfield, the holes mask, the water surface and its shade, one control texture per four surface layers), the
surfaces it declares, and the rect it covers. `terrain.landscape` answers one, held on one element as
`Terrain = { terrain = <record>, ... }`.
Live, a record becomes a `.terrainData` written in the session's scratch folder, the asset the `Terrain` component's
`terrain` field stands on; it is removed once nothing stands on it. Saved, it is a `.terrainData` container with its
textures as `.texture` children inside it, written inside the folder of the asset being exported. `terrain.write`
saves one under the name and folder it is given.
`landscape.module` is the writer both use: `declare` states the surfaces a layer list names, and `writeLandscape`
writes the container.
# terrain_cell
The height of the ground inside one cell of a landscape's lattice of samples
(`zero_terrain_cell_height`): the cell's two triangles, split along the
diagonal from its +Z corner to its +X corner. It is the surface a Terrain's
collider holds, its mesh draws and `terrainHeightfield.cellHeight` answers, so
a kernel that reads a landscape's height between its samples through it puts a
point on that same ground.
```wgsl
#include "@builtin::systems.terrainSystem.terrain_cell"
```
# terrain_ground
The ground a landscape paints by where it stands: four bands of colour
climbing with altitude, a cliff over steep faces, a noise breaking each band's
edge, and a slow macro variation across large patches
(`zero_terrain_ground_bands`). `terrainSplat` paints the share of a pixel no
named layer claims this way (`ground_fill`), all of it under `terrainStandard`,
so a streamed landscape that draws one tile through each shows no seam between
them.
```wgsl
#include "@builtin::systems.terrainSystem.terrain_ground"
```
## What the module holds
- `zero_terrain_ground_bands(wp, n, heights, blend_width, slope_start, slope_end, detail_scale, detail_amp,
macro_scale, height_range, altitudes)`: the bands at a point. A `height_range` (minimum, maximum, metres) that
states a reach puts the bands at `altitudes`, fractions of it, with the transitions and the breakup scaled to it;
a reach of nothing takes `heights` and `blend_width` as metres. The peak's snow is drawn only where the ground
lies down, and `face` is a noise continuous in the world's position.
- `zero_terrain_strata(wp, spacing, warp, dip, quality)`: where a point stands in the sedimentary bands of a cliff,
0 to 1, a function of the world height tilted by `dip` and warped by a slow noise, in three octaves at
irrational ratios.
- `zero_terrain_strata_tone(s, amount, contrast, warm, cool)`: the colour factor a layer takes from the strata.
- `zero_terrain_ihash2`, `zero_terrain_ground_vnoise2`, `zero_terrain_noise1`, `zero_terrain_ground_fbm2`: value
noise from an integer hash, the same on every backend however far the ground runs from the origin.
# terrain_surface
What a surface shader reads of the landscape it stands on. A shader declares the
`terrain_*` properties it reads (`terrain_field_min`, `terrain_field_size`,
`terrain_morph_band_start`, `terrain_cut_eyes_a`, `terrain_cut_eyes_b`,
`terrain_cut_eye_count`, `terrain_normal`, `terrain_normal_strength`,
`terrain_weights_lo`, `terrain_weights_hi`) and a `Terrain` binds each one the
shader declares from the landscape it draws; this module holds the functions
that turn those values into what a pixel needs. They take their values as
arguments and bind nothing, so including the module spends no texture slot,
sampler or buffer.
| function | |
|---|---|
| `zero_terrain_morph_cut(v, band_start, eyes_a, eyes_b, eye_count)` | The geomorph: slides a vertex onto the position it holds one LOD level coarser, by its distance to the nearest point the LOD cut was taken for, and sets `uv` to the landscape XZ the vertex stands on. Every view drawing the ground (another camera, a capture, a shadow map) draws the surface the cut stitched. |
| `zero_terrain_morph(v, band_start)` | The same slide measured from the camera drawing the view. |
| `zero_terrain_field_uv(xz, field_min, field_size)` | Where a landscape point falls in the textures covering its rect, 0 to 1. |
| `zero_terrain_ground_normal(t, s, uv, vertex_n, strength, instance_id)` | The ground's own normal from the landscape's normal texture, turned by the drawn instance's normal transform (`input.instance_id`) into a world normal; `strength` 0 keeps `vertex_n`. |
| `zero_terrain_weights(t, s, uv)` | A weight texture through a cubic B-spline. Weights stored in a block format do not keep summing to one: divide them by their sum. |
```wgsl
#include "@builtin::systems.terrainSystem.terrain_surface"
fn vertex(v: VertexData) -> VertexData {
return zero_terrain_morph_cut(v, material.terrain_morph_band_start, material.terrain_cut_eyes_a,
material.terrain_cut_eyes_b, material.terrain_cut_eye_count);
}
```
# Package (asset type)
A package is an asset — a `<Name>.package/` folder that bundles
components, modules, scenes, presets, tools, and any other typed
sub-assets under one identity, installed into a world as one unit.
Packages are how authoring sets get distributed across worlds.
A **library** is the addressable root scope content resolves under
(`@builtin`, `@<name>`) — a whole world mounted into this one under a
namespace, via `zeromind.installLib` / `world.installLibrary`. A package is
an asset that lives inside such a root, and one library holds as many
packages as its author put there. A package is installed by guid the
way every asset is (`zeromind.installAsset`).
## When to use one
- You're authoring a coherent feature suite (character controller
stack, voxel engine, UI kit, animation library) and want to ship
it as one install target.
- You want a stable identity worlds can install and resolve sub-assets
against (`@<lib>::pkg.sub_module`).
- You want versioning + a per-package metadata layer that travels with
the contents.
If you're authoring inside a single world and don't need a separate
install lifecycle, you don't need a package — drop your `.component`
/ `.module` / etc. directly in `/zero/source/`. Packages are for
cross-world distribution.
## Where it lives
- Source: `/zero/source/.../<Name>.package/` (or, for legacy
packages, a folder containing `package.yaml` at its root).
- Identity: `<Name>` (the `.package` suffix collapses in identity —
mirrors `.module`). A file at `<Name>.package/<sub>/init.luau`
resolves under the same identity it would at `<Name>/<sub>/init.luau`.
- Folder shape (container-style — open child set):
- `package.yaml`: metadata (name, version, description) and the
packages it depends on (`dependencies`). **Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- Sub-asset folders: any combination of `.component/`,
`.module/`, `.scene/`, `.preset/`, `.tool/`, `.toolbox/`,
`.material/`, `.shader/`, etc.
The validator permits unlisted children (`allow_unlisted: true`) by
design — packages are open containers.
## How to create one
```luau
asset.create("package", "<Name>")
-- Creates: /zero/source/<Name>.package/
-- package.yaml (metadata scaffold)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("package", "<Name>", { folder = "systems" })
```
Then scaffold sub-assets inside it:
```luau
local pkg = asset.resolve("<Name>.package")
asset.create("component", "Spinner", { into = pkg })
asset.create("module", "util", { into = pkg })
```
## `package.yaml`
```yaml
name: inkBlocks # optional; the folder stem when absent
version: "1.0.3"
description: "Ink and paper style blocks"
dependencies:
- styleKit # no version: the newest release
- { name: starterBlocks, version: ">=1.0.8" } # a floor
- name: uiKit
version: "=2.3.1" # an exact pin
reason: "2.4.0 renames the panel styles"
```
`dependencies` lists the packages this package needs. Each entry's `name` is
a reference the package records, the same kind of reference a `require` or an
asset name in a data file makes:
- **It resolves in the author's world.** Install the dependency here first
(`zeromind.installAsset`); the entry then names the copy this world holds.
A push refuses a package whose dependency resolves to nothing, naming it.
- **An install brings it along.** Installing the package installs every
dependency it lists, at the version this world holds when the package is
pushed, under `/source/deps/<owner world>/`, deduplicated against what the
installing world already holds. `zeromind.preview` lists each one before
anything is written, and the install's `deps` counts what it brought and
names each package among it (`detail = "full"` lists every dependency's
path and version).
Uninstalling the package leaves a dependency that another installed
package still uses.
- **`version` is a spec.** It names the releases of the dependency the
package works with. With no `version`, or `latest` / `*`, every release is
admitted, across major versions.
| Spec | Admits |
|---|---|
| `latest`, `*`, no version | every release |
| `">=1.4"` | 1.4.0 and every release above it |
| `"^1.4.10"` | `>=1.4.10 <2.0.0` (`^0.3.1` is `>=0.3.1 <0.4.0`) |
| `"~1.4.10"` | `>=1.4.10 <1.5.0` |
| `"1.4.*"` | `>=1.4.0 <1.5.0` |
| `"=1.4.10"` | exactly 1.4.10: the one form of an exact pin |
| `">=1.4 <1.6"` | what every part admits |
Quote a spec in YAML: `>`, `*` and `~` start other YAML forms. A
prerelease (`1.5.0-rc.1`) is admitted only by a spec naming a prerelease of
the same version (`">=1.5.0-rc.1"`). A bare number with no operator
(`version: 1.0.8`) reads as `latest`, and `asset.validate` warns that it
does: delete it to say latest, or write `"=1.0.8"` to pin. Give a pin or a
range a `reason`, which says why to whoever reads it.
`asset.validate` (and so the push) refuses a `version` that is not a spec,
and an explicit spec the dependency this world holds does not satisfy,
naming both; in a world the package is installed into, the package runs the
release the install placed, and the same finding is a warning.
`@builtin::modules.deps` parses specs and resolves a set of them to one
release of each package: the newest release every explicit spec naming it
admits, or a report naming the specs that exclude each other.
## How it operates
1. **Registration.** Writing `package.yaml` indexes the package with
the package registry.
2. **Install.** A package is read before it is installed: `zm ls-tree
@<guid>` in the shell lists what it contains, and `zm show
@<guid>:<path>` and `zm grep <pattern> @<guid>` read it, so candidates
are compared by what they do. The one that fits is installed by guid,
the way every asset is: `zeromind_install` over the engine's MCP, or
`tools.use("zeromind", "installAsset", <guid>)` inside the engine. The
install writes the package's files (and the deps its `.refs`
record, the packages its `package.yaml` lists under `dependencies`
included) into this world's source, so its sub-assets resolve here.
`tools.use("zeromind", "preview", <guid>)` reports what an install would
write before it writes anything.
3. **Sub-asset resolution.** Because `.package` collapses in
identity, sub-asset paths work whether the package folder is
suffixed (`<Name>.package/<sub>`) or not (`<Name>/<sub>`).
4. **Updates.** `tools.use("zeromind", "updates")` lists installed content
with upstream changes available; re-running the install pulls them.
5. **Metadata.** `package.yaml::name` overrides the folder stem if
present (rare); `version` + `description` are surfaced in the
package index.
6. **Hot reload.** Edits to sub-assets hot-reload as normal; edits to
`package.yaml` reload package metadata.
## Discovery
- `asset.list("package")` — every registered package.
- `asset.inspect("<name>")` — sub-asset catalog, source, this type
README.
- `ls /zero/source/<Name>.package` lists the files the folder holds.
- `library.list()` — the library assets registered in this world,
including the ones packages under an installed library contribute.
## Authoring conventions
- Name packages by their feature (`voxels`, `cameraRigs`,
`dialogSystem`), not by their owner — the host library is the
`@<lib>::` scope prefix.
- Cluster cohesive sub-assets together. A "character controller"
package should ship the controller component, its preset configs,
its supporting modules, and a demo scene — not just the component.
- Document the package's surface in `README.md` — what install
installs, what each sub-asset does, how they relate. Agents reading
`cat /zero/source/<Name>.package/README.md` get the full picture in one shot.
- Leave the release version to the push: `zm push` releases a changed
package under the next patch version and writes it into `package.yaml`.
A change that breaks the package's users is `zm push --major`, a new
capability `zm push --minor`. Anything else that names the package's
version reads it from `package.yaml` rather than keeping a copy.
## Common pitfalls
- **Missing `package.yaml`.** Without it the folder isn't recognized
as a package even if it has a `.package/` suffix.
- **A dependency named only by a string the code builds.** A package
whose files reach another package only through a name assembled at
runtime records no reference to it, so an install arrives without it.
List that package under `dependencies` in `package.yaml`.
- **Identity collapse.** Sub-asset paths skip the `.package` suffix.
Don't include `.package` in `require` strings.
## Referencing inside a package: the `~` rule
`~` means **this package**, resolved structurally from the referring file's own
location. It is the only package-specific syntax. It is rename-safe (no package
name is ever written) and library-agnostic (it never names the host library, so
it survives `@builtin` being renamed or the package being mounted elsewhere).
`~.tail` maps to `<pkg>.package/tail` from anywhere inside the package.
| Referencing from | Use | Example |
|---|---|---|
| An asset/module **inside this package** | `~.tail` | `require("~.modules.myThing")`, `shader: "~.shaders.myThingBlend"` |
| A **different package** under the same root | root-relative identity | `require("@root::systems.terrainSystem.modules.terrainOps")` |
| A **different library's** public API (a deliberate external dependency) | `@otherlib::…` | `require("@<otherlib>::<path>")` |
**Never write `@builtin::` (or any host-library name) to reference your own
package** — that couples the package to the library it currently lives in and
breaks if the library is renamed or the files move. Use `~.`. It works from
Luau `require()` and from asset-reference strings in data files (a material's
`mat.yaml` `shader:` field, a component's default asset ref); the engine
resolves it against the referring file's own package. `asset.resolve` takes a
`~.` name the same way, against the package of the file that calls it:
`asset.resolve("~.materials.myThingStandard", "material")`.
`~.` is the package-relative self-reference; `@root::` is the root-relative one
(the library root, or the world source tree for non-library content). The
`core/requiring-modules` guide covers the root model in full.
A package that ships substantial functionality should include a `.guide` asset
(a `<name>.guide/guide.md` folder anywhere under the package); the `guides` tool
discovers it live, so collaborators find the system the way they find built-in
guides. A package's test suite reaches the shared `Test` framework through its
enclosing asset: `local Test = asset.containing(__FILE__).modules.shared`
(`asset.containing` returns the deepest enclosing typed asset, the `.testSuite`,
not the outer `.package`).
## Related types
- Any of `.component`, `.module`, `.scene`, `.preset`, `.tool`,
`.toolbox`, `.material`, `.shader`, `.style`, `.service`,
`.importer` — packages bundle these.
## In the Inspector
Package: the name, version and description package.yaml declares, how many things the package holds and what they are, and **Open** for package.yaml. A package.yaml that does not decode is listed under Problems with the decoder's error.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `interfaces:` | The interfaces every asset of the type implements (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
| `contexts:` | The environment the engine loads a file of the asset into, and what it holds (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export?, export_optional? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## Computed output files
A type can declare files produced by its compiler. Each rule names an exact
asset-relative output path, an activation marker, and guidance for editing the
inputs:
```yaml
computed_files:
- path: "cache.json"
when_exists: "authoring/state.json"
edit: "Edit the recipe and run the asset compiler."
```
Once the marker exists, ordinary writes, removal and individual-file moves are
refused for that output. The marker and output paths stay within the asset.
Declare their folders in `files.required` or `files.optional` as usual.
Compilers commit their outputs with the input revisions through
`modules.sourceOperations.materialize`. A complete asset copy to a new
destination carries its inputs and computed files together. Copying individual
files into protected outputs and merging a tree over protected outputs are
refused before destination leaves change.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. A type that lists `sceneInstantiable` under `interfaces:` guarantees it, and its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `implements`, `as`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
| `validateCommitted` | `(folder, read) -> { { code, message, severity?, remedy? } }` | On every push, for each asset the push changes, over the asset as the commit the push publishes holds it. `read(file)` answers a file's committed text, relative to the asset's folder, or nil for a file the commit holds no text of. A problem of `error` severity (the default) refuses the push, whatever the working tree holds. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. |
| `settingsHealed(values, stored)` | On a read, to repair stored values. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
An asset whose picture is what it does to a scene rather than what it looks
like (a lighting setup) names a `subject` on an `instantiate` recipe: a
scene-instantiable asset stood in the studio in its place, while the asset
itself is applied to the world (`applicable`, owner `preview`) for the
shot and dropped after it. `studio_light: false` photographs the subject under
the world's lighting, which the applied asset states, instead of the studio's;
such a picture renders only on an explicit request (`preview.writePreview`,
`assets.generatePreviews`, staging), never from the preview queue or a live
preview.
```yaml
preview:
kind: instantiate
subject: "@builtin::preview.subjects.lookdev"
studio_light: false
```
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in, or a list of categories: a name
there is recorded as the one asset of those categories it answers to, a name
two of them answer to is recorded as neither, and a name written as a path
ending in one of their suffixes is the asset at that path.
A key whose names are assets of any type implementing an interface is stated
under `interfaceKeys`, and is declared typed to the types that implement the
interface, again whenever a type or an interface changes:
```yaml
references:
interfaceKeys:
- { key: "members", implements: applicable, field: "source" }
```
`asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
A JSON or YAML data file of your type is read whole for the references it holds:
every `{ __ref }` envelope, `@` identity and `components` entry in it. When a file
also keeps values that are data rather than links (an edit history holding the
asset a field used to name, say), `documents` names the fields that carry its
links, and the rest of the file is read as data:
```yaml
references:
documents:
- path: authoring/entities/ # every file under this folder of the asset
fields:
- [records, "*", references] # keys from the root; "*" is every entry of a list or mapping
- references
- path: authoring/settings.json # this one file
fields: [references]
```
`path` is inside the asset's folder; the longest `path` covering a file decides
it. Each value a field reaches is read whole. A file that holds none of the
fields is read whole, as is every file no `path` covers. An entry with no valid
`path` or `fields` is refused with a warning naming it.
## What your type guarantees (`interfaces:`)
An interface is an asset (`<name>.interface/`, see the `interface` type) that
states a guarantee: members with signatures, and properties. A type lists the
interfaces its assets implement in its `type.yaml`:
```yaml
interfaces: [sceneInstantiable]
```
Every asset of the type implements every interface the type lists; an asset of
a type that lists nothing never does. The key is a reference to `interface`
assets, so each name resolves like any asset name and is recorded by guid in the
type's reference table, which is where the engine reads the type's marks from.
The `indexing:` role named `interface` is a different thing: it names the file
that states the signatures a caller of an asset uses.
The type meets each member in its `behavior.luau`, implicitly with its own
`M.ref.<member>` of the member's name and signature, or explicitly when its own
method of that name means something else:
```lua
M.ref = { apply = function(self, into) ... end } -- the type's own meaning
M.interfaces = {
applicable = { apply = function(self, owner, values, opts) ... end },
}
```
`M.interfaces` is keyed by the interface's name as the type lists it. A property
the interface states is met by a value or a getter `(self) -> value` in the same
two places, else by the interface's default. A type whose own `<member>` is
shared by two interfaces with different signatures meets at least one of them
explicitly.
| Question | Call |
|---|---|
| Does this asset implement X? | `ref:implements("X")` (a name, identity or guid, or a list meaning any of) |
| Call a member through the interface | `ref:as("X"):member(...)`; `ref:as("X").property` reads a property |
`ref:as("X")` raises, naming the asset and `X`, when the type does not implement
it. A direct `ref:member(...)` reaches the type's own method of that name; when
the type meets the member implicitly, that method is the member and the call goes
through the interface's gate, which checks its inputs and its result. A generic
caller (one that knows only the interface) calls through `:as`.
A declaration that breaks a check is refused: it carries no marks, `asset.validate`
reports each problem as an error that refuses a push, and the engine log states
each once. The codes are `interfaces.shape`, `unknown`, `ambiguous`, `duplicate`,
`missing`, `arity`, `typeKey`, `explicitUnclaimed`, `explicitUnknown`,
`propertyMissing`, `propertyType`, `conflict` and `unloadable`; each message names
the type, the file, the fault and what to write instead. A type that defines
`instantiate` and lists no `interfaces:` (one written before the key existed, or
defined by its `behavior.luau` alone) implements `sceneInstantiable` with the
warning `interfaces.implied`, which names the line to add. `asset.inspect` of an asset lists the interfaces its type
implements, and of a type definition lists them under `detail.interfaces` with
`detail.interfaceProblems` when the declaration was refused. The type's
Inspector shows the same under **Interfaces**: one row per interface (its name,
the first line of its description, and whether the type declares it or it is
implied), then every problem the declaration raised. An interface's own
Inspector shows its guarantee, its contract module and conformance suite, every
member with its signature, inputs and output, and the types that implement it.
The asset browser's **Implements** filter narrows the list to the assets whose
type implements the interface chosen, each interface's description as its
tooltip.
## The environment a file runs in (`contexts:`)
A type whose assets hold a script the engine loads itself states the environment that script runs in, so the engine binds it and the language server checks the script against the same names:
```yaml
contexts:
- name: sceneBuild
file: "build.luau"
surface: "scene's `build.luau`"
globals:
build: "the build surface is bound in a scene's `build.luau`'s own environment, where `build.asset` authors ..."
hooks: [content, editorOnly]
modules: true
```
- `name` is the context's name.
- `file` is the file of the asset folder that runs in the context.
- `surface` names that file in a diagnostic, without an article.
- `globals` are the names the type's loader binds into each run of the file. Each carries the note an unknown-global message gives when the name is used in a file that lacks it.
- `hooks` are the functions the engine calls by name from the file, which the language server does not report as unused.
- `modules: true` says the loader binds the exports of the modules that join the context.
A module joins with `--!context <name>` in its leading comment block. The type's loader builds the environment with `ScriptContext.bind(env, path, values)` (the `script_context` module), which refuses a value the context does not declare. `asset.context(path)` reads the context a file runs in.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# Component (asset type)
A component is code that runs on an entity. The component file
declares public fields, methods, and lifecycle hooks and callbacks; the
engine creates one per entity it is attached to and drives those hooks
(`start`, `update` every frame, `onDestroy`) and callbacks. Components
are the unit of per-entity gameplay code: movement, AI, animations, UI
panels, network sync, and per-entity state all live here.
## When to use one
- You need per-entity state that survives across frames.
- You need per-entity behavior driven by engine lifecycle hooks
(`start`, `update`, `onDestroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If the code does not run on an entity and needs no hooks or callbacks,
use a `.module`. If you
need to generate content declaratively, use a `.service`; compute work
belongs in a `.computeShader`.
## Where it lives
- Source: `/zero/source/.../<Name>.component/`
- Identity: `<Name>` (the `.component` suffix strips from the
identity, but the folder retains the suffix on disk).
- Folder shape:
- `init.luau` (or `init.lua`) — declares the component. **Required.**
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
The structural contract is enforced by `asset.validate` against this
type's `type.yaml`.
## How to create one
Always start with the scaffold — it guarantees the folder shape
matches `type.yaml` from the moment it's on disk:
```luau
asset.create("component", "<Name>")
-- Creates: /zero/source/<Name>.component/
-- init.luau (canonical declare + public block + hooks stubbed)
-- README.md (instance README template)
```
After scaffolding, edit `init.luau` to fill in the actual fields and
behaviour. The component registers as soon as the file is written —
hot-reload is automatic; no engine restart required.
## How it operates
1. **Registration.** Writing `init.luau` into a `.component/` folder
indexes the asset, mints a guid (in the `.meta` sidecar), and
surfaces the type to the engine's component registry. Same-frame
visible to `entity.component.add`.
2. **Attachment.** `entity(id).component.add(name, data)` (or the
batch form `tools.use("entityOps", "addComponents", targets,
{ [name] = data })`) attaches an instance.
The `data` table's fields override the component's declared
defaults; omitted fields take the declared default. The `data`
values are copied into `public.*` BEFORE `awake()` runs.
3. **Lifecycle.** The hooks run in this order:
- `awake()` — same frame as attach, immediately after the data
copy. Initialise state, set up native bridges, register with
other systems. Other components on the same entity may not have
awoken yet.
- `start()` — the next frame. Every component on the entity has
completed `awake()` by then, so cross-component setup is safe
here.
- `update(dt)` — same frame as `start()`, then every frame after,
for as long as the gameplay clock is running. `fixedUpdate(dt)`
runs once per physics step, straight after it, with the step's
`dt`, so a frame can run it several times or not at all;
`editorUpdate(dt)` runs
while the clock is held. Which of them ticks is decided by
`engine.mode` AND `engine.paused` together — see **Per-frame
hooks and the two axes** below, and `man modes`.
- `onDestroy()` — when the component is removed via
`component.remove` or when the owning entity is despawned.
Release resources, drop native ECS components.
For the full list (`onEnable`, `onDisable`, `fixedUpdate`,
`editorUpdate`, `onPropertyChanged`, `onAssetReload`,
`onModuleReload`,
`onBeforeSave`, …) and the timing details, **read `man components`
— that is the canonical lifecycle reference. Generic component
patterns (declare blocks, public fields, sync, ECS bindings,
typed methods) all live there.**
4. **Public surface.** Fields declared in `public` are inspectable,
editable in the inspector, and persist with the entity. Methods are
declared on that same table with a colon —
`typed function public:method(args)` — and every one of them takes
the component ref as `self`, so a caller invokes it with a colon
too: `entity(id).component.get(name):method(args)`. That is the one
calling convention a component ref answers to: the reflection
methods `ref:fields()` / `ref:getField(name)` /
`ref:setField(name, value)` take the same spelling. A function the
chunk declares at file scope (`function helper()`) is the
component's own, reachable from its hooks under its bare name;
`public` is what the ref carries.
5. **Settings and the Inspector card.** `type.yaml` names the component's
settings schema as `settings: { schema: { instance: "init.luau",
export: "public" } }`: the `public` table IS the schema, and its values
live on each entity the component is on, so `asset.schema(componentRef)`
answers the Field descriptors and no values file exists. On an entity
the Inspector shows the component as a card whose generic `settings`
section edits those fields as typed controls, each edit checked against
the schema and written to the live component as one undoable operation.
`type.yaml` also names `inspector: { instance: "inspector.luau" }`: a
component that ships an `inspector.luau` beside its `init.luau` shapes
its card — the file returns `{ sections, replace, order }` (see
`assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)`
reading `ctx.component` (the live component) and `ctx.selection.id` (the
entity). `SceneModule.component/inspector.luau` replaces `settings` with
the bound module's declared inputs.
6. **Events.** An `events` block declares typed moments the component
fires from inside — `events = { onHit = Event({ dmg =
Field.number(0, NoSync) }) }`. The owner fires with
`events.onHit:fire({ dmg = 10 })`; outside code subscribes through
the proxy's subscribe-only facade,
`entity(id).component.get(name).events.onHit:connect(fn)`
(`:once` / `:wait` too). Pass `Sync` as the event's second argument
to replicate a fire to other peers. Events let one component react
to another's moments without polling. Full reference: **`man
components`**, Events section.
7. **Hot reload.** Editing `init.luau` reloads the component
definition; live instances are reconciled with the new declaration
in-place, and each crosses one lifecycle boundary: `onDestroy()`
ends the running life, then `awake()` and `start()` construct the
one that replaces it, and `update()` resumes on the next frame.
`public` and `private` values carry across; module-level `local`s
belong to the chunk, so the new life starts with them at their
initial values and its `awake`/`start` are what fill them in.
Whatever the old life handed elsewhere — a subscription, a shared
registration, a spawned entity — is released in `onDestroy`, the
call that pairs with the construction about to run. An edit that
leaves the source byte-identical crosses no boundary at all.
A field carries its value across when something stated it: a key of
the `data` table the instance was attached with (a scene record's
data is that table), or a write made since. Every other field takes
the edited source's declared default, so changing a default reaches
every instance that left the field to it. An instance that states
its own value for a field whose default the edit changed keeps that
value, and the reload logs a `[HotReload]` warning naming the field,
the entity, the value kept and both defaults.
## Discovery
- `asset.list("component")` — every registered component (engine +
world + libraries).
- `asset.inspect("<name>")` — identity, scope, public fields,
lifecycle methods, source path, and this type README. `detail`
carries the component's declared `fields`, `methods`, and `events`,
parsed from its source — `tools.use("assets","describe", "<name>")`
renders it as markdown, so a component's events are visible without
opening its source.
- `ls /zero/source/<Name>.component` lists the files the folder holds.
- `entity(id).component.list()` — components attached to an entity.
## Per-frame hooks and the two axes
`engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay
clock) are independent, and the per-frame hooks read them separately:
- `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is
running** — whichever mode the engine is in.
- `editorUpdate(dt)` ticks while **the clock is held** — because the
mode is `edit`, or because play is paused — and also alongside
`update` whenever edit is running.
Which gives four states, and this table is the contract:
| `engine.mode` | `engine.paused` | hooks that tick |
|---|---|---|
| `edit` | `true` | `editorUpdate` |
| `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` |
| `play` | `false` | `update`, `fixedUpdate` |
| `play` | `true` | `editorUpdate` |
Entering edit sets `paused = true` and entering play sets it back to
`false`, so a session that never writes `engine.paused` only ever sees
rows 1 and 3 — which is where the shorthand "`update` is the play tick,
`editorUpdate` is the edit tick" comes from. It is the two default rows
of a four-row table, not the rule.
**Row 2 is the one that surprises.** With `engine.paused = false` in
edit — set by hand, or by a tool that advances the gameplay clock to
sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate`
both fire, once each, every frame. A component that declares both and
routes them to one body therefore runs that body **twice per frame**:
```luau
local function drive(dt) ... end
function update(dt) drive(dt) end
function editorUpdate(dt) drive(dt) end -- twice per frame in row 2
```
Nothing reports the doubling; it reads as an animation running at twice
its intended speed. To get exactly one tick per frame in every row, ask
which axis you meant and answer it in the body:
```luau
function update(dt) drive(dt) end
function editorUpdate(dt) if engine.paused then drive(dt) end end
```
A scene `entrypoint.luau` declaring the same two hook names is dispatched
by the scene loader, not by this table: there `update` needs play AND
running, `editorUpdate` needs edit, and play-paused ticks neither. Read
`man scenes` before carrying a component's rule to an entrypoint.
## Authoring conventions
- Annotate public fields with `--!desc` so the inspector + LSP show
documentation alongside the field name.
- Declare lifecycle hooks (`start`, `update`, `onDestroy`) explicitly
rather than relying on engine defaults — readers can see at a glance
what runs when.
- Keep `update(dt)` cheap — it runs every frame per instance. Move
heavy work to `start`, to a `.computeShader`, or behind a job (`man jobs`).
- For multi-entity batching, prefer
`tools.use("entityOps", "addComponents", targets, components)` over
a loop of `entity(id).component.add` — it takes many targets and
many components in one call.
## Common pitfalls
- **Naming.** The component identity is the folder stem with
`.component` stripped (e.g. `<Spinner>.component/` → identity
`Spinner`). Don't repeat the suffix in the identity passed to
`component.add`.
- **`init.lua` vs `init.luau`.** Either is accepted (it's a
`one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both
in one folder is invalid.
- **`update` in edit mode.** It runs whenever the gameplay clock is
running, and entering edit stops that clock — so `update` is idle in
a freshly-entered edit session and ticks again the moment anything
sets `engine.paused = false`. Use `tools.use("wld", "play")` to test
update logic under the mode it ships in; `tools.use("wld", "edit")`
to return. See **Per-frame hooks and the two axes** above.
- **Renaming.** Renaming the folder changes the identity. References
to the component are recorded against the component itself, so
renaming or moving it does not break them.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service`: a declarative content generator, no per-entity state.
- `.preset` — a captured component configuration, replayable into
`component.add` without re-typing fields.
- `.bundle` — entity hierarchies that may carry component attachments
as part of the bundle.
## In the Inspector
Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
# Compute shader (asset type)
A `.computeShader` is a GPU compute (GPGPU) program with a **zero-scaffolding**
authoring contract: you write only `@compute fn main(...)` plus a declarative
`bindings.yaml`, and the engine GENERATES every `@group/@binding` declaration —
storage buffers, textures, samplers, storage textures, and a `params:` uniform —
expands `#include`s, naga-validates the result, and registers it. The single
source of truth for the binding layout is `bindings.yaml`; there are no
hand-written `@binding` lines to keep in sync.
> New to how content lives across the CPU and GPU? Read `core/resource-model`
> first: it covers the asset / CPU / GPU forms every resource takes, the upload
> path, and how compute fits the performance ladder (`core/performance`).
## Folder shape
A `.computeShader` is a folder asset:
```
<name>.computeShader/
shader.wgsl # the WGSL body — only `@compute fn main` + helpers (required)
bindings.yaml # the binding + params schema (required)
README.md # a one-paragraph description of THIS shader (required)
.metadata # asset metadata
```
Each file carries a committed `.meta` sidecar pinning its stable guid. The
identity is `<name>` (the `.computeShader` suffix strips).
Resolve the shader once, then dispatch through the reference:
```lua
local carve = asset.resolve("carve", "computeShader")
carve:dispatch({ buffers = { heights }, workgroups = { 64 } })
```
`asset.resolve` is what records your script's dependency on the shader, so the
shader travels with the world your script lives in — packed, pulled, or
published. It compiles on first dispatch, and on the first frame a render
feature's compute pass names it; there is no setup step.
## bindings.yaml
One ordered `bindings:` list — the binding index is the list position
(0, 1, 2, …) — plus an optional `params:` scalar-uniform block. `kind` defaults
to `buffer` when omitted.
```yaml
bindings:
- { name: clouds, kind: storage3d, format: rgba16f } # texture_storage_3d<rgba16float, write>
- { name: occupancy, kind: texture3d } # texture_3d<f32>
- { name: smp, kind: sampler } # sampler
- { name: out_tex, kind: storage2d, format: rgba16f } # texture_storage_2d<rgba16float, write>
- { name: U, kind: buffer, access: read, element: f32 } # var<storage, read> U: array<f32>
- { name: Uniforms, kind: buffer, access: read, element: VolumeUniforms, array: false } # var<storage, read> Uniforms: VolumeUniforms
params:
- { name: scale, type: float, default: 2.0 }
- { name: count, type: int, default: 0 }
```
| `kind` | extra keys | generated WGSL declaration |
|---|---|---|
| `buffer` (default) | `access: read \| read_write` (default `read_write`), `element: <wgsl type>` (default `f32`), `array: true \| false` (default `true`) | `var<storage, ACCESS> NAME: array<ELEMENT>;` (or `… NAME: ELEMENT;` when `array: false`) |
| `texture3d` | — | `var NAME: texture_3d<f32>;` |
| `texture2d` | `sample: float \| uint \| sint` (default `float`) | `var NAME: texture_2d<f32>;`, or `<u32>` / `<i32>` for the other classes |
| `texture_depth` | — | `var NAME: texture_depth_2d;` — the one sampled shape with no `sample:` of its own; a depth-aspect channel (`@scene.depth`) binds here, not through `texture2d` |
| `storage3d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_3d<FMT, ACCESS>;` |
| `storage2d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_2d<FMT, ACCESS>;` |
| `sampler` | `filter: linear \| nearest`, `mipmap: linear \| nearest`, `address` (or `addressU` / `addressV` / `addressW`): `clamp \| repeat \| mirror`, `anisotropy: 1..16` (with `filter` and `mipmap` linear), `compare: never \| less \| less-equal \| equal \| greater \| greater-equal \| not-equal \| always`; none stated is the engine's linear, clamped sampler | `var NAME: sampler;`, or `var NAME: sampler_comparison;` when it states `compare` (for `textureSampleCompare` on a `texture_depth`) |
| `textureCubeArray` | — | `var NAME: texture_cube_array<f32>;` — the environment cube array, bound to `@scene.environment` by a render feature's pass |
| `vertices` | `access: read \| read_write` (default `read_write`) | `var<storage, ACCESS> NAME: array<u32>;` plus the mesh's layout uniform and the `zeroVertex*` accessors |
| `acceleration_structure` | — | `var NAME: acceleration_structure;` (hardware ray tracing) |
- **Eight storage buffers per shader** — the WebGPU guarantee, and what the
engine asks every device for. `buffer` and `vertices` bindings spend that
budget; textures, samplers, storage textures and `params:` do not. An
`acceleration_structure` brings engine-owned buffers with it — **three** where
the device has hardware ray query (the tables `zeroHitSurface` / `zeroMaterial`
read) and **five** on the software backend (those, plus the scene triangles and
the hierarchy over them) — so a traced pass has three slots of its own on the
backend web users get. Over budget, the engine refuses the shader and logs
which buffers it declared.
- A `buffer` defaults to `array<ELEMENT>`. Set `array: false` for a single
NON-array storage buffer — a struct binding (e.g. `element: VolumeUniforms`,
`array: false` → `var<storage, read> NAME: VolumeUniforms;`). The struct
definition itself lives in `shader.wgsl`, not `bindings.yaml`.
- **A sampled texture binds under the class its FORMAT puts it in**, so
`sample` states that class and the generated `texture_2d<..>` matches it. An
integer channel — `@scene.material`, which is `Rgba8Uint` — is `uint`;
everything else is the `float` default. Bind an integer channel to a `float`
slot and the engine refuses the pass and names both classes, because the
device would otherwise reject the bind group and invalidate the pipeline.
- **A float texture binding filters where the shader samples it.** Each
`texture2d` / `texture3d` binding is laid out from what the shader does with
it: one the shader reads through a sampler (`textureSample*`,
`textureGather*`, in the entry point or any function it calls) is filterable,
and one it reads with `textureLoad` alone is unfilterable and takes every
float texture. `r32f`, `rg32f` and `rgba32f` filter only on a device that
grants 32-bit float filtering, which many mobile GPUs do not; there a pass or
dispatch binding one at a sampled binding is refused and logged, naming the
binding and the format. Read a 32-bit float texture with `textureLoad`, or
keep a texture the shader samples at `rgba16f`.
- A storage texture's `access` decides both the generated declaration and the
layout the engine registers, so the two always agree. It defaults to `write`,
the access every target grants every storage-compatible format. `read_write`
is granted on `r32f` and `r32u` alone; declaring it on any other format is refused at
the compile, with the reason on `compute.programState`. A pass that needs to
read a wider target reads it through a separate `texture3d` / `texture2d`
binding, or through a second storage binding declared `read`.
- `format` tags (storage textures): `r8`, `r16f`, `r32f`, `r32u`, `rg32f`,
`rgba8`, `rgba8u`, `rgba16f`, `rgba32f`. Storage textures only allow
storage-compatible formats (`r32f` / `r32u` / `rg32f` / `rgba8` / `rgba8u` /
`rgba16f` / `rgba32f`). `r32u` holds one unsigned 32-bit word a texel and
`rgba8u` four unsigned 8-bit lanes (the format `@scene.material` is kept in):
the shader loads and stores either as a `vec4<u32>`, and the texel is never
filtered, so a texture bound to a `texture2d` slot reads it with
`sample: uint`. `rg32f` holds two 32-bit floats a texel, each stored and
read back as written and never filtered.
- An `acceleration_structure` binding resolves to the scene acceleration
structure when the shader runs as a render-pass with ray tracing enabled
(`renderer.setRaytrace(true)`). Declaring one makes the engine emit the helper
functions the body can call:
`zeroTraceClosest(origin, dir, t_min, t_max) -> ZeroHit` (struct: `hit, t,
instance, primitive, bary, attr`, where `instance` is the hit object's render
slot), `zeroTraceAny(origin, dir, t_min, t_max) -> bool`
(terminate-on-first-hit over every traced surface, for occlusion rays),
`zeroTraceShadow(origin, dir, t_min, t_max) -> bool` (the same over the
surfaces that cast shadows, for a shadow ray toward a light: a surface with
`castsShadows = false` lets the light through), and
`zeroHitSurface(hit) -> ZeroSurface` (`normal, uv, material`) +
`zeroMaterial(index) -> ZeroMaterial` (`base_color, emissive, metallic,
roughness`) to shade what a hit landed on; its `base_color.rgb` is the
material's `base_color` times the mean colour of its `base_color_texture`. The same surface works on both backends — hardware
ray query and the software/compute path — so the shader doesn't branch on
`renderer.raytraceCapability()`. Both trace helpers pass through the
cut-away texels of an alpha-tested surface (a texel stays where
`base_color.a * base_color_texture.a` reaches the material's `alpha_cutoff`),
read from the engine-owned coverage texture `zeroHitCoverage` bound beside
the hit tables. Bind it from a render-pass, which is where
the scene acceleration structure exists.
`params:` declares scalar uniforms (`type: float | int`). When non-empty the
engine appends a `ZeroComputeParams` uniform as the trailing binding (read it in
WGSL as `params.<name>`) and tunes its values at runtime with
`shaderRef:setParam(prop, value)`.
## The kernel ABI: `columns`, counted and appended outputs, `specialize`, `determinism`
One shader asset can serve many shapes of data. `bindings.yaml` states the shape
with these extensions, and the engine's compile path lowers them to the plain
bindings and WGSL above (`modules/compute_abi`, whose README has the whole
surface):
```yaml
workgroup: 64 # the size the body declares (default 64)
bindings:
- { name: cols, kind: columns, access: read } # a table of columns in one binding
- { name: src, kind: buffer, access: read, element: T }
- { name: dst, kind: buffer, access: read_write, element: T, count: "len(src)" }
- { name: hits, kind: buffer, access: read_write, element: vec4<f32>, capacity: "n * 4", append: true }
specialize:
- { name: T, options: [f32, i32, vec2<f32>, vec3<f32>, vec4<f32>] }
- { name: FOLD, options: [add, min, max] }
- { name: BODY, kind: source, default: "0.0" } # text that replaces the identifier
determinism: exact # or float_order
```
- A `buffer` of a scalar or vector element gets `NAME_get(i)`, `NAME_len()` and
(unless `access: read`) `NAME_set(i, v)`. A `vec3` element is stored as a flat
scalar array, so a column of vec3 keeps its 12-byte stride. `zero_n()` is the
dispatch size.
- `columns` binds a table of columns (`compute_abi.table`) as one storage buffer;
`cols_f32(c, i, lane)`, `cols_vec3(c, i)` and the rest read it.
- `count` / `capacity` give the size, in elements, of an output the run
allocates. `append: true` adds a live counter binding, `NAME_count`, with
`NAME_store(slot, v)`, `NAME_set_count(n)` and, under `determinism: float_order`,
`NAME_append(v)`.
- `specialize` parameters are compile-time: type options become `alias NAME`,
named options become `const NAME` and `NAME_<option>`, `kind: source` text
replaces the identifier. Each specialization compiles once.
- `determinism: exact` refuses `NAME_append`: an exact output is written at ranks
the kernel computed.
Dispatch such a shader through its program:
```lua
local variant = shaderRef:program():variant({ specialize = { T = "vec3<f32>" } })
local run = variant:run({ n = 64, inputs = { src = srcBuffer } })
local values = require("@builtin::modules.compute_abi").read(run.outputs.dst.buffer)
```
`shaderRef:program()` answers the same program, with the variants it has lowered and compiled, for as long as
`shader.wgsl` and `bindings.yaml` hold the bytes they held when it was made. A write to either file, from any origin
(`vfs.contentVersion` moves), makes the next `program()` a new one, and a dispatch through it runs the new text. The
schema `getBindings()` answers is the one the program was made over.
## Writing a mesh's vertices — `kind: vertices`
A mesh's vertices are raw bytes on the GPU, and the engine stores a mesh in one
of two layouts: 92 bytes a vertex with every attribute a `f32`, or 32 bytes a
vertex with normals and tangents quantized to bytes and UVs to shorts. Which one
a mesh got depends on the mesh.
Declare `kind: vertices` and the shader is handed both the buffer and the layout
that mesh is in, plus accessors that address it:
```yaml
bindings:
- { name: verts, kind: vertices } # the mesh, writable
- { name: heights, kind: buffer, access: read, element: f32 }
params:
- { name: lift, type: float, default: 1.0 }
```
```wgsl
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x >= zeroVertexCount()) { return; }
var p = zeroVertexPosition(id.x);
p.y = p.y + heights[id.x] * params.lift;
zeroSetVertexPosition(id.x, p);
zeroSetVertexNormal(id.x, vec3<f32>(0.0, 1.0, 0.0));
}
```
```lua
carve:dispatchOnVertices({ model = meshRef:handle().guid, buffers = { heights }, workgroups = { 64 } })
```
The accessors, over a binding declared `read_write`:
| read | write |
|---|---|
| `zeroVertexCount() -> u32` | — |
| `zeroVertexPosition(i) -> vec3<f32>` | `zeroSetVertexPosition(i, vec3<f32>)` |
| `zeroVertexNormal(i) -> vec3<f32>` | `zeroSetVertexNormal(i, vec3<f32>)` |
| `zeroVertexTangent(i) -> vec4<f32>` | `zeroSetVertexTangent(i, vec4<f32>)` |
| `zeroVertexUv(i) -> vec2<f32>` | `zeroSetVertexUv(i, vec2<f32>)` |
| `zeroVertexColor(i) -> vec4<f32>` | `zeroSetVertexColor(i, vec4<f32>)` |
| `zeroVertexNodeIndex(i) -> u32` | — |
| `zeroVertexWord(i, offset) -> u32` | — |
`access: read` gives you the readers only — a `var<storage, read>` binding
cannot be assigned to, so the writers are left out rather than handed to you
broken.
Once a pass has written a mesh's vertices, the engine bounds that mesh by what
the pass wrote: it reduces the vertices to an AABB every frame and culls against
that, so geometry a pass moves across the scene needs no oversized placeholder
to survive culling. `renderer.mesh.boundsSource(guid)` reports `"compute"` for
such a mesh and `"geometry"` for one still bounded by what it was created with.
A shader declares at most one `vertices` binding; the accessors are generated
for that mesh. It can be declared anywhere in the list — the mesh is bound by
the dispatch, and `buffers` fills the other storage slots in declaration order.
The tangent's `w` carries handedness, and quantized normals/tangents come back
in -1..1 while quantized UVs and colours come back in 0..1, so the values are
the same ones a surface shader sees whichever layout the mesh is in.
## shader.wgsl
Write only `@compute fn main` (and any helpers / `#include`s). The names declared
in `bindings.yaml` are in scope — `data`, `out_tex`, `params.scale`, … — with no
`@group`/`@binding` lines of your own.
```wgsl
// @domain: compute
// Bindings are declared in bindings.yaml — do NOT write @group/@binding here.
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x < arrayLength(&data)) {
data[id.x] = data[id.x] * 2.0;
}
}
```
## Dispatch & runtime
Everything a compute shader does, it does through its reference:
| method | what it does |
|---|---|
| `ref:dispatch(opts)` | `{ buffers, workgroups, params? }` — bind one buffer per declared storage binding, in order |
| `ref:dispatchOnVertices(opts)` | `{ model, buffers?, workgroups, params? }` — bind the mesh `model` names to the `vertices` binding, `buffers` filling the rest |
| `ref:dispatchEx(opts)` | `{ resources, workgroups, params? }` — for shaders mixing textures, samplers and storage textures: one `{ kind, name }` per declared binding, in order; `params = { name = value }` gives the shader's `params:` fields values for this dispatch alone, as `ref:dispatch` takes them. Any other key is refused, naming it |
| `ref:setParam(prop, value)` | write one `params:` scalar uniform |
| `ref:createBuffer(name, opts)` | `{ type, len, usage? }` — a GPU buffer owned by this shader |
| `ref:buffer(name)` | the buffer this shader last made under `name` |
| `ref:getBindings()` | the parsed `bindings.yaml` schema, read and parsed again only after the file is written |
| `ref:getSource()` / `ref:setSource(wgsl)` | read / overwrite `shader.wgsl` |
| `ref:compile()` | compile now instead of on the first dispatch or the first frame a feature pass names it |
| `ref:withIncludes(replacements)` | `{ [module as the shader's WGSL includes it] = shaderModule }` — a program of this shader in which each named `#include` reaches the compiler as the module its value names; answers the key a render pass's `program` or a dispatch takes, compiled again under a new key when the shader, a replacement module or any module the program reaches through its includes is edited (`compute.programState(key)` reads where it stands) |
| `ref:status()` | what the engine did with this shader's dispatches, one record per target |
The `params:` uniform is engine-owned and takes no entry in `buffers` or
`resources`, and neither does a `vertices` binding's layout.
`setParam` writes the uniform every later dispatch reads. A dispatch that
passes `params = { name = value }` reads those values instead, in a copy of the
uniform only it binds, with every name it leaves out at the value the shader
holds — so one shader dispatched twice in a frame over different data reads
different values each time:
```lua
lift:dispatch({ buffers = { a }, workgroups = { 4 }, params = { height = 1.0 } })
lift:dispatch({ buffers = { b }, workgroups = { 4 }, params = { height = 3.0 } })
```
A name the shader does not declare fails that dispatch, and the failure names
what it does declare.
### `dispatchEx` resources
Each `resources` entry fills the binding at its position. Its `kind` says what
the resource is, in the words `bindings.yaml` uses, and the binding decides how
it is read. A slot takes the kind it is declared with; a `texture2d` slot also
reads a storage texture, a side of a history pair or the scene depth, and a
`storage2d` slot also writes this frame's side of a history pair:
| binding's `bindings.yaml` kind | `resources` entry | `name` |
|---|---|---|
| `buffer` | `{ kind = "buffer", name = buf }` | a buffer handle from `ref:createBuffer` |
| `texture3d` | `{ kind = "texture3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` |
| `storage3d` | `{ kind = "storage3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` made with `storage = true` |
| `storage2d` | `{ kind = "storage2d", name = target }` | a storage texture handle from `ref:createStorageTexture2D` |
| `storage2d` | `{ kind = "history_curr", name = history }` | a history pair from `ref:createTextureHistory`: this frame's side |
| `texture2d` | `{ kind = "texture2d", name = tex }` | a handle `ref:copyBufferToTexture` returns, a texture asset's guid once `texRef:handle()` has made it GPU-resident, or a `renderer.texture.create` handle: a render target a render feature draws into, or a texture made from pixels |
| `texture2d` | `{ kind = "storage2d", name = target }` | a storage texture handle, read as a texture |
| `texture2d` | `{ kind = "history_prev", name = history }` / `{ kind = "history_curr", name = history }` | a history pair: the previous frame's side or this frame's |
| `texture2d` | `{ kind = "scene_depth" }` | none: the frame's scene depth |
| `sampler` | `{ kind = "sampler", name = smp }` | a sampler handle from `ref:createSampler` |
A `dispatchEx` is recorded at the start of the frame, ahead of the frame's render
passes, so a render target it reads holds what the previous drawn frame's passes
wrote into it; a pass of a render feature reads what a `dispatchEx` of the same
frame wrote.
`texture3d` and `storage3d` name the same resource, a 3D texture, so either one
fills either slot. The engine's own spellings name the same resources and keep
working: `texture_3d` for `texture3d` and `storage3d`, `texture_2d` for
`texture2d`, and `storage_2d` for `storage2d`. Any other `kind` is refused at the
call, naming every kind it accepts. A `vertices` binding is filled by
`ref:dispatchOnVertices`, and `texture_depth`, `textureCubeArray` and
`acceleration_structure` bindings by a render feature's pass.
```lua
local march = asset.resolve("volume_march", "computeShader")
-- bindings.yaml: density (storage3d), out_tex (storage2d), U (buffer)
march:dispatchEx({
resources = {
{ kind = "storage3d", name = density },
{ kind = "storage2d", name = target },
{ kind = "buffer", name = uniforms },
},
workgroups = { 8, 8, 8 },
})
```
`workgroups` is `{ x, y, z }`, `{ x }`, or a bare `x`, and every dimension it
leaves out is 1. A zero in any dimension is refused: the dispatch is dropped and
recorded as a failure, so it surfaces in `ref:status()` and `compute.failing()`
with the reason. A count derived from how much data there is passes through
`math.max` first, so an empty set dispatches one workgroup rather than none:
```lua
carve:dispatch({ buffers = { heights }, workgroups = { math.max(1, math.ceil(#points / 64)) } })
```
### Buffers and readback (the CPU side)
A buffer is created through the shader that owns it and comes back as a handle.
Pass the handle to a dispatch — including another shader's — to bind it there:
```lua
local double = asset.resolve("@builtin::shaders.compute_double", "computeShader")
-- `type` is the element the shader declares, `len` how many of them.
local data = double:createBuffer("data", { type = "f32", len = 4, usage = { "readback" } })
data:write({ 1.0, 2.0, 3.0, 4.0 }) -- :writeU32 for integer words, :writeBytes for packed bytes
double:dispatch({ buffers = { data }, workgroups = { 1, 1, 1 } })
local pending = data:read() -- starts an async GPU->CPU readback
-- a frame or two later, drain it (nil until it has arrived):
local out = pending:result() -- :resultU32 / :resultBytes read the same bytes another way
data:destroy() -- free it when done
```
`type` is one of `"f32"`, `"vec3"`, `"vec4"`, `"quat"`, `"mat4"`, and `usage`
adds `"readback"`, `"vertex"`, `"index"` or `"indirect"` on top of the storage a
buffer always has. An `"indirect"` buffer holds a draw's arguments where the GPU
reads them, so a shader that compacts geometry writes the drawn count into the
same dispatch that produced it and a render feature's `kind = "draw"` pass
submits exactly that — the `renderFeature` asset type's README documents that
pass and the `storage.indirect` name it reads.
An `"indirect"` buffer also holds the three workgroup counts a compute pass
dispatches over: a render feature pass stating `dispatch = { indirect = buffer }`
runs the counts a pass before it wrote there (`renderFeature`'s README, "Compute
passes").
The handle's key is the shader's guid plus the name you gave it and
a serial, so two shaders that both want a buffer called `data` get one each —
and so do two callers asking this same shader for one. `ref:buffer(name)`
returns the last one made under that name, which is how two callers share one
on purpose.
A buffer that no shader computes — a vertex or index run that is only ever
drawn — is allocated straight from the primitive instead:
`substrate.createBuffer({ name = ..., type = ..., len = ..., kind = "gpu", usage = { "vertex" } })`.
The first dispatch of a shader compiles it, so the very first readback can still
reflect the un-run shader; dispatch again once it is compiled, or `ref:compile()`
to pre-warm. This create/write/dispatch/readback loop is the CPU side of the
resource model in `core/resource-model`.
### Is it compiled?
`ref:compile()` queues the compile; the pipeline is built on the render side
frames later, so that call cannot say whether it produced a program.
A shader whose program the engine holds (`ready`) or is building (`pending`),
compiled again while its `shader.wgsl`, its `bindings.yaml` and every module it
includes hold the content the program was made from, queues nothing and
leaves the program as it is; an edit to any of those files queues the compile
again. A shader that includes a module some code filed under a key of its own
(`shader.registerModule`; the engine's `zero::` names aside) queues the compile
each time, since no file says when that text changed. `compute.programState(ref)` is where that lands:
```lua
if compute.programState(carve) == "ready" then carve:dispatch(opts) end
local state, reason = compute.programState(carve)
if state == "failed" then print(reason) end
```
- `"absent"` — the engine holds nothing under this key and nothing is in
flight: never asked for, or released.
- `"pending"` — a compile was asked for and has not reached the device. A
recompile of a resident program reads pending too, because what it produces
is a different program from the one bound now — which is what makes this the
precondition to wait on after an edit.
- `"ready"` — compiled and resident, so a dispatch naming it binds it.
- `"failed"` — the most recent compile produced no program, and the second
return says why.
A dispatch issued while the program is `"pending"` is held behind the compile
and dropped if it never lands, so a readback taken before `"ready"` reports the
buffer as it was. Wait for `"ready"`, not for a count of frames.
### Did it run?
A dispatch is recorded into a command encoder frames after the call that asked
for it returned, so that call's `true` means "queued", not "ran". `ref:status()`
is where the outcome lands — one record per target, cumulative:
```lua
for _, d in ipairs(carve:status()) do
print(d.target, d.ok, d.dispatches, d.failures, d.lastError)
end
```
`target` is the mesh guid for a `dispatchOnVertices` and the buffers it bound
for a dispatch that writes only those, so two systems driving one shader over
their own buffers read as the two passes they are. `ok` is the most recent outcome; `lastError` says
why the last failure failed and is kept after a recovery. An empty result means
nothing has dispatched this shader at all. `compute.failing()` answers the same
question across every shader at once.
A failing dispatch also posts a notice, so a pass that stops running reports
itself rather than waiting to be found.
### Running one every frame
A `kind = "compute"` substrate job queues one dispatch per frame:
```lua
jobs.register({
phase = "main",
executor = {
kind = "compute",
shader = asset.resolve("carve", "computeShader"),
buffers = { "heights" },
workgroups = { 64 },
},
})
```
### Many dispatches as one call: compute lists
Work that issues many dispatches every frame (a solver's passes, the levels of a
pyramid, a chain of blurs) registers them once as a compute list and queues them
all with one call, so a frame pays for one call rather than one per dispatch:
```lua
local advect = asset.resolve("~.advect", "computeShader")
local project = asset.resolve("~.project", "computeShader")
local key = velA.key .. ":step" -- named from something this system owns
compute.list(key, {
{ write = params, values = { 0, 0, 0, 1 / 60 }, slots = { [4] = "dt" } },
{ program = advect, resources = {
{ kind = "texture3d", name = velA }, { kind = "sampler", name = smp },
{ kind = "storage3d", name = velB }, { kind = "buffer", name = params },
}, workgroups = { 16, 16, 16 } },
{ program = project, resources = {
{ kind = "texture3d", name = velB }, { kind = "storage3d", name = velA },
}, workgroups = { 16, 16, 16 }, slots = { strength = "strength" } },
})
-- every frame:
compute.runList(key, { dt = dt, strength = 0.5 })
```
An entry is a dispatch, binding `buffers` as `ref:dispatch` does or `resources`
as `ref:dispatchEx` does, or a buffer `write` (`offset` in 32-bit words,
`values` as f32, or u32 with `unsigned = true`). `slots` names the values a run
supplies: a `params:` name to a slot on a dispatch, a value's place (from 1) to
a slot on a write. `when = "<slot>"` leaves the entry out of a run that gives
that slot 0, so one list holds the variants a run picks between. Everything
else is fixed when the list is registered, so a list that alternates between two
textures (a ping-pong) is two lists, or one list whose two halves are guarded by
`when`. The entries run in the order the list states them, and runs in the order
they were queued: a write lands after the dispatches before it and ahead of the
ones after it, so a list may write a buffer between two dispatches that read it,
and two runs in one frame each read their own writes.
`compute.list` resolves every reference and handle when it is called and raises
on a malformed entry, naming it; `compute.runList` answers that the run was
queued, and `ref:status()` and `compute.failing()` say what each dispatch did.
Registering again under the same key replaces the list; `compute.dropList(key)`
forgets it when the system is torn down. `fluidSim` steps its whole solver this
way.
## Registration & hot reload
Writing `shader.wgsl` or `bindings.yaml` fires the `.computeShader` assetType's
`onChange`, which compiles it: the binding declarations are generated,
`#include`s expanded, the WGSL validated, and the shader registered. This happens on
create and on every edit, so saving recompiles with no world reload. A shader
with invalid WGSL (a type mismatch, an undefined name) **fails to compile** with
the reason logged (`[compute] Compile of '<name>' failed: …`) and is **not**
registered. You don't need to register a shader before dispatching it — the first
dispatch auto-compiles it on use. `ref:compile()` remains as an optional explicit
pre-warm, only to avoid the one-frame first-dispatch warm-up in a
latency-critical spot.
## What compute is holding, and why a key names nothing
Every buffer, volume, storage target, history pair and sampler a dispatch can
bind is filed under a key, and `compute.observe()` lists all of them with what
each costs:
```lua
local r = compute.observe()
print(r.totals.count, r.totals.bytes)
for _, res in ipairs(r.resources) do
print(res.key, res.kind, res.bytes, res.owner.name)
end
```
A row carries the key verbatim — the same string a dispatch names it by and a
dispatch-failure message prints — plus its `kind`, its `bytes`, its extent and
`format` where it has them, the `usage` bits it was created with, and the frame
it was created on. `owner` is read back out of the key
(`<shader-guid>::<name>#<serial>`), so a resource nothing has ever dispatched
over still names the shader that made it. `compute.resources(ref)` narrows to
one shader's — including the `<shader-guid>::__params` uniform the compile
created for a `params:` block, which the shader owns like any other resource.
`r.totals.bytes` is the `compute` figure of `renderer.gpuMemory()` — the two are
read off the same registries, so a listing accounts for the category exactly.
The same reading is served at `/zero/runtime/compute`.
When a key names nothing, `compute.diagnose(key)` says which of the states the
inventory distinguishes it is in, from the closed set `compute.absentReasons()`
enumerates:
| reason | what the inventory read |
|---|---|
| `resident` | a resource is filed under exactly this key; the row is on `resource` |
| `replaced` | the owner holds the same name at a different serial — `current` names the live key |
| `nameUnused` | the owner holds resources, none under this name |
| `ownerAbsent` | no live resource carries this key's owner |
| `unowned` | the key carries no owner segment, and nothing is filed under it |
| `notPublished` | no renderer has published an inventory, so no key can be answered for |
So a key out of `[compute] dispatch '…' failed` resolves against what exists,
and a typo reports which part of it the engine could not match rather than
coming back empty.
A reason is the inventory at the moment the call read it. The reading is
republished on a frame where a registry gained or lost an entry, so a resource
created and diagnosed inside one script sees the reading from before it was
made; wait a frame and ask again.
## Discovery
- `asset.list("computeShader")` — every registered compute shader.
- `asset.inspect("<name>")` — status, source, parse errors, this README.
- `computeRef:getBindings()` — the parsed `bindings.yaml` schema
(`{ bindings, params }`).
- `compute.programState(ref)` — whether the program is compiled, still
compiling, or failed, and why.
- `compute.observe()` — every GPU resource compute holds, and what it costs.
- `compute.diagnose(key)` — whether a key names a live resource, and why not.
- `profiler.gpuFrame()` — what each dispatch of this shader spends on the GPU.
A dispatch is timed under `compute.<identity>` — the same identity
`asset.resolve` takes, so a timing row names the shader that produced it.
## Common pitfalls
- **Compute shaders don't render** — verify output via a buffer readback or a
debug pass, not a screenshot.
- **`ref:compile()` returns before the program exists** — the pipeline is
built on the render side; `compute.programState(ref)` says when it is
`"ready"`. A dispatch issued before that is held behind the compile and
dropped only if the compile never lands.
- **A dispatch call returning true means queued** — ask `ref:status()` whether
it ran.
- **A destroyed buffer is refused where it is bound** — a handle outlives its
storage, and `buf:alive()` reports which.
- **Binding order is the contract** — `buffers` and `resources` bind in
`bindings:` list order; reordering the list reorders the bindings.
- **Don't write `@group`/`@binding` in `shader.wgsl`** — the engine owns them;
re-declaring is the fastest way to a layout mismatch.
- **Don't infer a mesh's vertex stride** — declare `kind: vertices` and use the
accessors. A wrong stride writes positions correctly and normals into the
wrong word, which renders as flat lighting rather than as broken geometry.
- **Storage-texture format must be storage-compatible** — `r32f` / `r32u` / `rg32f` /
`rgba8` / `rgba8u` / `rgba16f` / `rgba32f`; others are rejected at compile.
- **A key that comes back empty is not the same as one that failed** —
`compute.diagnose(key)` separates a name never used from a generation that
was replaced, and names the live key in the second case.
## Related types
- `.shader`: render-domain shaders (surface, sky, post-process, screen).
## In the Inspector
Selecting a compute shader opens its **Compute** section: whether its program is ready (and why not), how many dispatches it has run and failed in this session (and the last error), tables of the bindings and params its `bindings.yaml` declares, and openers for `shader.wgsl` and `bindings.yaml`.
# guide
A guide is a single-file documentation asset: a `<name>.guide/` folder whose body is `guide.md`, surfaced through the `guides` MCP tool, the `man` shell builtin and the Docs panel. Drop one anywhere under `/zero/source/`, a `.package` included, and it shows beside the built-in guides.
## Linking guides together
A markdown link in a guide is followed when it is clicked in the Docs panel: `[Bindings](controls-guide)` opens another guide by any name `guides read` takes, `[Slots](#save-slots)` a heading of the same guide (its text in lower case, punctuation removed, spaces turned into `-`), `[Slots](save-kit#save-slots)` a heading of another, and `[the module](../saveKit.module)` a file or asset, relative to the guide's own folder. A link the panel cannot follow says why above the guide.
## In the Inspector
Guide: the guide's word count, its headings, and **Open in Docs**, which opens it in the Docs panel.
# Material (asset type)
A material is a named, configured instance of a `.shader`. The shader
defines the surface look (lighting model, available property fields,
texture slots); the material picks values for those fields and a
shader to bind to. Renderable entities reference materials, not
shaders, so the same geometry can wear different materials and the
same material can be reused across many entities.
Entities sharing one material can still differ in a value: every drawn
object carries four `vec4` lanes of its own that a surface shader reads
as `input.shader_data[lane]` and `renderer.instanceData.set` writes. Use
that for a dissolve at its own progress per subject, a hit flash at its
own age, a fill level per instance — a material per entity is for when
the LOOK differs, not when a number does.
> New to how a material relates to its shader, its textures, and the live GPU
> material behind it? Read `core/resource-model` first. It also covers the
> difference between an authored `.material` asset (this type) and a runtime GPU
> material made with `renderer.material.create`.
## When to use one
- You want a named surface configuration an entity wears by referencing it
from its `Model` component (`material = "@.../<Name>"`).
- You want runtime property tweaks (`asset.resolve(ref):setProperty(...)`) to
affect every entity using the material at once.
- You want to publish a curated look (`Gold`, `RedGlow`,
`BrickWall`) other authors can reuse without re-typing shader
bindings.
If you need a brand-new lighting model or a custom visual effect, you
need a `.shader` first; the material wraps it.
## Where it lives
- Source: `/zero/source/.../<Name>.material/`
- Identity: `<Name>` (the `.material` suffix strips).
- Folder shape:
- `mat.yaml` — canonical material spec (shader + property values).
**Required.**
- `README.md` / `.metadata` — optional prose + tags, indexed when an
author writes real ones.
- `textures/` — optional folder for embedded textures. Validator
allows the folder; its interior is unrestricted.
- `shaders/` — optional folder for a co-located custom shader.
Same rule.
## How to create one
```luau
asset.create("material", "<Name>")
-- Creates: /zero/source/<Name>.material/
-- mat.yaml (shader binding + property scaffold)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("material", "<Name>", { folder = "materials" })
```
Pass the shader and initial values through `asset.create`, then tune with
`setProperty` and keep what you tuned with `saveDefinition`:
```luau
local mat = asset.create("material", "<Name>", { shader = "@builtin::shaders.pbr" })
mat:setProperty("base_color", { 0.8, 0.6, 0.1, 1 })
mat:setProperty("roughness", 0.3)
mat:saveDefinition() -- writes the tuned values into mat.yaml
```
This mints the `.material` asset and returns a handle you tune with
`setProperty`. A set is a runtime change: it reaches the GPU material and every
entity wearing it, and `saveDefinition` is the call that writes it into
`mat.yaml`, so a property driven every frame costs no file write and leaves the
authored file as its author wrote it. A purely runtime `asset.create` lives only
for the session.
For an ephemeral, runtime-only GPU material that is not an asset at all, use
`renderer.material.create` instead (see `core/resource-model`).
## How it operates
1. **Property reflection.** The bound shader's uniform struct fields
become the material's configurable properties — no manual property
declarations needed.
2. **Property values.** `mat.yaml` groups values by type, each block
keyed by the shader's field names: `properties:` holds scalars and
colors/vectors, `ints:` holds integer-typed fields, `bools:` holds
boolean-typed fields, and `textures:` holds texture slots. Omitted
fields take the shader's default. A scalar is a bare number
(`roughness: 0.5`); a color or vector is an array
(`base_color: [1, 1, 1, 1]`). `shader:` is the shader's identity
string. This is the shape every material the engine writes uses. A
`saveDefinition` writes the changed values into the file where they
already stand and leaves the rest of it — its comments, the order of
its keys and blocks, the spelling of its literals, untouched.
3. **Render state.** `render:` holds how the mesh is drawn rather than
what the shader reads: `blend` (the equation the fragment composites
with, also spelled `type`), `cull`, `depth_write`, `depth_compare`,
`topology`, `queue` (the draw order, a whole number: `2000` opaque,
`3000` transparent, `4000` overlay; blended surfaces draw a lower queue
first and back to front within a queue) and the depth bias `depth_bias`,
`depth_bias_slope` and `depth_bias_clamp` (numbers, also spelled
`depthBias`, `depthBiasSlope` and `depthBiasClamp`). A block whose `blend`
blends (anything but `opaque` and `cutout`) and leaves out `depth_write`
and `queue` writes no depth and draws in `3000`. The `.shader` type
README's "The render block" section lists every value each key takes, and
`asset.create`'s `render` argument takes the same keys and values.
4. **Application.** An entity wears a material by referencing it from its
`Model` component (`material = "@.../<Name>"`). Materials affect every entity
that references them; runtime `asset.resolve(ref):setProperty(...)` changes
propagate to all of them immediately, and last until the next mode change
unless `saveDefinition` writes them into `mat.yaml`.
5. **Texture binding.** Texture slots accept `color:r,g,b,a` for
solid colors, `default:white` / `default:black` / `default:normal` for the
engine's own fallback texels, `@builtin::textures.<name>` for builtins,
`path/to/image.png` for file textures, or a render-target handle
for camera renders. The GPU texture cache reads the `color:` and
`default:` forms from the string itself, so a slot written in one names no
asset and carries nothing with the material when it travels; every other
form names a texture asset the slot depends on.
A texture in `base_color_texture` is multiplied by `base_color`: every
built-in surface shader declaring both draws the texture's colour times
`base_color`, channel by channel. Under the default white `base_color` the
texture shows as itself, and a coloured `base_color` tints it. The two
read a colour differently: `base_color` is linear, and the slot reads its
texels as sRGB-encoded, a `color:` value's included, the way it reads an
image. A colour stated in both places is therefore multiplied by a darker
copy of itself: `color:0.62,0.14,0.05,1` in the slot decodes to
`0.34, 0.017, 0.0039`, so beside `base_color` `0.62, 0.14, 0.05` the
surface draws `0.21, 0.0024, 0.0002`, far darker than either. State a
solid colour once, as `base_color`, and leave the slot at its default
white.
6. **Hot reload.** Editing `mat.yaml` repacks the GPU uniform buffer
on the next frame; visible immediately.
**Properties that follow a named value.** `values:` binds a property to a
named value of the entity wearing the material (`values.set(entity, name,
v)`, the `topics/values` guide): `property: valueName`, or
`property: { value: "name", scale: s, offset: o }`, and the property draws
`value * scale + offset` on each entity holding the value, read on the draw.
A boolean reads as 1 or 0, and a number fills every channel of a colour or
vector property. The wearer's own value is read, else its nearest
ancestor's, so a lamp mesh under a car lights from the car's `brake`; a
wearer holding none draws the material's own value. A scalar, vector,
colour or bool property binds (at most 32 per material); a texture slot
does not. `asset.create("material", name, { values = { ... } })` and
`renderer.material.create({ ..., values = { ... } }, key)` take the same
map.
```yaml
values:
emissive_intensity: { value: "brake", scale: 3 }
```
7. **Inspector.** `type.yaml` names `inspector: { type: "inspector.luau" }`,
and `inspector.luau` declares the material's sections beside the generic
ones: `shader` (the bound shader, swappable), `properties` (each shader
field as its typed control) and `textures` (each texture slot as an asset
chip). They read the material through `mat:getShaderRef()` (the bound
shader's ref, `~` expanded) and `mat:getTextures()` (slot name →
`{ ref, name }`: the bound texture's guid and the id the material names
it by). An edit there is an authoring write: `mat:writeProperty(name,
value)` and `mat:writeTexture(slot, texture)` write the value into
`mat.yaml` (and drop the session's own value for it, so the material
reads what the file holds), and `setShader` rewrites the file; inside an
undo operation each file write is recorded, so undo puts `mat.yaml` back.
`setProperty` / `setTexture` stay runtime writes that last until the next
mode change.
## Discovery
- `asset.list("material")` — every registered material.
- `asset.inspect("<name>")` — shader binding, property values,
source path, this type README.
- `ls /zero/source/<Name>.material` lists the files the folder holds.
- `asset.resolve("<name>"):getProperties()` — the property fields exposed by
the bound shader, each at the value it currently holds: what `mat.yaml`
authored until something writes to the material, and the written value from
then on, whichever call wrote it. That is the value the surface is drawn
with. Read them back rather than guessing names; which fields exist comes
from the shader.
- `asset.resolve("<name>"):getDefinition()` — the authored `mat.yaml` bytes,
the value the material rests at.
- `asset.resolve("<name>"):getShader()` — the shader the material binds.
## Authoring conventions
- Use lowercase, descriptive names (`brushed_steel`, `red_glow`,
`tarmac_wet`). Avoid shader-name suffixes in the material name —
the binding lives in `mat.yaml::shader`.
- Drive every property the shader exposes; defaults are a fallback,
not a contract for which fields exist.
- Embed textures alongside the material (`textures/` subfolder) when
they're used only by this material; reference shared textures from
`@builtin::textures.*` or a library.
## Common pitfalls
- **Property names must match the shader's uniform struct exactly**
(case-sensitive). Misnamed properties silently get the shader's
default.
- **`base_color_texture` multiplies `base_color`.** A `color:` texture holding
the same value as `base_color` multiplies the colour by its own
sRGB-decoded value, so the surface renders far darker than the value
written. Write a solid colour as `base_color` alone.
- **Broken shaders break the material.** A material whose shader has a
parse error renders as the magenta checkerboard. Inspect the shader
first if the material looks wrong.
- **`setProperty` targets the material, not the entity.** Changes affect
every entity that references the material.
- **`setProperty` is a runtime change.** It reaches the GPU, not the file:
call `saveDefinition` to write the current values into `mat.yaml`. For a
per-entity override that no other entity sees, give the entity its own copy
with `Model:applySessionMaterial(renderer.material.create(...))`.
- **Renaming the folder changes the identity.** A `Model` component or
other reference to the material is recorded against the material
itself, so renaming or moving it does not break them.
## Related types
- `.shader` — defines what properties exist; required before a
material can bind to it.
- `.preset` — captures a component configuration; conceptually
similar to a material, but for components instead of shaders.
# Module (asset type)
A module is Luau code that runs when other code calls it: other code
pulls it in with `require()` and calls its functions. It has no
lifecycle hooks or callbacks; nothing attaches it to an entity or runs
it every frame. Anything that is code can be a module: a whole game
system (rules, an inventory, a level generator, a match flow), a
helper, a format parser, a registry, a shared algorithm. The engine's
own APIs (`physics`, `input`, `audio`, `camera`, `entity`, `asset`,
`http` and the rest) are modules.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the code runs on an entity, driven by hooks and callbacks, use a
`.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.