# Fire
Fire with its smoke, as a component: a campfire or a hearth, a torch, a brazier
or a candle-sized flame, a bonfire or a pyre, a building, a vehicle or a forest
on fire, or an explosion's fireball. Put it on an entity where the fire burns
and it burns there: flames that glow white-hot at the core through yellow and
orange to dull red at the tips, grey or black smoke rising over them lit by the
scene with a shadow of its own, and a point light that lights the ground, the
walls and the people around it and the smoke from within.
```luau
local e = entity.spawn("campfire")
e.localPosition = { 0, 0, 0 }
e.component.add("Fire", { style = "campfire" })
```
An explosion is a burst: the `explosion` style ignites when the component
starts, and gameplay sets it off again by changing `ignite`:
```luau
local boom = entity.spawn("barrel_explosion")
boom.localPosition = { 6, 0, 3 }
boom.component.add("Fire", { style = "explosion" })
-- later, to set it off again:
local fire = boom.component.get("Fire")
fire.ignite = fire.ignite + 1
```
For smoke alone use the `Smoke` component.
Fires and smoke whose boxes overlap draw as one group, the widest first and the
ones it holds over it: small fires breaking out along a burning barn show in
front of the barn's big smoke plume.
## Styles
| `style` | What it is | Height | Flames | Light |
|---|---|---|---|---|
| `campfire` | Flames a metre high under a thin grey smoke | 5 m | 1.2 m | 6, radius 9 m |
| `torch` | A small flame with a thin wisp of smoke | 1.6 m | 0.6 m | 3, radius 6 m |
| `bonfire` | Roaring flames a few metres high under heavy smoke | 12 m | 3.6 m | 14, radius 20 m |
| `burning` | Wide flames under thick black smoke: a building or vehicle on fire | 22 m | 6.6 m | 24, radius 30 m |
| `explosion` | A fireball that swells, rises and cools into dark smoke over 2.6 s | 9 m | the ball | 40 while it burns |
## Public fields
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `style` | enum | Sync | `"campfire"` | The kind of fire (above). |
| `height` | number | Sync | `0` | Metres the fire and its smoke rise; 0 takes the style's. Its width scales with it. |
| `radius` | number | Sync | `0` | Metres from the centre to the edge of the flames at their base; the smoke widens from it as it climbs, by the style's spread. 0 takes the style's at this height. |
| `flame` | number | Sync | `1` | How bright the flames burn, as a multiple of the style's. |
| `flameHeight` | number | Sync | `0` | Metres the flames reach above the base; 0 takes the style's (the Flames column, scaled with `height`). Tall flames for a house fire: `flameHeight = 10`. |
| `smoke` | number | Sync | `1` | How thick the smoke is; 0 burns clean. |
| `color` | color | Sync | white | Tints the style's smoke colour. |
| `light` | number | Sync | `-1` | The intensity of the point light it casts; -1 takes the style's, 0 casts none. |
| `flicker` | number | Sync | `1` | How far the light rises and falls with the flames (0 to 1); 0 holds it steady. |
| `speed` | number | Sync | `1` | How fast the flames lick and the smoke climbs. |
| `windX`, `windZ` | number | Sync | `0` | Metres the top of the smoke drifts along world x and z, on top of what the scene's wind carries it. |
| `sceneWind` | number | Sync | `1` | How far the scene's wind carries the smoke: 1 drifts with every `Wind` blowing at the source (`Physics.wind`), the top carried by the wind for as long as the smoke takes to climb there (up to half the plume's height; a thin wisp drifts far, a big fire's column stands up to the wind); 0 leans it by `windX` / `windZ` alone. |
| `seed` | number | Sync | `0` | Which turbulence it takes. |
| `loop` | boolean | Sync | `false` | For `explosion`: start over once its smoke has cleared. |
| `ignite` | number | Sync | `0` | For `explosion`: each change sets it off again. |
| `quality` | enum | NoSync | `"auto"` | `auto` follows the device's quality tier; `high`, `medium`, `low`. |
| `lightResponse` | string | Sync | `""` | The `.shaderModule` its light is drawn with, for a drawn style: toon bands, a palette, an ink line, a hard silhouette, flames in flat bands. Empty draws the engine's own light. `@builtin::systems.volumetrics.shaders.medium_light`'s README states what a response defines. |
| `lightResponseParams` | table | Sync | `{}` | Up to sixteen numbers the response reads as `params` (colours, thresholds), in order. |
The light is a point light halfway up the flames, where it lights the ground,
the logs and the walls around the fire and the smoke from within. It stands on
a child entity the fire puts up for the session and keeps out of every save
(`fire:lightEntity()` answers it), and flickers with the flames (`flicker`),
each peer drawing its own.
A fire is seen the way anything is: a wall, a roof or any opaque surface in
front of it hides it. A building on fire shows its flames where it is open, so
stand the fire where the roof has burnt through, in a doorway or at a broken
wall, or above the roofline.
## Drawn in a style
`lightResponse` names a `.shaderModule` of the world that draws the flames and the smoke in a
style instead of the engine's own light: flat lit and shade tones with a hard
edge, a painted palette, an ink line, a crisp silhouette, flames in a few flat bands. The
module includes `@builtin::systems.volumetrics.shaders.medium_light` and
defines `medium_shape`, `medium_light` and `medium_flame`; that module's
README states what each is handed and shows a two-tone response. One module
can draw the clouds (`VolumetricSky`), smoke, fire, volumes and fog banks
(`ParticipatingMedium`) alike, and the volumetrics guide
(`systems/volumetrics/documentation/README`) walks through it.
## Cost
The same as the `Smoke` component's: a 3D texture written every frame the scene
draws and marched over the pixels its box covers, at 48, 40 or 32 voxels across
with 96, 64 or 48 march steps for `high`, `medium` and `low`, over the whole
view at `high` and half its width and height at `medium` and `low`. A campfire
filling a 1920 x 1080 view costs 7 to 14 ms at `high` and 0.38 ms at `medium` on
a desktop GPU; from 9 m away 0.69 and 0.13 ms.
## Related
- `Smoke`: smoke without flames.
- `plume` module: the same fire from a script (`plume.create`).
# ParticipatingMedium
A bank of fog or mist, a cloud of smoke, dust or steam in one place, as a
component. It marks its entity as a volume of fog, smoke, dust or steam,
something light has to travel through. The camera sees it: what is behind the volume comes out
dimmer than what is beside it, and the volume shows by the sunlight and the sky
light it scatters. The ground under it is in its shadow: the volume dims the
scene's sun there and leaves the sky and the other lights. Overlapping volumes
stack.
```luau
local id = entity.spawn("fog_bank").id
entity(id).component.add("ParticipatingMedium", {
sizeX = 30, sizeY = 8, sizeZ = 30,
density = 0.15,
})
```
## Fields
| Field | Meaning |
|---|---|
| `shape` | `"box"` (default) or `"sphere"` |
| `density` | Extinction per world unit. `0` releases the medium. |
| `sizeX` / `sizeY` / `sizeZ` | Half-extents, for a box |
| `radius` | Radius, for a sphere |
| `skyLight` | How much of its surroundings' light the medium takes: the sky, the ambient term and the probes. `1` (the default) lights it as the surroundings light a surface standing in it; `0` leaves the sun alone. |
| `lightResponse` | The `.shaderModule` the medium's light is drawn with, for a drawn style (toon bands, a palette, a hard edge); empty draws the engine's own light. The media in a scene are drawn with one response, with one set of `lightResponseParams`: those of the first registered medium that names one. `@builtin::systems.volumetrics.shaders.medium_light`'s README states what a response defines. |
| `lightResponseParams` | Up to sixteen numbers the response reads as `params`, in order. |
`density` is the physical knob: a ray crossing `d` world units of a medium of
density `k` leaves with `exp(-k * d)` of the light it entered with. A 20-unit
bank at `0.15` therefore passes about 5% of the light straight through it.
The entity's position places the volume; move the entity and the volume and
its shadow move with it.
## Drawn in a style
`lightResponse` names a `.shaderModule` of the world that draws the fog bank in a
style instead of the engine's own light: flat lit and shade tones with a hard
edge, a painted palette, an ink line, a crisp silhouette. The
module includes `@builtin::systems.volumetrics.shaders.medium_light` and
defines `medium_shape`, `medium_light` and `medium_flame`; that module's
README states what each is handed and shows a two-tone response. One module
can draw the clouds (`VolumetricSky`), smoke, fire, volumes and fog banks
(`ParticipatingMedium`) alike, and the volumetrics guide
(`systems/volumetrics/documentation/README`) walks through it.
## Notes
- The medium is lit by the light the surfaces around it are lit by, in the
same frame: the scene's own sun, and where the sun does not reach, the
ambient term, the sky and the reflection probes the environment captured and
the baked light-probe volumes, so the side of a fog bank turned from the sun
reads like fog rather than a dark box. The ambient term and the sky reach a
point of the medium as far as it sees the sky past every surface standing
over it, a tree's crown or a roof, movable and instanced ones included, so a
bank under a canopy takes the sky the canopy leaves open; the reflection
probes and light-probe volumes light it as they light a surface there. Its
shadow falls the way the scene's
shadows do and follows the sun, and with the sun, the ambient and the sky
dark the medium is black.
- The medium dims the sun's light on the surfaces under it, so a thick bank's
shadow reads like an opaque blocker's: lit by the sky and the ambient.
See `mediaTransmittance` for the scene-wide settings and the direct API,
`quality` among them: how finely the view rays sample the media, following the
device's quality tier unless the scene names a level
(`mediaTransmittance.set({ quality = "high" })`).
# Smoke
Smoke rising from a chimney, a stove pipe, a vent, a kettle or a cooling tower,
the wisps over embers or ruins, the thick black column over a city block, an
oil well or a wreck seen from far away, or the puffs of a smoke signal: a smoke
volume lit by the scene, as a component.
Put it on an entity where the smoke leaves (the top of the chimney) and the
smoke rises from there, with the sun on one
side and the smoke's own shadow on the other, greyed by the ambient light and
lit by the lamps near it, a lamp inside it from within. It
churns as it climbs, widens, thins toward the top and drifts with the wind.
```luau
local e = entity.spawn("chimney_smoke")
e.localPosition = { 4, 9, -2 } -- the chimney's top
e.component.add("Smoke", { style = "chimney", windX = 2 })
```
Smoke with a blaze under it is the `Fire` component. Plumes whose boxes overlap
draw as one group, the widest first and the ones it holds over it.
## Styles
| `style` | What it is | Height |
|---|---|---|
| `chimney` | A thin grey column from a chimney or a stove pipe | 7 m |
| `steam` | White steam from a vent, a kettle or a hot spring, thinning out fast | 3.5 m |
| `smoulder` | Low, wide grey wisps over embers or ruins | 2.5 m |
| `column` | A tall, thick black column over a city block, an oil well or a wreck | 30 m |
| `signal` | Separate puffs rising one after another | 9 m |
## Public fields
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `style` | enum | Sync | `"chimney"` | The kind of smoke (above). |
| `height` | number | Sync | `0` | Metres it rises; 0 takes the style's. Its width scales with it. |
| `radius` | number | Sync | `0` | Metres from the centre to the edge of the opening the smoke leaves (a chimney's flue, a vent, the fire under a column); the smoke widens from it as it climbs, by the style's spread (a `column` from 2.5 m to 9 m over its 30 m). 0 takes the style's at this height. |
| `density` | number | Sync | `1` | How thick the smoke is, as a multiple of the style's. |
| `color` | color | Sync | white | Tints the style's smoke colour. |
| `speed` | number | Sync | `1` | How fast it climbs and churns. |
| `windX`, `windZ` | number | Sync | `0` | Metres the top drifts along world x and z, on top of what the scene's wind carries it. |
| `sceneWind` | number | Sync | `1` | How far the scene's wind carries the smoke: 1 drifts with every `Wind` blowing at the source (`Physics.wind`), the top carried by the wind for as long as the smoke takes to climb there (up to half the plume's height; a thin wisp drifts far, a big fire's column stands up to the wind); 0 leans it by `windX` / `windZ` alone. |
| `seed` | number | Sync | `0` | Which turbulence it takes, so two plumes side by side differ. |
| `quality` | enum | NoSync | `"auto"` | `auto` follows the device's quality tier; `high`, `medium`, `low`. |
| `lightResponse` | string | Sync | `""` | The `.shaderModule` its light is drawn with, for a drawn style: toon bands, a palette, an ink line, a hard silhouette. Empty draws the engine's own light. `@builtin::systems.volumetrics.shaders.medium_light`'s README states what a response defines. |
| `lightResponseParams` | table | Sync | `{}` | Up to sixteen numbers the response reads as `params` (colours, thresholds), in order. |
## Drawn in a style
`lightResponse` names a `.shaderModule` of the world that draws the smoke in a
style instead of the engine's own light: flat lit and shade tones with a hard
edge, a painted palette, an ink line, a crisp silhouette. The
module includes `@builtin::systems.volumetrics.shaders.medium_light` and
defines `medium_shape`, `medium_light` and `medium_flame`; that module's
README states what each is handed and shows a two-tone response. One module
can draw the clouds (`VolumetricSky`), smoke, fire, volumes and fog banks
(`ParticipatingMedium`) alike, and the volumetrics guide
(`systems/volumetrics/documentation/README`) walks through it.
## Cost
The smoke is a 3D texture written every frame the scene draws and marched like
any `Volume`, only over the pixels its box covers. What each level holds:
| Level | Voxels across | March steps | Shadow samples | Local lights | March resolution |
|---|---|---|---|---|---|
| `high` | 48 | 96 | 6 | 4 | the view's |
| `medium` | 40 | 64 | 4 | 2 | half the view's width and height |
| `low` | 32 | 48 | 3 | 1 | half the view's width and height |
`auto` draws `high` on a desktop's or browser's high tier, `medium` on a
handheld's high tier and every medium tier, and `low` on the low tier.
Measured on a desktop discrete GPU with the view at 1920 x 1080, the march of a
campfire's plume filling the whole view costs 7 to 14 ms at `high`, 0.38 ms at
`medium` and 0.35 ms at `low`; seen from 9 m away, 0.69, 0.13 and 0.08 ms. The
fill costs 0.01 to 0.02 ms. A scene holding several plumes close to the camera
draws them at `medium` to keep the frame. The march skips the parts of the box the column cannot
reach.
## Related
- `Fire`: a blaze with its smoke, and the light it casts.
- `plume` module: the same smoke from a script (`plume.create`), every style in
`plume.STYLES`.
- `Volume`: any 3D texture as a volume; `scattering` lights it by the scene.
- `ParticipatingMedium`: a bank of fog, haze or mist filling a box.
# Volume
A smoke plume, a single cloud, a fire, a nebula or an imported VDB grid
standing in the scene, as a component: it renders a 3D voxel texture into the
scene as a volumetric body. A producer (the `volume` module's builders, a
custom compute fill, or `compute.writeTexture3D`) builds the texture and owns
its lifetime, and the component names it in `volumeName`. The entity's world
transform defines the AABB the raymarcher samples.
The volume stands in the scene: the frame marches it for every view it draws
(the viewport, a capture, a render-to-texture camera), against that view's
camera and its depth, so opaque geometry in front of the volume hides it and
geometry inside it cuts it where it stands. The march covers the drawn view's
resolution at the `high` level and half its width and height at `medium` and
`low`, brought up to the view as it is laid over the frame. A disabled `Volume` draws nothing.
`volumeName` is resolved through `Volume.get`, so a volume the `volume`
module built is rendered as it stands — at its own dimensions, from its own
density channel, through its occupancy grid, and out of its brick pool if it
is paged. A name no volume answers to is taken as a bare 3D texture some
other system owns, and `occupancyName` / `isRgba` describe it.
Smoke lit by the scene is `scattering = 1, emission = 0`: the sun lights the
side facing it, the volume shadows its far side, and with every light off it is
black. Rising smoke and fire that need no texture of their own are the `Smoke`
and `Fire` components, which fill and stand a lit volume for you.
## Usage
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 })
cloud:buildOccupancy({ brickSize = 8 })
local e = entity.spawn("cloud_entity")
e.localScale.set(8, 4, 8)
e.component.add("Volume", {
volumeName = "cloud",
occupancyName = cloud.occupancyName,
density = 6.0,
})
```
A paged volume costs what it holds and is named the same way:
```luau
local cloud = Volume.noise({ name = "cloud", size = 128, threshold = 0.6 })
cloud:buildSparse({ brickSize = 8, threshold = 0.01 })
cloud:releaseDense() -- the brick pool is now the only copy
local e = entity.spawn("cloud_entity")
entity(e.id).localScale = { 8, 4, 8 }
e.component.add("Volume", { volumeName = "cloud", density = 6.0 })
```
## Public fields
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `volumeName` | string | Sync | `""` | Required. Name of the volume, or of a bare 3D texture, to render. |
| `occupancyName` | string | Sync | `""` | R8 occupancy texture for a bare texture's empty-space skipping. Empty = no occupancy. A volume the module built carries its own, and a name set against one is reported as left aside. |
| `density` | number | Sync | `1.0` | Density gain multiplier. |
| `absorption` | number | Sync | `1.0` | Beer-Lambert absorption coefficient. |
| `emission` | number | Sync | `1.0` | Emission gain. |
| `color` | color | Sync | `{1,1,1,0}` | RGB tint + density floor in alpha. |
| `stepSize` | number | NoSync | `0` | World units per ray step. `0` = auto-derive from volume extent. |
| `maxSteps` | number | NoSync | `256` | Ray-march step cap. |
| `useOccupancy` | boolean | NoSync | `true` | Toggle empty-space skipping. |
| `quality` | string | NoSync | `"auto"` | The level the march takes `stepSize` and `maxSteps` at: `high` as stated over the whole view, `medium` steps 1.5 times as long under 67 % of the cap, `low` twice as long under half of it, both over half the view's width and height. `auto` follows the device's quality tier. |
| `isRgba` | boolean | Sync | `true` | `false` reads density from the red channel. Left `true`, a volume the module built is read from the channel it was built with, and a bare texture as RGBA. |
| `scattering` | number | Sync | `0` | The share of the scene's light the medium scatters, its albedo. 0 shows the volume by its emission alone; above 0 the sun, the ambient term and the point, spot and rect lights reaching it light it, each dimmed by the volume between it and the light. |
| `anisotropy` | number | Sync | `0.3` | How far the scattering leans forward, -0.95..0.95: smoke between the camera and the sun glows at its rim. |
| `flame` | number | Sync | `0` | Gain of the light a density volume's temperature (its green channel) emits along a blackbody ramp. |
| `flameTemperature` | number | Sync | `1.0` | The temperature that burns white-hot; cooler glows yellow, orange, then dull red. |
| `shadowSteps` | number | NoSync | `6` | Samples of each march toward a light, the shadow the volume casts on itself (half as many toward a local light); 0 casts none. Scaled by `quality` (`medium` two thirds, `low` half). |
| `lights` | number | NoSync | `4` | How many of the scene's local lights a sample takes. Scaled by `quality` (`medium` half, `low` a quarter). |
| `lightResponse` | string | Sync | `""` | The `.shaderModule` the volume's light is drawn with, for a drawn style: toon bands, a palette, an ink line, a hard silhouette, flames in flat bands. Empty draws the engine's own light. `@builtin::systems.volumetrics.shaders.medium_light`'s README states what a response defines. |
| `lightResponseParams` | table | Sync | `{}` | Up to sixteen numbers the response reads as `params` (colours, thresholds), in order. |
All public fields use the `Field.<kind>(default, Sync|NoSync)` schema.
Visual params (look, tint, density) propagate Sync; quality knobs
(stepSize, maxSteps, useOccupancy, quality) are NoSync, so each client picks
its own perf/quality point.
Under `auto` a desktop's or a browser's high tier draws `high`, a handheld's
high tier and every medium tier `medium`, and the low tier `low`
(`renderer.qualityTier()`, `@builtin::modules.qualityLevels`), and
`renderer.setQualityTier` moves it on the next frame. The `graphics-quality`
guide lists what each level costs.
`Volume.draws()` names each draw's `quality`, the `level` its march is packed
at, the `stepSize` and `maxSteps` it marches there and the share of the view
its march covers (`resolution`); a draw following the
tier is packed again at the level in force on the frame after the tier moves.
## Lifecycle
- **`awake`** — no-op. The volume texture is owned by the producer
and looked up lazily on the first `update`.
- **`update(dt)`** — resolves `volumeName` through `Volume.get`, falling
back to a wrapper over a bare texture of that name, and stands it in the
scene with this frame's box and settings (`Volume:draw`). The resolution
runs every frame, so a volume built, paged or destroyed after this
component attached is picked up on the next one.
- **`editorUpdate(dt)`**: the same draw in edit mode, so the volume
shows while the scene is being edited.
- **`onDisable`** / **`onDestroy`**: take the draw down
(`Volume.withdraw`), so the frame draws nothing of the volume. The next
update after the component is enabled again stands it back up. The last
draw to go takes the `volume` render feature down.
- **`onPropertyChanged(key, value, old)`** — drops the resolved volume
when `volumeName`, `occupancyName`, or `isRgba` changes, forcing a
re-resolve on the next frame.
## Related
- `volume` module — texture builders and name lookup (`Volume.noise`,
`Volume.get`, `Volume.wrap`, `:buildSparse`, `:draw`, `Volume.draws`).
- `vdb_to_zvol.importer` — VDB → dense voxel pipeline that produces
textures consumable by this component.
- `volumeDemos` / `volumetricSky` packages — worked examples.
# VolumeSequence
Plays an open volume sequence through an entity's transform AABB.
The sequence is opened by a producer and named here — the same split the
`Volume` component makes between "what data to render" and "where it appears
in the world". Each tick the component advances the playhead and stands the
frame that is resident in the scene as a draw of the `volume` module, in both
play and edit mode, so the run animates while it is being authored. The frame
marches the draw for every view it draws, against that view's camera and its
depth, so geometry in front of the run hides it. Disabling the component takes
the draw down.
```luau
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
Seq.open({ name = "plume", frames = paths, resident = 3, fps = 24 })
local id = entity.spawn("plume_entity").id
entity(id).localScale = { 8, 8, 8 }
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
`quality` is the level the march takes `stepSize` and `maxSteps` at, as on
`Volume`: `auto` (the default) follows the device's quality tier and moves
with `renderer.setQualityTier`, and `low`, `medium` or `high` holds that level
on every device (the `graphics-quality` guide lists what each level draws).
`scattering`, `anisotropy`, `flame`, `flameTemperature`, `shadowSteps` and
`lights` light the run as they light a `Volume`: `scattering` above 0 lets the
scene's sun, ambient term and nearby lights light it with a shadow of its own,
and `flame` makes a density run's temperature channel glow along a blackbody
ramp, so a smoke or explosion cache reads lit and burning.
`lightResponse` names a `.shaderModule` that draws the run in a style instead
of the engine's own light (toon bands, a palette, a hard silhouette, flames in
flat bands), with up to sixteen numbers in `lightResponseParams`, as on
`Volume`; `@builtin::systems.volumetrics.shaders.medium_light`'s README states
what a response defines.
`fps` and `playing` are pushed into the sequence when they change, so a
script calling `seq:setFps()` / `seq:pause()` between two ticks is left
standing until the authored value itself moves.
The component does not own the sequence: despawning the entity leaves the
ring allocated, and `volumeSequence.close(name)` is what frees it.
## Sharing
The playhead, the rate and the ring belong to the sequence, so several
entities naming one run play the same frame from the same three textures:
the playhead advances once per engine frame however many components tick it,
and the rate is whichever component's `fps` moved last. Give each entity its
own run when they should play independently.
Each component stands a draw of its own, so a run beside a `Volume`, or two
runs, are all drawn, the nearer laid over the further.
# VolumetricLighting
Light shafts, god rays and glowing air, as a component. It is the air between
the camera and the scene: add it to an entity and light travelling through that
air scatters toward the viewer, so a lamp becomes a glow rather than an
invisible point and the sun cuts shafts where something crosses it, through
the trees of a forest, a window or a gap in a wall.
```lua
local id = entity.spawn("air").id
entity(id).component.add("VolumetricLighting", {
density = 0.06,
anisotropy = 0.7,
})
```
Every field is live — editing one in the inspector changes the air on the next
frame, and the values persist with the scene. Setting `density` to 0 empties the
air and releases the passes while keeping the rest authored; removing the
last one in the scene clears it.
| field | effect |
|---|---|
| `density` | How much medium there is per world unit at the reference altitude. 0 is off. |
| `heightFalloff` / `heightRef` | How fast density thins with altitude, and the altitude `density` is quoted at. 0 falloff fills the scene evenly. |
| `steps` | Samples along each view ray. More resolves a beam's edge more cleanly. |
| `colorR/G/B` | What the medium scatters. Warm dust and cold mist differ here. |
| `anisotropy` | How forward-biased the scattering is, in (-1, 1). Positive values throw light onward, so haze blooms around a source you look toward. |
| `sunIntensity` / `sunColorR/G/B` | A scale and a tint on the scene's sun as it lights the medium: at 1 and white the medium takes the sun as the surfaces do, so a setting sun dims the haze and a sun switched off lights none of it. |
| `lightScale` | The scene lights' contribution to the medium. |
| `skyLight` | How much of its surroundings' light the medium takes: the sky, the ambient term and the probes. 1 (the default) lights it as the surroundings light a surface standing in it; 0 leaves the sun and the lights alone. |
| `skySource` | The sky light the medium takes the sky's light from, by its identity: the scene's own (`@builtin::systems.sky.skyLight`, the default), at the diffuse strength it lights the surfaces with, so haze in front of a daylight sky stands in for the sky it hides. A sky light that is not running hands it none; empty takes none. |
| `shadowSteps` / `shadowDistance` | Samples taken back toward the sun to decide whether a point in the air is lit, and how far they reach. **0 leaves the sun's contribution unshadowed**, so the haze glows evenly and no shafts form. |
| `maxDistance` | How far along the view ray the march runs. A ray that escapes to sky stops here. |
| `quality` | How much the march draws: `auto` (the default) follows the device's quality tier, `high` marches `steps` and `shadowSteps` as stated, `medium` and `low` a coarser grid with a share of them (below). |
The march runs on a grid coarser than the frame and is upsampled over it with
a depth-aware filter. The quality level sets that grid and the share of the
stated samples each ray takes:
| level | grid (each axis of the frame) | `steps` | `shadowSteps` |
|---|---|---|---|
| `high` | 1/2 | all (40 by default) | all (6) |
| `medium` | 1/3 | 60 % (24) | 67 % (4) |
| `low` | 1/4 | 50 % (20) | 50 % (3) |
Under `auto` a desktop's or a browser's high tier draws `high`, a handheld's
high tier and every medium tier `medium`, and the low tier `low`
(`renderer.qualityTier()`, `@builtin::modules.qualityLevels`), and
`renderer.setQualityTier` moves it on the next frame.
`volumetricLighting.drawn()` reads the `level` in force and what the march
draws at it; the `graphics-quality` guide lists what each level costs.
The lights are the scene's own, each scattering on the terms its kind emits on:
a point fills the air around it, a spot fills its cone, a rect reaches the air on
the side its face emits along, and a parallel light lays an even glow across the
whole medium. One added, moved, re-aimed or recoloured at runtime changes the
glow it throws with nothing to keep in step here. The sun is the scene's sun,
lighting the air as it lights the surfaces, so haze under a daylight sun is as
bright as that sun makes it and a setting sun dims it. The air also takes the
light of its surroundings, the light a surface standing in it takes from the
scene's ambient term, the sky and reflection probes the environment captured and
the baked light-probe volumes. The ambient term and the sky reach the air as
far as it sees the sky past the static geometry and past every surface standing
over it (a tree's crown or a roof, movable and instanced ones included), so haze
in front of the sky stands in for the sky it hides, by day and by night, and the
air under a canopy takes the share of the sky the canopy leaves open; the probes
light it as they light a surface there. `skyLight` scales what it takes. With
the sun, every light, the ambient term and the sky dark it scatters nothing.
One body of air fills the scene, so one of these per scene is enough — the last
one to push wins.
The work runs in `lightScattering.renderFeature`; the settings live in
`@builtin::systems.volumetrics.volumetricLighting`, which is also how to drive
them from a script.
# VolumetricSky
Clouds in the sky, as a component. Add it to one entity and the sky gets a
volumetric cloud layer lit by the scene's own sun: a shell around the planet
between two altitudes that reaches the horizon in every direction, its clouds
formed where they stand in the world, cumulus by default. A weather map sets
the coverage, cloud type and density over each place, so a storm over one
valley and clear sky over the next stand in one frame. The component
applies the `volumetricSky` render feature asset with its fields as the values
it states, owned by its entity: an edit applies them again, disabling it turns
its layer off, removing it drops it. It runs nothing per frame. The feature
draws the layer into every view the frame draws, over the sky and over the
surfaces under it, in every mode, carrying the clouds on the wind at
`preset.windSpeed` by the session clock (`multiplayer.roomTime()`), so every
client of a session draws the same clouds with nothing replicated per frame;
while the engine is paused (edit mode, paused play) the clouds stand still.
Adding the component is the whole set-up: no composite is authored.
Of two `VolumetricSky` components, the one edited last is in force; removing
it hands the layer to the other.
## Usage
```luau
-- Defaults (fair-weather cumulus — `Sky.defaultPreset()` hands out a copy
-- of the same table this field defaults to)
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
-- Or apply a captured preset:
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
-- Inline tweak. `component.add` writes the `preset` field as it is given,
-- so a table handed here carries the whole configuration:
local p = require("@builtin::systems.volumetrics.volumetricSky").defaultPreset()
p.coverage, p.cloudType = 0.7, 1.0 -- towering, most of the sky
sky.component.add("VolumetricSky", { preset = p })
-- Weather that differs from place to place:
sky.component.get("VolumetricSky").weatherRegions = {
{ x = -6000, z = 0, radius = 5000, coverage = 0.9, cloudType = 1 },
{ x = 6000, z = 0, radius = 5000, coverage = 0.05 },
}
```
`volumetricSky.module`'s `M.spawn` / `M.configure` take the same parameters
by name, folding each into the current configuration and leaving the rest
where they stand:
```luau
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
Sky.spawn({ coverage = 0.6, cloudType = 0.8, maxSteps = 96 })
```
## Schema (Field<T> / Sync / NoSync)
The shaping / weather / lighting params travel as ONE Sync field —
`preset = Field.table(DEFAULT_PRESET, Sync)` — so replicating a sky change
is **one mutation**, and copying a sky between scenes is **copying one
field**. Per-client quality knobs sit outside the preset as NoSync fields so
each client picks its own tier without disturbing peers.
`SkyPreset` and `DEFAULT_PRESET` are declared by `volumetricSky.module`,
which this component reads its default from and which routes an option by
that same key set — so the shape below and the module's `M.spawn` options
are one declaration.
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `preset` | `SkyPreset` table | Sync | `DEFAULT_PRESET` (cumulus) | All shaping / weather / lighting (see below). |
| `weatherRegions` | table | Sync | `{}` | Up to 16 `{ x, z, radius, falloff?, coverage?, cloudType?, density? }`: the weather inside each, blending into the sky around it across `falloff` (a share of the radius, default 0.5). |
| `stepSize` | number | NoSync | `10` | The shortest ray step, in world units; steps grow with distance. |
| `maxSteps` | number | NoSync | `128` | Ray-march step cap. |
| `shadowSteps` | number | NoSync | `4` | Samples toward the sun for each lit sample. |
| `maxDistance` | number | NoSync | `80000` | How far out each ray is marched; the layer thins into the horizon's haze over its last part. |
| `alphaCutoff` | number | NoSync | `0.99` | Early-exit α threshold. |
| `jitter` | number | NoSync | `1.0` | Ray-origin jitter strength. |
| `renderScale` | number | NoSync | `2` | The layer renders at the target size divided by this. |
| `taaBlendAlpha` | number | NoSync | `0.1` | TAA current-sample weight. |
| `targetWidth` | number | NoSync | `0` | Render target width (`0` = the width of the view the scene is drawn into). |
| `targetHeight` | number | NoSync | `0` | Render target height (`0` = the view's height). |
| `quality` | string | NoSync | `"auto"` | The level the knobs above are traced at: `auto` follows the device's quality tier, `high` traces them as stated, `medium` and `low` a coarser layer with a share of the steps (below). |
| `lightResponse` | string | Sync | `""` | The `.shaderModule` the clouds' light is drawn with: it turns each lit sample's light into the colour it adds and shapes the density the march takes (toon bands, a palette, a rim, a hard silhouette). It includes `@builtin::systems.volumetrics.shaders.medium_light`, whose README states what it is handed, and defines `medium_shape`, `medium_light` and `medium_flame`. Empty draws the engine's own light. The layer marches, shadows, reuses and composites the response's light as it does its own, at every quality level. |
| `lightResponseParams` | table | Sync | `{}` | Up to sixteen numbers the response reads as `params` (colours, band thresholds), in order; a colour `{ r, g, b, a }` counts four. |
| `cloudSize`, `cloudHeight`, `noiseRegenRate`, `wind` | | | | Fields an earlier cloud layer read; a scene stored with them still loads, and the layer reads nothing from them. |
### Preset (`SkyPreset`) shape
Weather: `coverage` (how much of the sky the clouds cover, 0..1),
`cloudType` (0 stratus, 0.5 cumulus, 1 cumulonimbus), `densityGain`
(extinction per world unit inside a cloud), `weatherVariation` (how far
coverage and type vary from place to place), `weatherExtent` (world units the
weather map covers before it repeats).
Cloud form, in world units whatever the layer reaches: `shapeScale` (one tile
of the shape noise; a cloud is about a quarter of it), `detailScale` (one tile
of the detail noise, 0 = `shapeScale / 16`), `detailStrength`, `color`,
`windSpeed` (world units per second), `seed`.
The layer: `cloudBaseAltitude, cloudTopAltitude`, altitudes over the ground
(`PhysicalAtmosphere`'s `groundLevelY`), over a planet of the radius the
physical atmosphere integrates over.
Look (visual, not perf): `phaseG`.
Shadow: `shadowStrength`, the share of the sun's light the clouds' shadow takes
from what the sun lights under them (the ground, a height fog, the volumetric
light, a participating medium, a scattering volume such as `Smoke`), 0 to 1;
0 casts none. The shadow moves with the
clouds (`@builtin::systems.volumetrics.cloudShadow`).
Sun / sky: `sunColor, sunIntensity, horizonColor, zenithColor, groundColor,
ambient`. The clouds are lit by the scene's own sun every frame: the sun's
direction, its colour, and its intensity up to a unit sun, which scales these
too, so a night leaves the clouds dark and a sun at zero leaves them black.
With a `PhysicalAtmosphere` in the scene the sun is the atmosphere's, reaching
each cloud through the air (gold and red as it sinks), the sky around the
clouds is the sky the atmosphere draws in place of `horizonColor`,
`zenithColor` and `groundColor`, and `ambient` states how strongly that sky
lights the clouds, as the share it holds of `horizonColor` and `zenithColor`;
`sunColor` and `sunIntensity` are then the tint and brightness of a high sun.
`sunDir` is deprecated and kept so a stored preset still loads.
A stored preset or a caller stating a key an earlier cloud layer read
(`noiseScale`, `octaves`, `altitudeLow`, `altitudeHigh`, `anvilBias`,
`detailOctaves`, `detailThreshold`, `baseLowRemap`, `baseHighRemap`,
`worleyBlend`, `horizExtent`, `sunDiscSize`) still loads and configures the
sky; the layer reads nothing from them.
See `presets/cumulus_default.preset/preset.yaml` for the canonical
full preset shape, and the module's `DEFAULT_PRESET` table for
the runtime defaults.
## Where the frame time goes
- **The fills** are one-off. The tiling noise (`cloud_noise`, a 128^3 and a
64^3 RGBA8 texture) is filled once per render device; the weather map
(`cloud_weather`, 256x256) again when the weather changes, a fraction of a
millisecond. Coverage, cloud type, `weatherRegions` and the wind refill no
noise: the wind moves the clouds through the world by an offset.
`volumetricSky.volumeBakes()` and `weatherBakes()` count the fills.
- **The raymarch** (`cloud_raymarch`) runs for every view of every frame.
`maxSteps`, `shadowSteps`, `renderScale`, `maxDistance`, `stepSize` and
`targetWidth` / `targetHeight` set its cost, at the quality level in force:
| level | `renderScale` | `maxSteps` | `shadowSteps` | `stepSize` |
|---|---|---|---|---|
| `high` | as stated (2) | all (128) | all (4) | as stated (10) |
| `medium` | x1.5 (3) | 75 % (96) | 75 % (3) | x1.25 (12.5) |
| `low` | x2 (4) | 50 % (64) | 50 % (2) | x1.5 (15) |
Under `auto` a desktop's or a browser's high tier traces `high`, a
handheld's high tier and every medium tier `medium`, and the low tier `low`
(`renderer.qualityTier()`); `renderer.setQualityTier` moves it on the next
frame the sky packs. `volumetricSky.drawnLevel()` reads the level in force
and what the raymarch traces at it; the `graphics-quality` guide lists what
each level costs.
`profiler.gpuFrame()` reports each as a `compute.<shader>` span.
## Field-mutation gotcha
Under the Field<T> / Sync / NoSync schema, `public` is not a plain Lua
table — it's wrapped in a proxy whose `__newindex` metamethod performs
type-checks, marks the field dirty, and queues Sync replication. Writing
`public.preset = p` takes all of those steps. Writing into the table a
field returns mutates it directly and **bypasses the setter** — no Sync
replication, no dirty flag, no `onPropertyChanged`. Always assign the whole
preset / colour table; never index-mutate.
The same caveat applies to `public.preset`: `public.preset.coverage = 0.2`
won't replicate. To change one preset field, copy the table, mutate,
reassign:
```luau
local p = public.preset
local next = {}
for k, v in pairs(p) do next[k] = v end
next.coverage = 0.2
public.preset = next
```
## Lifecycle
- **`awake`** / **`onEnable`**: applies the `volumetricSky` asset with the
fields as stated values, owned by the entity.
- **`onPropertyChanged`**: applies them again.
- **`onDisable`**: turns the application off.
- **`onDestroy`**: drops it. Once no application is in force the feature
goes, and its teardown releases the noise, the weather map, the render
targets and the programs through `volumetricSky.destroy`.
The feature's `render` runs once a frame, after every script of the frame
has written the camera, so the layer is raymarched for the camera the frame
is drawn with; a hard cut composites the layer of the shot it lands on.
## Related
- `volumetricSky.module` — orchestration backend.
- `presets/cumulus_default.preset` — canonical full preset; copy
to author named weather (storm, overcast, dawn, …).
- `Volume.component` — per-entity flow for non-cloud volumetric content.
- `showcase/volumetrics/sky.scene` in the public **Engine Showcase** world — worked example.
# cloudShadow
The shadow the cloud layer (`VolumetricSky`) casts on everything the sun
lights under it. A cloud is density rather than a surface, so the shadow is
the optical depth of cloud between each point and the sun, and the sun keeps
`exp(-tau)` of its light there (scaled by the sky's `shadowStrength`).
Each frame the cloud layer draws, `enqueue` runs three passes for every view,
at the `afterDepthPrepass` seam:
1. `cloud_shadow_map`: a map of lines toward the sun, one per texel, each
marched across the layer through the same clouds the raymarcher draws
(`cloud_density`), recording the optical depth above the layer's base and
above a quarter, a half and three quarters of the way up. The texels are
packed most closely around the camera and still reach as far as the layer
is drawn (`cloud_shadow_space`).
2. `cloud_shadow_apply`: the share of the sun the clouds take from each
surface in view.
3. A composite laying that share into the scene's sun occlusion channel
(`@scene.sunOcclusion`) with the `union` blend, so it stands with a
participating medium's and a contact shadow's share as `a + b - ab`: the
two transmittances multiply, and neither is taken twice. The sun's term
reads the channel, so the clouds dim the sun's diffuse and specular light
alone and the sky, the ambient term and the other lights still reach the
surface.
The air reads the same map. A pass marching it merges what `bindings()` names
into its own `inputs` and `buffers`, includes
`@builtin::systems.volumetrics.shaders.cloud_shadow` and multiplies the sun's
light at each of its samples by `cloud_shadow_transmittance(p, cam, to_sun)`.
The height fog, the volumetric light (`lightScattering`), the participating
media's view march (`mediaShadow`) and the march of every standing volume
(`volume_draw`: `Volume`, `Smoke`, `Fire`) do, so the air and the smoke in a
cloud's shadow are dark and the sun falls through the gaps.
With no cloud layer drawing, nothing is enqueued, the map's parameters say no
shadow is cast, and `cloud_shadow_transmittance` answers 1 without reading the
map.
## Quality levels
| level | map texels | samples per line |
|-------|------------|------------------|
| high | 384 x 384 | 16 |
| medium | 256 x 256 | 12 |
| low | 192 x 192 | 8 |
The level is the cloud layer's own (`VolumetricSky`'s `quality`).
## Direct use
```luau
local CloudShadow = require("@builtin::systems.volumetrics.cloudShadow")
local shadow = CloudShadow.bindings()
ctx.enqueue {
kind = "compute", program = myAirMarch,
inputs = { frame_cam = "@frame.camera", cloud_shadow_map = shadow.inputs.cloud_shadow_map },
buffers = { cloud_shadow = shadow.buffers.cloud_shadow },
}
print(CloudShadow.state().casting)
```
·computeshader · born here
❒asset # emission_raymarch
Marches a camera ray through an emissive volume and writes the result to a 2D
target. Emission accumulates along the ray and density attenuates what is behind
it, so a volume reads as light rather than as a surface.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `vol` | `texture3d` | the volume marched — RGB emission, A density |
| `smp` | `sampler` | how `vol` is filtered along the ray |
| `out_tex` | `storage2d` (rgba16f) | the image the march writes |
| `U` | `buffer` (read, f32) | camera, volume placement and march settings |
`U` carries the inverse view-projection, the volume's world transform, the step
count, density and emission gains, and the target's inverse size.
# VDB → ZVOL importer
Claims `.vdb` (OpenVDB) writes and produces a sibling `.zvol` — the
engine-native dense RGBA8 volumetric format consumed by the volumetrics
system.
This is a standard `importer` asset: `init.luau` returns a
`{ canImport, import }` module that the importer dispatcher
(`@builtin::assetTypes.importer`) loads lazily and runs only when a matching
file is written. It does **not** execute anything at load time.
## Pipeline
1. **Real parse** — if the `openvdb` plugin in the builtin library
(`@builtin::plugins.openvdb`) is loaded, the VDB B-tree is parsed into a
dense RGBA8 voxel buffer and wrapped in a 64-byte ZVOL header.
2. **Procedural fallback** — without the plugin, a deterministic
noise-modulated torus is synthesised (FNV-1a hash of the first 256 source
bytes seeds it) so the importer + demo wiring stays functional. The
`produced_by` field in the result distinguishes the two paths.
## ZVOL header (64 bytes)
| offset | size | field |
|--------|------|-------|
| 0 | 4 | magic `ZVOL` |
| 4 | 4 | u32 version (1) |
| 8 | 4 | u32 width |
| 12 | 4 | u32 height |
| 16 | 4 | u32 depth |
| 20 | 4 | u32 format (1 = rgba8) |
| 24 | 12 | f32[3] aabb_min |
| 36 | 12 | f32[3] aabb_max |
| 48 | 16 | reserved |
| 64 | … | voxel data, `w*h*d*4` bytes, XY-major Z-slowest |
·renderfeature · born here
❒asset # lightScattering
The render passes behind the `VolumetricLighting` component and the
`volumetricLighting` module. Light shafts and glowing air in a scene come from
adding that component to an entity; this feature runs while one stands.
Three compute passes in the `medium` stage, after the fog.
**`vol_scatter`** marches each view ray at half resolution, from the camera to
the surface the ray hits, or to the medium's reach when it escapes to sky, since
an unbounded march would integrate the whole horizon into every sky pixel. At
each step it evaluates the medium's density and accumulates the fraction of the
sun's light sent toward the camera, attenuating by everything already crossed.
The medium's surroundings light it too, as they light a surface standing in it:
the scene's ambient term, the sky and reflection probes the environment captured
and the baked light-probe volumes (`@scene.environment`,
`@scene.environmentSampler`, `@scene.reflectionProbes`), averaged over every
direction through `@builtin::shaderModules.ambient_light`, and the sky light the
medium's `skySource` names (the scene's own, `@builtin::systems.sky.skyLight`,
by default), at the diffuse strength it lights the surfaces with. They change over the
room, the canopy or the sky rather than over a step, so each ray reads them once
per stretch of four, where the medium that stretch holds stands. The sky reaches
that point as far as the point sees it, past the static geometry (the
sky-visibility field) and past every surface standing over it, movable and
instanced ones included: the feature draws the overhead cover map
(`@builtin::systems.skyVisibility.overheadCover`) at `afterLighting`, ahead of
the march, and the march reads it as `overhead_map`. The air under a canopy or a
roof so takes the share of the sky it sees, and the medium's `skyLight` scales
what it takes. Haze in front of the sky stands in for the sky it hides, by day
and by night, and with the sun, every light and the surroundings dark the
medium scatters nothing.
A surface-only renderer draws the pool of light a lamp throws on the floor but
not the beam that carried it there, because nothing between the lamp and the
floor is ever shaded. Marching the ray shades that space.
The sun's contribution is gated by a short march back toward it, tested against
the depth buffer. That is what turns uniform haze into shafts: the medium is lit
only where the path back to the sun is clear, so an occluder carves a dark volume
out of the beam rather than only shading the surface behind it. Because the test
reads the depth buffer, an occluder outside the view frustum does not cast into
the medium.
**`vol_lights`** marches the same rays for the scene's lights that stand
somewhere. The lights are the scene's own. `@scene.lights` is the same buffer
the lit passes read, so a light added, moved or recoloured at runtime changes the
beam it throws with no bookkeeping here. A spot's cone gate is evaluated at the
sample itself rather than at a surface, which is what makes the cone visible as a
volume instead of only where it lands, and a rect lights the sample from the part
of its face nearest to it. Attenuation matches the lit passes' windowed falloff,
so a beam and the pool of light it lands in agree about how far the source
reaches, and the pass spends its work only where that is: a tile of rays marches
with the lights whose reach meets it, a ray with the ones whose reach it crosses,
over the stretch of the ray they reach. A light whose radius reaches no ray costs
the march nothing.
Scattering follows Henyey-Greenstein, so the medium brightens toward a source you
are looking at and stays dim when it is behind you: the difference between haze
that reads as air and haze that reads as a grey wash.
Each ray's first sample is offset by a per-pixel fraction of a step, trading the
banding a fixed step pattern produces for noise.
Consecutive renders of a view share each ray's samples. Each render marches every
other sample of a ray, and lays its half beside the half the view's previous
render marched, taken from where the end of the ray stood in that render, so a
camera holding still sees every sample of the ray for the price of half. The
halves are held in history targets, one pair of images per view, beside the
length of each ray: a ray whose previous render ended at another distance (an
object moved across it), one that falls off the previous picture, and every ray
of a view with no previous render (its first, its first after a cut, a one-shot
capture) march all of their samples.
**`vol_composite`** upsamples both and composites them. The taps are weighted by
how closely their depth matches the full-resolution pixel's, which keeps a beam
from bleeding across a silhouette: the halo a plain bilinear upsample leaves
behind.
The camera comes from `@frame.camera`, the camera of the render target being
drawn, its inverse view-projection to unproject a pixel and its view-projection to
project a point back, so an offscreen capture or an RTT camera marches through
its own matrices at its own resolution.
Parameters arrive through the `vol_params` buffer, packed by the
`volumetricLighting` module.
·renderfeature · born here
❒asset # mediaShadow
Participating media in the frame, for every view it draws. Brought up by
`mediaTransmittance` while a medium is registered and released with the last.
A fog bank or a smoke cloud in one place is the `ParticipatingMedium`
component; adding one to an entity registers it.
| Where | Pass | Work |
|---|---|---|
| `afterDepthPrepass`, order 45 | `media_shadow_apply` | For every surface, the share of the scene's sun the media take on the way to it, written to `@scene.sunOcclusion` |
| `afterLighting` | overhead cover | What stands over each point around the camera (`@builtin::systems.skyVisibility.overheadCover`) |
| `medium` stage, order 29 | `vol_surroundings` | The light the surroundings hand the air at each node of the surroundings grid around the camera, once per render |
| `medium` stage, order 30 | `media_view` | March each view ray across the media in front of the surface: dim what is behind, add the light scattered toward the camera, the surroundings' light read from the grid |
| `medium` stage, order 30 | composite | Lay the result over the frame |
The surroundings grid, the view march and the composite declare
`environmentCapture = false`: the sky fallback and the reflection probes the
media are lit by are captured without them, so each capture holds the light of
the scene as it stands, a recapture leaves the media as they were, and a
reflecting surface is seen through the media in front of it. The sun occlusion
stays in the captures, so the ground a capture sees under a medium is dimmed
as the camera sees it.
## Why the sun occlusion channel
A medium in front of the sun takes the sun's light from the surfaces under it
and leaves the light arriving from every other direction. The sun occlusion
channel is the scene's per-pixel answer to how much of the sun is taken; the
sun's term reads it at the fragment's own pixel, the way it reads the
translucent casters' colour, so the ground under a thick medium is lit by the
sky and the ambient like the ground in an opaque blocker's shadow. It is
written at the depth seam, against this frame's depth and for the camera being
drawn, before anything shades.
What the channel holds is optical depth, not a depth to compare against:
- **Overlapping media stack.** Optical depth is additive, so two volumes that
intersect contribute to the same total with nothing to resolve.
- **Geometry inside a volume is lit by the part it has reached.** The ray toward
the sun starts at the surface, so a post standing in the middle of a fog bank
is dimmed by the half between it and the sun rather than by the whole column.
## Inputs
`@scene.color`, `@scene.depth`, `@frame.camera`, `@frame.light`,
`@scene.environment`, `@scene.reflectionProbes`, and the
`media_params` / `media_volumes` buffers packed by
`@builtin::systems.volumetrics.mediaTransmittance`. Writes
`@scene.sunOcclusion`.
# mediaTransmittance
Participating media (fog, smoke, dust, steam) as the camera and the scene's sun
see them. A ray crossing `d` units of a medium of density `k` keeps
`exp(-k * d)` of its light, and every view of the frame reads the registered
media two ways:
- **Toward the sun, from every surface.** The share of the scene's sun the
media take on the way to the surface is written to the scene's sun occlusion
channel, and the sun's term reads it. The medium dims the sun alone: the sky,
the ambient term and the other lights still reach the surface, so the ground
under a thick bank reads like the ground in an opaque blocker's shadow. A
surface standing inside a medium is dimmed by the part between it and the sun.
- **Along each view ray.** What is behind a medium is dimmed by the media in
front of it, and the media add the light they scatter toward the camera from
the scene's sun (itself dimmed by the media between each point and the sun)
and from their surroundings: the light a surface standing there takes from
the ambient term, the sky and reflection probes the environment captured, and
the baked light-probe volumes, averaged over every direction.
The sun is the one the scene is lit by, read in the same frame the surfaces
read it: a medium follows a day cycle and a scripted sun, and a scene with the
sun, the ambient and the environment dark leaves it black. Optical depth is
additive, so overlapping media stack. A view ray samples the stretch of
medium it crosses `steps` times, so a thin medium is sampled as finely as a
thick one, and the optical depth toward the sun is read in one intersection
per medium (`media_common`).
## Direct use
```luau
local Media = require("@builtin::systems.volumetrics.mediaTransmittance")
Media.set({ steps = 32 })
Media.setMedium("bank", {
position = { 0, 8, 0 },
size = { 20, 6, 20 },
density = 0.15,
})
```
Most scenes attach `ParticipatingMedium` to an entity instead and let it drive
this module.
## API
| Call | Effect |
|---|---|
| `set(opts)` | Scene-wide settings; omitted fields keep their value, and a field that is not a setting is refused by name |
| `setMedium(key, opts)` | Register or move a medium under a stable key |
| `removeMedium(key)` | Drop one medium |
| `get()` | A copy of the settings in force |
| `clear()` | Drop everything and release the passes |
| `active()` | Whether the passes are running |
| `buffers()` | The two buffers the passes read |
### Settings
| Field | Meaning |
|---|---|
| `strength` | How much of the media's effect is applied, `[0, 1]` |
| `steps` | Samples a view ray takes across each stretch of medium it crosses, `[4, 128]` (default 24) |
| `quality` | How finely the view rays sample: `auto` (the default) follows the device's quality tier, `high` takes `steps`, `medium` 67 % of them (16 of 24) and `low` 50 % (12). `drawn()` reads the `level` in force and the `steps` it takes. |
### Media
| Field | Meaning |
|---|---|
| `position` | World-space centre |
| `shape` | `"box"` (default) or `"sphere"` |
| `size` | Half-extents, for a box |
| `radius` | Radius, for a sphere |
| `density` | Extinction per world unit |
Up to 32 media are packed into the records buffer. The outer tenth of each
shape is feathered so a bank does not end at a visible face.
## Cost
A medium costs in proportion to the pixels it covers. Every pass works per
pixel of the view being drawn, and only a view ray that crosses a medium
samples: `steps` samples across each stretch of medium in front of its
surface, each reading the density of the media that ray crosses and the
optical depth toward the sun through the media the sun's light can cross on
its way to that stretch, one intersection per medium. The share of the sun a
surface keeps is one intersection per medium as well. The light of the
surroundings is stated once per render at the nodes of the surroundings grid
(`surroundings_grid`, 16384 nodes) and read at each stretch for eight loads.
While any medium is registered the passes cost about 0.4 ms a frame on a
desktop GPU at 2097x1409 before a medium covers a pixel; a medium filling the
whole view adds about 1.5 ms more there, at the default 24 `steps`
(`systems/volumetrics/documentation/README` has the figures). With nothing
registered the passes are released entirely, so a scene with no media pays
nothing.
Under `auto` a desktop's or a browser's high tier draws `high`, a handheld's
high tier and every medium tier `medium`, and the low tier `low`
(`renderer.qualityTier()`, `@builtin::modules.qualityLevels`), and
`renderer.setQualityTier` moves it on the next frame. The `graphics-quality`
guide lists what each level costs.
# media_common
The participating-media passes' shared ground: the volume record layout, the
occupancy and density of each medium, where a ray enters and leaves one
(`media_span`), and the optical depth a ray collects through them
(`media_optical_depth`): each medium's density times the length of the ray
inside it, measured to where its feathered edge holds half its density, read
in one intersection per medium. Across the whole feather of a box's face that
is the integral of its occupancy over the stretch, and across a sphere's edge
or a box's corner it comes close to it. `media_all`, `media_reached_along`, `volume_density_and_sky_of` and
`media_optical_depth_of` take a set of media as a bit mask, so a pass reads
only the media a ray can reach. The cap on how many volumes one frame carries
(`MAX_VOLUMES` = 32) sizes a fixed array and the 32 bits of a set, so it is a
constant here rather than a param.
·computeshader · born here
❒asset # media_shadow_apply
Writes the share of the scene's sun the participating media take on the way to
each surface into the sun occlusion channel (`@scene.sunOcclusion`), which the
sun's term reads at that pixel. The sun is the one the scene is lit by
(`@frame.light`), and the optical depth is each medium's density times the
length of the ray toward it inside the medium (`media_optical_depth`), one
intersection per medium.
## Includes
- `media_common`
- `@builtin::shaderModules.frame_light`
## Bindings
| name | kind |
|------|------|
| `scene_depth` | `texture_depth` |
| `frame_cam` | `buffer` |
| `scene_light` | `buffer` |
| `media_params` | `buffer` |
| `media_volumes` | `buffer` |
| `sun_occlusion` | `storage2d (rgba8)` |
·computeshader · born here
❒asset # media_view
The participating media as the camera sees them. Each pixel's view ray is
marched across the stretches of medium it crosses in front of the surface (or,
over the sky, until it leaves the last medium), `steps` samples a stretch:
what is behind the medium is dimmed by `exp(-tau)` of the optical depth in
front of it, and the medium adds the light it scatters toward the camera, lit
by the scene's sun (dimmed by the media between each sample and the sun and
by the cloud layer's shadow there, `@frame.light`, `cloud_shadow`) and by its surroundings: the light a surface standing there
takes from the scene's ambient term, the sky and reflection probes the
environment captured and the baked light-probe volumes, averaged over every
direction, the ambient term and the sky as far as the point sees the sky past
what stands over it. The surroundings' light is read from the surroundings
grid `vol_surroundings` states for the view (`surroundings_grid`), once per
stretch. A sample reads the density of the media its ray crosses, and the
optical depth toward the sun through the media the sun's light can cross on
its way to the stretch (`media_reached_along`), so a pixel costs what the
media in front of it are rather than what every registered medium is. With
the sun, the ambient and the environment dark a medium scatters nothing.
## Includes
- `media_common`
- `@builtin::shaderModules.frame_light`
- `surroundings_grid`
- `@builtin::systems.sky.skyLight_read`
- `@builtin::systems.volumetrics.shaders.cloud_shadow`
- `@builtin::systems.volumetrics.shaders.medium_physical`, the light response
the media are drawn with; a program in which the module the media name in
`lightResponse` stands in its place draws them when they name one
(`mediumResponse`). It shapes each step's density and turns the light the
step scatters into the colour it adds, with the parameters at
`media_params[1..5)`.
## Bindings
| name | kind |
|------|------|
| `source_map` | `texture2d` |
| `scene_depth` | `texture_depth` |
| `frame_cam` | `buffer` |
| `scene_light` | `buffer` |
| `vol_surroundings` | `buffer` |
| `media_params` | `buffer` |
| `sky_irradiance` | `texture2d` |
| `media_volumes` | `buffer` |
| `cloud_shadow_map` | `texture2d` |
| `cloud_shadow_smp` | `sampler` |
| `cloud_shadow` | `buffer` |
| `media_out` | `storage2d (rgba16f)` |
# mediumResponse
The light response a medium is drawn with. `VolumetricSky`, `Volume`,
`VolumeSequence`, `Smoke`, `Fire` and `ParticipatingMedium` each name one in
`lightResponse` (a `.shaderModule`) with its numbers in `lightResponseParams`;
left empty, the medium takes the engine's own light
(`shaders.medium_physical`). `shaders.medium_light` states what a response is
handed and the three functions it defines.
- `program(shader, response)`: the program a marcher draws with, the shader
itself or the one in which the response stands in `medium_physical`'s place.
- `params(list)`: the sixteen numbers a response is handed.
- `status()`: each marcher and response asked for, the program it draws with
and where it stands; a response that names no module or fails to compile
reads `failed` with the reason, and its medium draws the engine's own light.
# plume
Smoke and fire from a script: a chimney's smoke, steam, a smoulder, a black
column over a big fire, smoke signals, a campfire, a torch, a bonfire, a
building on fire and an explosion's fireball. A plume writes its smoke (density)
and flames (temperature) into a 3D texture once for each frame the scene draws,
and stands it in the scene through `Volume:draw`, where the scene's sun, ambient
term and nearby point, spot and rect lights light the smoke with a shadow of
its own, and the flames glow along a blackbody ramp. The `Smoke` and `Fire`
components each hold one; use the module directly to drive a plume from a
script you already have (a moving vehicle's exhaust, a scripted sequence).
```luau
local plume = require("@builtin::systems.volumetrics.plume")
local p = plume.create({ style = "campfire" })
local key = plume.drawKey("myFire")
-- every frame:
p:step(dt, { x, y, z }) -- the source, where it reads the scene's wind
p:draw(key, { x, y, z }, entity(id))
-- when done:
p:destroy()
```
## Exports
- `plume.STYLES`: every style by name, each with `about`, its size in metres,
its climb, colour, flames and light.
- `plume.styles() -> { string }`: the style names, sorted.
- `plume.LEVELS`: the voxels across the box each quality level holds; the march takes the volume's levels (`Volume.LEVELS`).
- `plume.create(opts) -> Plume`: `style`, `height`, `radius`, `density`,
`color`, `flame`, `smoke`, `speed`, `wind` (`{ x, z }` metres the top
drifts), `sceneWind` (how far the scene's wind carries it, default 1),
`seed`, `quality`.
- `plume.drawKey(prefix, id?) -> string`: a key for `draw`.
- `plume.optsOf(fields) -> opts`: the options a `Smoke` or `Fire` component's
fields state.
- `p:set(opts)`, `p:step(dt, origin?)` (with the source, the plume leans with
the scene's wind there: `Physics.wind`), `p:draw(key, origin, entity)`, `p:withdraw()`,
`p:ignite()` (a burst again), `p:ended()`, `p:stats()`, `p:destroy()`.
# cumulus_default
Default weather preset for `VolumetricSky.component`: fair-weather cumulus
over the whole sky, warm-afternoon sun, a little under half the sky covered,
the coverage varying from place to place.
## Use
```luau
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
```
The values set the component's `preset` Field.table as a unit — one
Sync replication carries every shaping/lighting parameter to peers. Tweak
by reading the values and changing them before the component is added:
```luau
local values = preset.values("cumulus_default")
values.preset.coverage = 0.7 -- more of the sky covered
values.preset.cloudType = 1.0 -- towering cumulonimbus
sky.component.add("VolumetricSky", values)
```
## Authoring more presets
Capture a sky you have tuned with
`preset.capture({ entity = sky.id, component = "VolumetricSky" }, "<name>")`,
or drop another `<name>.preset/` folder next to this one (or anywhere under
`/zero/source/`); the asset indexer registers it and `preset.values("<name>")`
resolves it. Common alternatives:
- `overcast.preset` — a broad grey sheet (`coverage ~= 0.9`,
`cloudType ~= 0.1`).
- `clear.preset` — barely any cloud (`coverage ~= 0.1`).
- `storm.preset` — towering dark cells (`coverage ~= 0.75`,
`cloudType = 1`, `densityGain ~= 0.08`, `sunColor ~= [0.6, 0.55, 0.5]`).
Weather that differs from place to place (a storm over one valley, clear sky
over the next) is the sky's `weatherRegions` field rather than a preset.
`preset` is one `Field.table`: applying a preset replaces it whole, so
provide every field.
# scattering_common
The light-scattering passes' shared ground: the phase function, the shadow lookup along a ray, the froxel-to-world mapping, and the distance term of each light standing in the medium: a point or spot light's windowed inverse-square law (`zero_punctual_falloff`, from `light_falloff`), and a rect light's window (`zero_area_falloff`), which `vol_lights` takes with the solid angle the rect's face fills seen from a point of the air.
Included with `#include "@builtin::systems.volumetrics.scattering_common"`.
# cloud_density
The cloud layer's density where it stands in the world, read by every pass
that marches the layer: the raymarcher that draws it (`cloud_raymarch`) and
the map of the shadow it casts (`cloud_shadow_map`), so both see the same
clouds.
- `height_profile(h, cloud_type)` — how much cloud a type holds at height
fraction `h` through the layer.
- `weather_at(p)` — the weather map's coverage, cloud type and density over
`p`.
- `cloud_density(p, h, w, t, with_detail)` — the cloud at `p`, seen from `t`
away; without `with_detail` the shape alone.
The including shader declares `shape`, `detail`, `weather`, `noise_smp` and the
layer's uniforms `U` (the layout `cloud_raymarch` states).
·computeshader · born here
❒asset # cloud_layer_surfaces
The cloud layer over the surfaces. Writes each cell of the layer whose scene
pixel a surface stands on, by the frame's depth once the transparent phase has
drawn (`@scene.depth`, the sea's included), and nothing in the cells over sky.
`cloud_layer_composite` lays what it writes over the frame at the head of the
`medium` stage; the sky's cells were laid before the transparent phase.
Bindings (see bindings.yaml): `layer` (texture2d, the accumulated layer),
`scene_depth` (texture_depth, `@scene.depth`), `out_tex` (storage2d rgba16f, the
size of the layer; the dispatch grid covers it).
# cloud_light
The light the cloud layer is lit by, and the air it is seen through, read by
the cloud raymarcher.
With the scene's physical atmosphere (`PhysicalAtmosphere`; the raymarch's
`U[28]` is 1) the clouds stand in that air:
- `cloud_sun_dir()`, `cloud_sun_radiance()` — the atmosphere's sun, its
direction, colour and brightness, scaled by the preset's sun colour and
brightness.
- `cloud_sun_through_air(offset, alt0, radius, sun_dir, zenith_sun)` — the
share of that sun reaching a sample through the air, against what a sun
overhead gives there (`cloud_zenith_sun(altitude)`): white at noon, gold and
red as the sun sinks, fading out over the sun's width once the planet stands
between the sample and the sun. A cloud high in the layer keeps the sun a
little after the ground has lost it, lit from below.
- `cloud_sky(cam_pos, sun_dir)` — the sky around the clouds as the physical
sky draws it: its zenith, its horizon away from the sun (the sky a cloud's
shade faces), the sunlit ground under the
air, and the light from every side (the mean of the zenith and the horizon,
in the proportion the preset's `ambient` holds to the mean of the preset's
own horizon and zenith).
- `cloud_through_air(cam_pos, dir, distance, light, coverage)` — a cloud's
light as it reaches the camera through the air between them, the way the
aerial perspective hazes a surface: the raymarch applies it at the cloud's
mean depth on every ray, over the sky and in front of a surface, so distant
clouds fade into the haze at the horizon.
Without one, the clouds take the scene's own sun (`@frame.light`, through
`@builtin::shaderModules.frame_light`) and the preset's sky colours, which are
the sky of a high sun: `cloud_sky` scales them by `cloud_sky_share()` (the
sun's share, times the daylight its height gives: all of it from about 20
degrees up, none once it is about 6 degrees under the horizon), and the air
terms pass the light through unchanged.
A sunset lights the clouds low and warm, a night leaves them dark, and with
the sun at zero the layer is black.
The including shader binds `scene_light` (`@frame.light`), the uniform `U`
with its `u_vec3` reader, and the atmosphere's `atmo_params`,
`transmittance_lut`, `multiscatter_lut`, `skyview_lut`, `aerial_volume` and
`aerial_smp`, and includes `@builtin::shaderModules.frame_light` and the
atmosphere's `atmo_common`, `atmo_transmittance_lookup`,
`atmo_multiscatter_lookup`, `atmo_integrator`, `atmo_skyview_lookup`,
`atmo_aerial_volume` and `atmo_aerial_lookup` ahead of this module.
# cloud_media_trace (raster shader)
Lays the cloud layer's trace in the media trace (`@scene.media`,
`@scene.mediaSurface`) for the `volumetricSky` render feature: one triangle
over the whole view, whose fragments read the coverage the layer's cells hold
under each pixel (`src`) and lay it as the cloud layer, standing where the
pixel's ray enters the layer's shell, facing back along the ray. A pixel no
cell covers draws nothing.
It runs beside each of the layer's two composites: over the sky (`sky_only`
1, after the opaque scene is lit, before the transparent phase lays its own
trace in front of it) and over the cells a surface stands on (at the head of
the `medium` stage). `cam` is the drawn camera (`@frame.camera`), `U` the
raymarch's uniforms (the planet's radius, the ground's height and the layer's
base and top at words 0 to 3) and `scene_depth` the scene's depth, whose size
the trace is drawn at. The pass writes `@scene.media` at `@location(0)` and
`@scene.mediaSurface` at `@location(1)`, both `"premultiplied"`, and runs only
on a view that keeps the trace.
·computeshader · born here
❒asset # cloud_noise
The cloud layer's tiling noise, filled once into two 3D textures the raymarcher
samples in world space (Schneider's Nubis noise set):
- **shape** (128^3 rgba8): R is Perlin-Worley (gradient noise dilated by
Worley noise), the billowing body of a cloud; G, B and A are Worley FBM at
periods 4, 8 and 16, which erode it.
- **detail** (64^3 rgba8): Worley FBM at periods 2, 4 and 8, which carve the
edge of a cloud into billows and wisps.
Every channel tiles across the texture's edges. The textures hold no weather,
no wind and no extent: `VolumetricSky` places them in world units
(`shapeScale`, `detailScale`), moves them with the wind and reads coverage and
cloud type from its weather map, so none of those ever refills them.
Bindings (see bindings.yaml): `out_vol` (storage3d rgba8, the texture being
filled) and `U` (`[0]` layout: 0 shape, 1 detail; `[1]` seed).
·computeshader · born here
❒asset # cloud_raymarch
The cloud layer's raymarcher: the one shader that draws a `VolumetricSky`.
The layer is a shell around the planet between two altitudes (`cloud_shell`),
so it reaches the horizon in every direction. Its clouds are formed where they
stand in the world: a weather map (`cloud_weather`) states coverage, cloud
type and density over each place; the cloud type sets the height profile
(stratus sheet, cumulus heap, cumulonimbus tower); and two tiling 3D noise
textures (`cloud_noise`) placed in world units form the clouds, the shape's
Perlin-Worley body thresholded by the coverage and the detail eroding its edge
into billows. The wind moves the noise through the world, so drift costs
nothing beyond the march.
Each ray is marched from where it enters the layer with steps that grow with
distance: three at a time across empty air, and a third of one inside a
cloud, entered by taking back the step that found it, so a distant cloud's
edge is placed at the fine step rather than in bands at the coarse one. Each
ray starts a share of a step in, the share uncorrelated between neighbouring
cells and moving through a golden-ratio sequence from one render of a view to
the next (the count of renders the view's accumulation has carried), so the
temporal pass averages the grain a single render leaves. A ray
ends where it leaves the layer, at the scene's surface, or at the
march's reach (where the layer thins into the horizon's haze), and is lit by
the sun through the cloud toward it (a cone of samples, Hillaire's
multiple-scattering octaves, a two-lobe Henyey-Greenstein phase, powder on the
shaded side) and by the sky, darker at a cloud's base than at its top.
The light is `cloud_light`'s. With the scene's physical atmosphere the sun
reaches each sample through the air (white at noon, gold and red low, gone
once the planet hides it), the sky around the clouds is the atmosphere's own,
and every ray carries its cloud through the air to the camera at the cloud's
mean depth, over the sky and in front of a surface alike, so distant clouds
fade into the horizon's haze and a cloud in front of a far surface takes the
air of its own distance. Without
one the clouds take the scene's sun and the preset's sky.
Each sample's light becomes the colour it adds through the light response
(`medium_light`), and the density the march takes through `medium_shape`:
`medium_physical`, the light above, unless the sky names a response of its own
(`lightResponse`), which the layer draws with a program in which that
response's module stands in `medium_physical`'s place
(`@builtin::systems.volumetrics.mediumResponse`). The response is handed the
sky's `lightResponseParams` at `U[64..80)`.
It writes scene-linear light premultiplied by coverage, with coverage in
alpha; the display stage tone-maps it with the rest of the frame.
Each cell records what its march was made from in the reuse record, a history
target with one pair of images per view: where its ray ended (the depth of the
surface along it, where that surface stands beyond where the ray enters the
layer), how many renders in a row it was marched from the same inputs, and the
reuse key (`U[30]`, which moves with everything else the march reads). A cell
whose view's camera stood still, whose ray ended where it ended and whose key
held over `U[31]` renders marches nothing and keeps what it made; `cloud_taa`
carries its accumulation as it stood. A kept cell's record holds the end its
last march was made from and how far, in cells, the layer it shows has moved
across the view since (the record's `a` is 1 plus that distance, in steps of
1/1024 of a cell rounded up with the chance the remainder states), so a surface
or a camera creeping by less than a render's check sees brings the march back
once the creep reaches a part in 500 of the end or a quarter of a cell, however
little it moves in each render. The distance is where this render's
view-projection with no sub-pixel offset (`@frame.camera` `[14..18)`) places
the layer's point against where the previous render's (`[5..9)`) placed it,
taken as the change between the two matrices, so a camera that has not moved
adds exactly nothing, render after render, and a camera that moves by any
amount adds that amount.
The scene's depth is drawn through the projection's sub-pixel offset, so a cell
on a surface's silhouette reads the surface under some offsets and what stands
behind it (the sky, or a farther surface) under the others, and a cell on a
surface seen at a slant reads a nearer or farther point of it under each. Each
view walks the offsets in a fixed order (`U[32]` of them,
`renderer.projectionJitter()`), so while nothing moves every offset ends a
cell's ray where it ended it one walk back. The record holds two ends, each
with the offset it is checked at (the first in the record, the second in the
record's second-end target beside it), and its `g` holds which of the two each
render of the last walk ended at: a cell's ray has to end at the end the render
one walk back ended at, of the same kind (over the sky, before the layer, or on
a surface in it), within a part in 500 at the offset that end is checked at and
within the step the march takes through a cloud there at every other. A
settled sky behind a still surface keeps its silhouette's cells under the
jitter, whether the silhouette stands against the sky or against a farther
surface, and a surface that moves by any part of a pixel turns some offset to
another end and marches the cells it turned. A walk longer than eight offsets
is checked against the render before.
Bindings (see bindings.yaml): `shape`, `detail`, `weather` (texture3d),
`noise_smp` (repeating sampler), `out_tex` (storage2d rgba16f), `U` (the layout
is stated at the top of `shader.wgsl`), `frame_cam` (`@frame.camera`),
`scene_depth` (`@scene.depth`), `scene_light` (`@frame.light`), and the
physical atmosphere's `atmo_params`, `transmittance_lut`, `multiscatter_lut`
and `skyview_lut` (`atmosphere.liveTables()`, or stand-ins while no
atmosphere runs), `hist_state` (the layer's history target's state), and the
reuse record: `reuse_out` (storage2d rgba16f), `reuse_prev` and `reuse_state`,
and its second end: `reuse_end2_out` (storage2d rgba16f), `reuse_end2_prev` and
`reuse_end2_state`.
# cloud_shadow
The cloud layer's shadow at a point in the world, for any pass that lights
something by the sun: a surface, a fog, a shaft of light, a participating
medium.
- `cloud_shadow_through_at(p, cam, to_sun)` — the share of the sun's light
the cloud lets through between `p` and the sun: the whole line for a point
under the layer, the part above it for a point inside it, all of it over
the layer. 1 while no layer casts a shadow, while the sun is below the
horizon, and past the map's reach (toward which the shadow fades over the
last fifth).
- `cloud_shadow_optical_depth(p, cam, to_sun)` — the optical depth of that
cloud, `-log` of the share above.
- `cloud_shadow_transmittance(p, cam, to_sun)` — the share of the sun's light
that reaches `p`, at the strength the layer casts with.
A render pass binds what `@builtin::systems.volumetrics.cloudShadow`'s
`bindings()` names and declares:
```yaml
- { name: cloud_shadow_map, kind: texture2d }
- { name: cloud_shadow_smp, kind: sampler, filter: linear, address: clamp }
- { name: cloud_shadow, kind: buffer, access: read, element: vec4<f32> }
```
## Includes
- `cloud_shell`
- `cloud_shadow_space`
·computeshader · born here
❒asset # cloud_shadow_apply
For every pixel with a surface under it, the share of the scene's sun the
cloud layer takes on the way from the sun to that surface
(`1 - cloud_shadow_transmittance`), written for the composite that lays it
into the sun occlusion channel (`@scene.sunOcclusion`) with the `union` blend.
Sky pixels take none.
## Includes
- `@builtin::shaderModules.frame_light`
- `cloud_shadow`
## Bindings
| name | kind |
|------|------|
| `scene_depth` | `texture_depth` |
| `frame_cam` | `buffer` |
| `scene_light` | `buffer` |
| `cloud_shadow_map` | `texture2d` |
| `cloud_shadow_smp` | `sampler` |
| `cloud_shadow` | `buffer` |
| `occlusion_out` | `storage2d (rgba8)` |
·computeshader · born here
❒asset # cloud_shadow_carry
The cloud layer's shadow map carried over from the view's previous render into
this one. Each texel's line toward the sun is found in the map the view's
previous render wrote, by where it crosses the layer's base, and its value is
taken from there: a camera that stands still under a still sky takes every
texel as it stood, and a camera that moves, a sun that turns and a wind that
carries the clouds move the map with them. A line the previous map cannot
answer for is marched here instead (`cloud_shadow_march`): every line on the
view's first render, after a cut, after a change of what the clouds are formed
from, a turn of the sun of more than a quarter of a degree, a wind that
carried the clouds through more than a sixty-fourth of their shape noise's
tile since the previous map (where they are other clouds), or one sinking them
through the noise fast enough to sink them more than a 128th of the tile over
the 16 renders a carried line can stand (the sinking changes their form, and a
long render lets the wind carry them further); and a line the previous map
holds outside its reach or more coarsely than this one does.
The first thread writes the record of what this map is written for (the
generation of the clouds' form, the camera, the lines' direction, the step of
the refresh this render takes, where in the shape noise the clouds were read)
into
`record_out`, which the view's next render recalls (`cloud_shadow_recall`),
and counts the render in the map's counter.
## Includes
- `@builtin::shaderModules.frame_light`
- `cloud_shadow_march`
## Bindings
| name | kind |
|------|------|
| `shape` | `texture3d` |
| `detail` | `texture3d` |
| `weather` | `texture3d` |
| `noise_smp` | `sampler` |
| `U` | `buffer` |
| `frame_cam` | `buffer` |
| `scene_light` | `buffer` |
| `cloud_shadow` | `buffer` |
| `history` | `texture2d` |
| `history_smp` | `sampler` |
| `recalled` | `buffer` |
| `record_out` | `storage2d (rgba32f)` |
| `cloud_shadow_count` | `buffer (atomic<u32>)` |
| `shadow_out` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # cloud_shadow_filter
The cloud layer's shadow map as the passes reading it sample it: the lines the
view being drawn wrote, drawn smooth between them at twice their density. Each
texel is the cubic B-spline through the four by four lines around it, taken as
four bilinear reads. The share of the sun crossing the cloud bends smoothly
from one line to the next, so a cloud's shadow fades over a line or so at its
edge rather than following the map's grid, and the bilinear read a reader
makes of this map runs between texels half a line apart.
## Bindings
| name | kind |
|------|------|
| `map_in` | `texture2d` |
| `map_smp` | `sampler` |
| `shadow_out` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # cloud_shadow_map
The share of the cloud layer's shadow map a render refreshes: one line of
every block of the map (`cloud_shadow_slice` at the step of the refresh
`cloud_shadow_recall` states, and `cloud_shadow_block`, in
`cloud_shadow_space`), marched across the layer toward the sun for the view
being drawn (`cloud_shadow_march`). It runs after `cloud_shadow_carry` has
carried the rest of the map over from the view's previous render and writes
over the lines it marches. One thread per block, so every thread of a
workgroup marches and the pass costs the share of the map it refreshes. It
counts the lines it marches in the map's counter.
## Includes
- `@builtin::shaderModules.frame_light`
- `cloud_shadow_march`
## Bindings
| name | kind |
|------|------|
| `shape` | `texture3d` |
| `detail` | `texture3d` |
| `weather` | `texture3d` |
| `noise_smp` | `sampler` |
| `U` | `buffer` |
| `frame_cam` | `buffer` |
| `scene_light` | `buffer` |
| `cloud_shadow` | `buffer` |
| `recalled` | `buffer` |
| `cloud_shadow_count` | `buffer (atomic<u32>)` |
| `shadow_out` | `storage2d (rgba16f)` |
# cloud_shadow_march
One line of the cloud layer's shadow map marched across the layer, for the
passes that write the map (`cloud_shadow_carry`, `cloud_shadow_map`).
- `cloud_shadow_march(m, cam, line)` — the share of the sun's light crossing
the cloud above the layer's base and above a quarter, a half and three
quarters of the way up, along the line through map coordinate `m` for the
camera at `cam`. The samples run through the same clouds the raymarcher
draws (`cloud_density`), their heights taken over the curved shell
(`cloud_shell`).
- `cloud_shadow_texel_at(texel, dims)` — the map coordinate of a texel's
middle.
The including shader declares the bindings `cloud_density` and
`cloud_shadow_space` name.
## Includes
- `cloud_shell`
- `cloud_density`
- `cloud_shadow_space`
·computeshader · born here
❒asset # cloud_shadow_recall
Reads what the cloud layer's shadow map the view being drawn wrote on its
previous render was written for (its record, three texels of a history target)
into a buffer `cloud_shadow_carry` and `cloud_shadow_map` read next, with the
step of the refresh this render takes: the one after the previous render's,
round the `block * block` steps of `cloud_shadow_slice`. A view whose previous
render left no map to carry (its first render, a cut, a map made at another
size) recalls none: the first word reads 0, and the refresh starts at its
first step.
## Includes
- `cloud_shadow_space`
## Bindings
| name | kind |
|------|------|
| `record_prev` | `texture2d` |
| `record_state` | `buffer` |
| `lines_state` | `buffer` |
| `cloud_shadow` | `buffer` |
| `recalled` | `buffer` |
# cloud_shadow_space
Where the cloud layer's shadow map stands. Each texel holds one straight line
toward the sun, named by where it crosses the plane at the layer's base
altitude, so a point finds its line by following the sun to that plane, with
no search. The texels are spaced from the middle of the map outward by the
square of their distance from it, so the lines near the camera stand closest
together and the map still reaches as far as the layer is drawn.
- `cloud_shadow_line(to_sun)` — the direction the lines run, lifted to at
least `CLOUD_SHADOW_LOWEST_SUN` above the horizon.
- `cloud_shadow_crossing(p, line)`, `cloud_shadow_centre(cam, line)` — where a
line crosses the base plane, and the map's middle for a camera.
- `cloud_shadow_map_at(offset)`, `cloud_shadow_offset_at(m)` — the map
coordinate of a crossing and back.
- `cloud_shadow_block()`, `cloud_shadow_slice(step)` — the side of the blocks
the map is refreshed by, and which line of every block a render marches at
a step of the refresh; a view's renders walk the `block * block` steps in
turn.
- The parameters' accessors: `cloud_shadow_casting`, `cloud_shadow_extent`,
`cloud_shadow_base`, `cloud_shadow_top`, `cloud_shadow_strength` and others.
The including shader declares the parameters as `cloud_shadow`, written by
`@builtin::systems.volumetrics.cloudShadow`.
# cloud_shell
The cloud layer as a shell around the planet: the band between two altitudes
over the ground, centred on a planet whose centre stands straight below the
camera being drawn. The layer reaches the horizon in every direction, recedes
into a thin band where it meets it, and curves away under a camera high above
it. The radius is the one `PhysicalAtmosphere` integrates over (6360 km times
its `worldUnitsPerKm`), so clouds and sky share one horizon.
- `cloud_shell_sphere(alt0, dir_y, radius, a)` — the nearer and farther
distances along a ray to the sphere of altitude `a`.
- `cloud_shell_span(alt0, dir_y, radius, base, top)` — the stretch of a ray
inside the layer, from a camera below, inside or above it.
- `cloud_shell_altitude(offset, alt0, radius)` — the altitude of a point given
as its offset from the camera.
Every sum is taken relative to the camera, which keeps an f32 precise at a
planet's radius.
# cloud_surface
Where a cloud ray meets the scene. Every cloud raymarcher includes it and ends
each ray at the surface the scene drew under its cell (`@scene.depth`), so a
cloud between the camera and the ground covers the ground and the part of the
layer behind a surface adds nothing.
- `cloud_cell_scene_pixel(cell, cells, scene)` names the scene pixel a layer
cell reads its surface from. `cloud_layer_composite` reads the same pixel for
the same cell when it lays the layer over the frame.
- `cloud_surface_distance(cell, cells, cam_pos, inv_view_proj)` is the world
distance to that surface, or the largest finite f32 over sky.
The including shader binds `scene_depth` as `kind: texture_depth`.
·computeshader · born here
❒asset # cloud_taa
The cloud layer's temporal accumulation, per view. Each view the frame draws
(the viewport, every camera rendering into a texture, every capture) runs it
against the images of a history target that belong to that view: `hist_prev`,
what the view's previous render accumulated, and `out_hist`, what this render
accumulates. `hist_state` (the target's state buffer) says whether `hist_prev`
holds that previous render; where it does not, the raymarch is the accumulation.
A capture drawing the viewport's picture runs it against the viewport's images:
`hist_prev` is what the viewport's latest render accumulated.
History is reprojected through the view's own matrices (`@frame.camera`: its
inverse view-projection, its position and its previous render's
view-projection), through the point at the middle of each view ray's traversal
of the cloud volume, where the cloud that ray sees stands. It is clamped to the
3x3 neighbourhood of this render's raymarch, coverage included, and blended
with weight `blend_alpha` on the current sample. The weight the history carries
falls to zero across the last `REPROJECT_BORDER_TEXELS` of the reprojected
frame, so a pixel whose history lies off the previous frame reaches the
raymarch's own output down a gradient rather than across a line.
The grid covers `out_hist`, at the view's size scaled as the layer is; the
raymarch output is read by UV. Where the raymarch kept a cell's result rather
than marching it (`reuse`, the raymarch's reuse record for this render, `a` at
1 or more), the cell's accumulation is carried as `hist_prev` holds it.
Bindings (by name, see bindings.yaml): `cur_tex` (texture2d), `hist_prev`
(texture2d), `smp` (sampler), `out_hist` (storage2d rgba16f), `frame_cam`,
`hist_state` (read `array<vec4<f32>>`), `U` (read `array<f32>`: the volume's
corners at `[0..2]` and `[4..6]`, `blend_alpha` at `[8]`), `reuse` (texture2d).
The `volumetricSky` module enqueues it as a render-feature pass; it reads the
frame's camera and a history target, so it runs inside a view's render.
·computeshader · born here
❒asset # cloud_weather
Fills the cloud layer's weather map: coverage, cloud type and density over
each place in the world, one texel per patch of ground, repeating every
`weatherExtent` world units.
Each texel starts from the sky's `coverage`, `cloudType` and density, varied
by a smooth field of weather over a few kilometres (`weatherVariation`), and
then takes each of the sky's `weatherRegions` in turn: inside a region's
radius its values hold, and across its falloff they blend into what surrounds
it, so a storm over one valley and clear sky over the next stand in one frame
with a gradual edge between them.
The map is a few hundred texels on a side, so a change to the weather fills it
again in a fraction of a millisecond; the raymarcher reads it every frame.
Bindings (see bindings.yaml): `out_map` (storage3d rgba16f, `width x 1 x
depth`) and `U` (the layout is stated at the top of `shader.wgsl`).
# medium_light
What a medium's light response is handed, and the functions a response
module defines. The cloud layer (`VolumetricSky`), a `Volume` draw (`Volume`,
`VolumeSequence`, `Smoke`, `Fire`) and the participating media
(`ParticipatingMedium`) each take the response their component names in
`lightResponse`: a `.shaderModule` that includes this module and defines
- `medium_shape(p: MediumPoint) -> f32`: the density the march takes at a
point. `p.density` keeps the medium's own shape; a step turns a soft edge
into a hard silhouette.
- `medium_light(s: MediumSample) -> vec3<f32>`: the light one unit of coverage
at a lit sample sends toward the camera. `s.physical` keeps the engine's
light.
- `medium_flame(s: MediumSample) -> vec3<f32>`: the light a burning sample
emits per world unit. `s.flame` keeps the engine's blackbody flame.
The march accumulates what the response returns front to back, so a sample
nearer the camera covers the ones behind it as far as its density does.
`medium_shape` thins, hardens or thickens the medium where it stands, and
answers 0 where `p.density` is 0: the marchers step over the empty space
around a medium without asking it, so density answered there shows only at
the samples that land in it. The density it answers is what the view's march
takes, and what the march toward the sun takes inside the clouds and a
volume, so their self-shadow follows the shape.
The shadows the medium casts beyond itself are cast by its own density: the
clouds' shadow on the ground and in each view's shadow map, and a fog bank's
shadow, on itself and on the surfaces under it.
## What a sample carries
`MediumSample`: `physical` (the engine's own light), `sun` (the sun's light
arriving at the medium) with `sun_kept` (the share the medium toward the sun
lets through, 1 on the lit edge) and `phase`, `surroundings` (sky, ambient and
surroundings), `lamps` (the scene's local lights, for a `Volume`), `color`
(the medium's own colour), `density` and `extinction` (that density times the
medium's absorption, per world unit), `height` (0 at the bottom of the layer or
box, 1 at its top), `heat` (a flame's temperature as a share of white-hot) and
`flame`, `view` and `toward_sun`, `kind` (`MEDIUM_CLOUD`, `MEDIUM_VOLUME`,
`MEDIUM_FOG`) and `params`.
`MediumPoint`: `density`, `height`, `heat`, `kind` and `params`.
`params` (`MediumParams`, four `vec4`s `a`, `b`, `c`, `d`) holds the sixteen
numbers the component states in `lightResponseParams`, in order; a number it
leaves out reads 0. A palette, band thresholds and rim colours travel there,
so one response module draws many looks.
`medium_luma(c)` is the luminance of a light.
`s.sun` carries the phase, so a sample seen toward the sun is brighter than
one seen away from it; `s.sun * (0.0795775 / s.phase)` is the sun's light with
the phase taken out (as even scattering sends it), the same from every view,
for a lit tone that stays flat as the camera turns.
These values are stated in `shaders.medium_types`, which this module
includes. This module also states `MEDIUM_AUTHORED` true: a marcher hands its
samples to a response's functions only in a program drawn with one.
## A two-tone response
```wgsl
#include "@builtin::systems.volumetrics.shaders.medium_light"
fn medium_shape(p: MediumPoint) -> f32 {
// A hard silhouette: thin medium is gone, the rest is solid.
return select(0.0, max(p.density, 0.05) * p.params.c.x, p.density > p.params.c.y);
}
fn medium_light(s: MediumSample) -> vec3<f32> {
// The lit tone where the sample keeps more of the sun than a.w, the shade
// tone elsewhere, at the brightness of the light reaching it.
let level = medium_luma(s.sun + s.surroundings + s.lamps);
return mix(s.params.b.rgb, s.params.a.rgb, step(s.params.a.w, s.sun_kept)) * level;
}
fn medium_flame(s: MediumSample) -> vec3<f32> {
return s.flame;
}
```
A component names it by identity in `lightResponse`, with
`lightResponseParams = { 1, 0.97, 0.9, 0.5, 0.45, 0.5, 0.7, 0, 300, 0.08, 0, 0 }`
(the lit tone and its edge, the shade tone, the silhouette's gain and
threshold).
## A hard silhouette and a flat flame
The march adds a sample's light over the coverage the sample adds, so an edge
reads hard only where one step covers everything behind it: where
`s.extinction` times the step reaches well past 1. A gain too small for that
leaves stair-step stripes inside the silhouette, each step only partly
covering the one behind; the clouds need a gain in the tens, smoke and fire in
the hundreds.
`medium_flame` is emission per world unit the ray crosses, which the march
integrates over each step through the medium the step crosses, so an opaque
flame shows its emission over its extinction. A flame band returns its colour
times `s.extinction` to show as that colour wherever the flame is opaque, at
any gain and any step:
```wgsl
fn medium_flame(s: MediumSample) -> vec3<f32> {
if (s.heat <= s.params.d.y) { return vec3<f32>(0.0); }
var band = vec3<f32>(0.9, 0.2, 0.05);
if (s.heat >= s.params.c.z) { band = vec3<f32>(1.0, 0.55, 0.1); }
if (s.heat >= s.params.c.w) { band = vec3<f32>(1.0, 0.9, 0.5); }
return band * s.params.d.x * s.extinction;
}
```
The frame's tone mapping takes the flame like any other light, so a band
brighter than about 1 reads white.
A burning sample is lit as well as burning: the march adds what
`medium_light` returns for the light it scatters and what `medium_flame`
returns for its flame. A response that draws a flame in its bands alone
returns black from `medium_light` where `s.heat` says the sample burns, so a
smoke tone does not wash over the flame; and a silhouette cut in
`medium_shape` that thins smoke away thins a flame's base too unless it keeps
a burning point (`p.heat` above where the flame starts) solid.
A hard edge shows the resolution a medium is drawn at: at the `low` and
`medium` quality levels a `Smoke` or `Fire` draws over half the view's width
and height, so a silhouette there steps at that size; `high` draws it at the
view's own.
# medium_media_trace (raster shader)
Lays the participating media's trace in the media trace (`@scene.media`,
`@scene.mediaSurface`) for the `mediaShadow` render feature: one triangle over
the whole view, whose fragments follow each pixel's view ray through the
registered media up to the opaque surface, and lay what the media take of the
light behind them (one less the share the view march keeps, from the optical
depth along the ray under the media's strength) as a volumetric medium
standing where the ray first enters one, facing back along the ray. A pixel
whose ray crosses no medium draws nothing.
`cam` is the drawn camera (`@frame.camera`), `media_params` and
`media_volumes` the registered media as
`@builtin::systems.volumetrics.mediaTransmittance` packs them, and
`scene_depth` the scene's depth, where each ray ends and whose size the trace
is drawn at. The pass writes `@scene.media` at `@location(0)` and
`@scene.mediaSurface` at `@location(1)`, both `"premultiplied"`, and runs only
on a view that keeps the trace.
# medium_physical
The light response every medium takes unless it names another: the cloud
layer (`VolumetricSky`), a `Volume` draw (`Volume`, `VolumeSequence`, `Smoke`,
`Fire`) and the participating media (`ParticipatingMedium`). It keeps the
density the medium holds (`medium_shape`), the light the engine works out for
each sample (`medium_light` answers `s.physical`) and the engine's blackbody
flame (`medium_flame` answers `s.flame`).
Every marcher includes it by this name; a medium that names a response of its
own (`lightResponse`) is drawn by a program in which the response's module
stands in its place. `medium_light` states the functions a response defines
and what each is handed.
It states `MEDIUM_AUTHORED` false and `medium_light` states it true, so a
marcher drawing a medium with the engine's own light runs none of a
response's work: it draws at the cost it draws at with no response named.
# medium_types
The values a medium's light response is handed, as the engine's marchers (the
cloud layer, a `Volume` draw, the participating media) state them:
`MediumPoint`, `MediumSample`, `MediumParams`, the kinds `MEDIUM_CLOUD`,
`MEDIUM_VOLUME` and `MEDIUM_FOG`, and `medium_luma`.
A response includes them through `shaders.medium_light`, whose README states
what each field holds and the functions a response defines; the marchers and
`shaders.medium_physical` include them here.
·computeshader · born here
❒asset # plume_fill
Writes a plume of smoke and fire into a volume each frame, for the `plume`
module: density in red and temperature in green, the layout the volume march
reads a density volume in, so a `Volume:draw` of it is lit by the scene's
lights with a shadow of its own and glows where it is hot.
The box stands on the plume's source: the floor's centre is where the smoke
leaves. A steady plume is a column that widens as it climbs, leans with the
wind and thins toward the top, its body noise carried upward with time and
curled by a second noise; fire is a flickering cone of temperature at the
source. A burst (`U[14]` above 0) is a fireball that swells, rises and cools to
smoke over its run.
Bindings (see bindings.yaml): `vol` (storage3d rgba16f), `U` (f32 words, listed
at the top of shader.wgsl).
·computeshader · born here
❒asset # volume_draw
The march of a volume standing in the scene, run as a render-feature pass for
every view the frame draws. Each ray leaves the drawn camera (`@frame.camera`),
is clipped against the volume's box and ends at the scene's depth
(`@scene.depth`), so opaque geometry in front of the volume hides it and
geometry inside it cuts the march where it stands. The march itself is the
shared `volume_march` module's, the one `volume_raymarch` runs too.
A volume that scatters (`scattering` above 0) is lit by the light the surfaces
of the view are shaded by: the scene's sun and ambient term (`@frame.light`,
read through `@builtin::shaderModules.frame_light`) and the point, spot and
rect lights reaching each sample (`@scene.lights`, through
`@builtin::shaderModules.scene_lights`), up to the number of local lights the
draw states. Each light is dimmed by the volume between it and the sample, in
`shadowSteps` samples toward it (half as many toward a local light), so the far
side of thick smoke stands in its own shadow; light scattered more than once
greys that shadow rather than leaving it black. The sun is dimmed as well by
the cloud layer's shadow at each sample (`cloud_shadow`, bound from
`@builtin::systems.volumetrics.cloudShadow`), so smoke under a cloud loses the
sun the ground under it loses. With every light dark a volume that neither
emits nor burns renders black.
Each sample's light becomes the colour it adds through the light response it
includes (`medium_physical`, or the module the draw names in `lightResponse`,
which a program of the draw's stands in its place), handed the light's parts:
the sun with nothing between, the share of it the volume lets through, the
ambient term and the local lights.
Bindings (see bindings.yaml): `volume` and `occupancy` (texture3d), `volume_smp`
(sampler), `out_tex` (storage2d rgba16f, sized to the drawn view), `U` (one
`VolumeUniforms`), `frame_cam` (`@frame.camera`), `scene_depth`
(`@scene.depth`), `scene_light` (`@frame.light`), `lights`
(`@scene.lights`), and `cloud_shadow_map` (texture2d), `cloud_shadow_smp`
(sampler) and `cloud_shadow` (buffer), what `cloudShadow.bindings()` names.
The `volume` module enqueues it, with the composite that lays its output over
the frame, for every draw `Volume:draw` stands up.
# volume_march
The volume march `volume_raymarch` and `volume_draw` share: the
`VolumeUniforms` layout, the lookup of a point in a dense texture or a paged
volume's brick pool, the empty-space skip through the occupancy grid or page
table, and `volume_march(ro, dir, t_enter, t_exit, pix)`, which marches a ray
front to back and returns premultiplied colour in rgb and accumulated alpha in
a. The last step ends at `t_exit`, so a march cut short by a surface stops
where the surface stands.
A sample holds a colour, a density and a temperature: a density volume reads
density from red and temperature from green (the layout the fluid solver
writes), an RGBA volume its colour from rgb and density from alpha. Along the
ray the march adds, front to back:
- emission: the sample's colour times its density and `emission`;
- scattered light: the light reaching the sample (`volume_light_at`) times its
colour and `scattering` (the albedo), integrated over the step, with a
Henyey-Greenstein phase of anisotropy `lighting.y` and two weaker octaves for
the light scattered more than once (`volume_scattered`);
- flame: a blackbody ramp over the temperature as a share of the white-hot one
(`flame.y`), times `flame.x` (`volume_flame_color`).
`volume_optical_depth(p, toward, reach, steps)` is the optical depth from a
point toward a light inside the box, the shadow the volume casts on itself.
The light response the including shader includes (`medium_physical`, or the
module a draw names in its place, `shaders.medium_light`) decides the density
each sample takes (`medium_shape`), the colour the scattered light adds
(`medium_light`, handed the engine's light as `physical`) and the flame's
(`medium_flame`, handed the blackbody ramp's as `flame`), with the draw's
sixteen parameters (`VolumeUniforms.response`).
The including shader binds `volume` and `occupancy` (texture3d), `volume_smp`
(sampler) and `U` (one `VolumeUniforms`), and defines
`volume_light_at(p, dir) -> VolumeLight`: the light that reaches point `p` of
the volume, as the radiance a unit of the medium scatters back along `-dir`
before its albedo (`total`), and its parts: the sun's with none of the volume
between (`sun`) and the share of it the volume lets through (`sun_kept`), its
`phase`, the ambient term's (`surroundings`), the local lights' (`lamps`) and
`toward_sun`. `volume_draw` answers it from the scene's lights; `volume_raymarch`,
which renders a volume under no scene light, answers black.
# volume_media_trace (raster shader)
Lays a volume's trace in the media trace (`@scene.media`,
`@scene.mediaSurface`) for the `volume` render feature: the far faces of the
volume's box (36 vertices, drawn with `cull = "front"`), which cover the pixels
the box stands on once each, from outside the box or in it, whose fragments
read the coverage the volume's march (`volume_draw`)
laid at each pixel, filtered up from the march's resolution as the volume's
composite reads it, and lay it as a volumetric medium standing where the
pixel's ray enters the volume's box, facing back along the ray. A pixel the
march laid nothing on draws nothing.
`src` is the march's target, `cam` the drawn camera (`@frame.camera`), `U` the
volume's uniforms (its box at words 5 and 6), `scene_depth` the scene's depth,
whose size the trace is drawn at. The pass writes `@scene.media` at
`@location(0)` and `@scene.mediaSurface` at `@location(1)`, both
`"premultiplied"`, and runs only on a view that keeps the trace.
·computeshader · born here
❒asset # volume_pack
Fills the brick pool from the volume `volume_pages` has just paged.
One invocation per pool voxel. The pool is a grid of blocks, one block per
slot; a block holds a brick plus a one-voxel apron taken from the neighbouring
bricks, so a trilinear sample inside a brick reads what the dense volume would
have given it rather than whatever brick the pool stores next door.
## Bindings
| # | name | what |
|---|---|---|
| 0 | `source` | the dense volume being paged (sampled 3D texture) |
| 1 | `atlas` | the brick pool (`rgba16f` storage) |
| 2 | `page_slots` | four words per slot, written by `volume_pages` |
| 3 | `K` | `PackParams` — volume dimensions and brick edge |
## Why the pool is always `rgba16f`
A pool is written as a storage texture and sampled with filtering. `rgba16f` is
the format that is both: the one-channel formats cannot be written as storage
textures, and `r32f` cannot be filtered without a device feature the engine
does not require. So a scalar volume's density rides in the pool's red channel
— which is where the raymarcher reads density from in density mode — and pays
`rgba16f` per resident voxel. `Volume:sparseStats()` reports the dense and
resident sizes side by side rather than assuming paging is the smaller of the
two.
The pass writes every voxel of the pool, including blocks whose slot was never
handed out: those hold whatever brick their stale slot entry names, and the
page table never points at them.
·computeshader · born here
❒asset # volume_pages
Decides which bricks of a volume are worth storing, and where each one lives.
One invocation per brick. It scans the brick's voxels in the source volume,
and a brick holding anything over `threshold` claims a slot from an atomic
counter. The slot number lands in the page table (`slot + 1`, so 0 keeps
meaning "empty"), and the brick's grid coordinates land in the slot list so
`volume_pack` knows what to copy into that slot.
Nothing is read back to the CPU and no brick waits on another, so the pass can
run every frame — which is what makes the page table usable as the acceleration
structure for a volume whose contents change while it renders.
## Bindings
| # | name | what |
|---|---|---|
| 0 | `source` | the dense volume being paged (sampled 3D texture) |
| 1 | `pages` | page table, one texel per brick (`rgba16f` storage) |
| 2 | `page_alloc` | `[0]` slots handed out, `[1]` bricks that found the pool full |
| 3 | `page_slots` | four words per slot: the brick's x, y, z, and 1 |
| 4 | `P` | `PageParams` — volume dimensions, brick edge, threshold, channel, capacity |
`page_alloc` must be zeroed before each run; the counter is what allocates, so
a stale count hands out slots past the pool.
## The page value
A resident brick's page value is `slot + 1`, split into two digits base 1024
across the texel's red and green channels. The page table is `rgba16f` because
that is the format that is both storage-writable and filterable — the
raymarcher binds it where a sampled 3D texture is expected — and a half float
only carries integers exactly up to 2048, which one digit stays under. A brick
holding nothing writes zero in both channels, so "is anything here" is the sum
against zero, the same test the older single-channel occupancy grid answers.
## Overflow
A brick that arrives after the pool is full is counted in `page_alloc[1]` and
written as empty. The volume renders without it rather than sharing a slot.
`page_alloc[0]` keeps counting past the capacity, so a caller that reads it
back learns the capacity the volume actually needs.
·computeshader · born here
❒asset # volume_raymarch
Generic volume raymarcher. One invocation per output pixel: builds a world-space
ray from the camera inverse view-projection, clips against the volume AABB, and
marches front-to-back, using the occupancy grid to skip empty bricks. Output is
RGBA16F (premultiplied RGB, accumulated alpha) for the caller to composite.
A paged volume marches through the same shader: `volume` is then the brick pool
and `occupancy` the page table, whose texel per brick carries the pool slot that
brick lives in (0 for a brick holding nothing, which is what the empty-space
skip already reads it as). `VolumeUniforms.paged` carries the flag and the
volume's own dimensions, which the pool no longer describes.
Both the skip and the pool lookup find a point's brick by the voxel it lands on
divided by the brick edge — the way the page table and the occupancy grid were
written. A volume that is not a whole number of bricks across has a grid wider
than `dims / brick`, so dividing the normalized coordinate by the grid instead
would name a different brick for the same point. When the dimensions are unknown
(a wrapper was never told them) the grid times the brick edge stands in for them.
Bindings (see bindings.yaml): `volume` (texture3d), `occupancy` (texture3d),
`volume_smp` (sampler), `out_tex` (storage2d rgba16f), `U` (read buffer, a single
`VolumeUniforms` struct).
Usage: resolve it once with `asset.resolve("@builtin::systems.volumetrics.shaders.volume_raymarch", "computeShader")` and
dispatch through the reference with `shaderRef:dispatchEx(...)` (textures/samplers/storage texture require resource binding, not positional buffers); the first
dispatch compiles it.
# surroundings_grid
The layout of the surroundings grid `vol_surroundings` writes and `vol_scatter`
and `media_view` read: 32 by 16 by 32 nodes, 4 units apart across and 2 up,
its corner moved in whole cells with the camera, from 12 units below the
camera's height. Each node
holds the light the medium's surroundings hand a point of the air there, and
`surroundings_grid_at(p, eye)` reads it at any point, blended over the eight
nodes around it (a point past the grid takes the nearest of its edge); the
including pass binds the grid as `vol_surroundings`.
Included with `#include "@builtin::systems.volumetrics.surroundings_grid"`.
·computeshader · born here
❒asset # vol_composite
Composites the scattered light over the scene, depth-aware so geometry occludes it: what `vol_scatter` marched for the sun and the medium, with what `vol_lights` marched for the lights standing somewhere on top.
## Includes
- `scattering_common`
## Bindings
| name | kind |
|------|------|
| `scene_color` | `texture2d` |
| `scene_depth` | `texture_depth` |
| `scatter_map` | `texture2d` |
| `lights_map` | `texture2d` |
| `vol_params` | `buffer` |
| `vol_out` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # vol_lights
Marches the view rays `vol_scatter` marches for the scene's lights that stand
somewhere (point, spot, rect), accumulating the light they scatter toward the
camera through the same medium and at the same samples.
A light lights nothing past its radius, so the work follows the light that
reaches the medium:
- each 8x8 tile of rays gathers the lights whose reach meets the cone its rays
fill, once for the whole tile;
- each ray keeps the tile's lights whose reach it crosses, and marches only the
stretch between the first place one of them reaches and the last, starting
from the transmittance the medium holds there (the density falls off
exponentially with altitude, so the medium crossed before a sample is a
geometric series in closed form);
- each sample takes a light only where its radius reaches it, shadowed from it
by the shadow pages the surfaces are shadowed by
(`@builtin::shaderModules.light_shadows`), so a lamp lights no air on the far
side of a wall.
A ray no light reaches marches nothing. Consecutive renders of a view share the
samples the way `vol_scatter`'s do.
## Includes
- `scattering_common`
- `@builtin::shaderModules.light_shadows`
## Bindings
| name | kind |
|------|------|
| `scene_depth` | `texture_depth` |
| `frame_cam` | `buffer` (`@frame.camera`) |
| `lights` | `buffer` (`@scene.lights`) |
| `shadow_pool` | `texture_depth` (`@scene.shadowPool`) |
| `vol_params` | `buffer` |
| `lights_prev` | `texture2d` (the previous render's half) |
| `length_prev` | `texture2d` (how long each of the previous render's rays was, written by `vol_scatter`) |
| `lights_state` | `buffer` (the history target's state) |
| `history_out` | `storage2d (rgba16f)` |
| `lights_out` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # vol_scatter
Marches each view ray through the medium, accumulating the light the scene's
sun (`@frame.light`), its parallel lights and the medium's surroundings scatter
toward the camera, and the transmittance left behind it. The lights standing
somewhere are `vol_lights`'.
The surroundings light the medium as they light a surface standing in it: the
scene's ambient term, the sky and reflection probes the environment captured
and the baked light-probe volumes, averaged over every direction
(`zpbr_surroundings_in_scatter`, the light `media_view` lights a
`ParticipatingMedium` by). The ray is cut into four stretches, and each reads
them once, at the distance where the medium it holds stands (its samples'
distances, without the per-pixel jitter, weighted by what each holds), and
applies them to its samples' weight. Two neighbouring rays so read their
surroundings at neighbouring points, and the light changes along a ray as
smoothly as the air it crosses. The sky reaches each point as far as the point
sees it, past the static geometry (the sky-visibility field) and past every
surface standing over it (`zero_overhead_openness` over `overhead_map`, the
overhead cover map the feature draws), so the air under a canopy or a roof takes
the share of the sky it sees. The medium's `skyLight` (`vol_params[5].x`) scales
what it takes. Haze in front of the sky so stands in for the sky it hides, by
day and by night, and with the sun, every light, the ambient term and the sky
dark the medium scatters nothing.
The sun and a parallel light arrive the same at every sample of a ray, so the
march sums each sample's weight (how much medium it holds and how much of the
way back is still clear) and applies the lights to the sums once per ray. The
sun's share is gated by a short march back toward it against the depth buffer,
which carves shafts where an occluder blocks it, and scaled by the share of
the sun the cloud layer lets through at the sample (`cloud_shadow`), so the
air under a cloud is dark and a gap between clouds lets a shaft through; its samples are a straight
line through the projection, so each one's clip-space position is the previous
one's plus a step, with no matrix product per sample.
Consecutive renders of a view share each ray's samples: a render marches every
other sample and lays its half beside the half the previous render marched,
taken from the texel where the end of the ray stood in that render. A ray with
no previous render (a view's first, its first after a cut, a one-shot capture),
one the previous render saw end at another distance, and one that falls off the
previous picture march every sample themselves.
## Includes
- `scattering_common`
- `@builtin::shaderModules.frame_light`
- `@builtin::shaderModules.ambient_light`
## Bindings
| name | kind |
|------|------|
| `scene_depth` | `texture_depth` |
| `frame_cam` | `buffer` (`@frame.camera`: its inverse view-projection, position, previous view-projection and view-projection) |
| `lights` | `buffer` (`@scene.lights`) |
| `vol_params` | `buffer` |
| `scene_light` | `buffer` (`@frame.light`) |
| `environment_map` | `textureCubeArray` (`@scene.environment`) |
| `environment_sampler` | `sampler` (`@scene.environmentSampler`) |
| `zero_environment` | `buffer` (`@scene.reflectionProbes`) |
| `scatter_prev` | `texture2d` (the previous render's half) |
| `length_prev` | `texture2d` (how long each of the previous render's rays was) |
| `scatter_state` | `buffer` (the history target's state) |
| `history_out` | `storage2d (rgba16f)` |
| `length_out` | `storage2d (r32f)` |
| `scatter_out` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # vol_surroundings
States the surroundings grid `vol_scatter` and `media_view` light the media by
(each feature states its own grid for the view it draws): at each node of
a 32 by 16 by 32 grid around the drawn camera (4 units apart across, 2 up), the
light a point in the air there takes from its surroundings, the scene's ambient
term, the sky and reflection probes the environment captured and the baked
light-probe volumes, from every direction at once
(`zpbr_surroundings_in_scatter_open`). The ambient term and the sky reach the
node as far as it sees the sky past the static geometry (the sky-visibility
field) and past every surface standing over it (`zero_overhead_openness` over
the overhead cover map); the probes and light-probe volumes hold the light where
they were captured and hand it on as they hand it a surface there.
That light changes over the room or the sky rather than over a step, so the
grid holds it at a few units, and every ray of `vol_scatter` and `media_view`
reads it trilinearly wherever the medium it marches stands, for eight loads
instead of six gathers of the environment. The layout is `surroundings_grid.shaderModule`'s.
# volume
High-level Luau API for 3D textures and volumetric rendering. Composes
the engine's generic `compute.*` primitives into volume-specific
helpers — procedural builders (`sphere`, `box`, `noise`), a sparse
NanoVDB-style occupancy grid for empty-space skipping, volumes standing in
the scene through any entity's transform (`draw`), and a one-call raymarcher
into a 2D target of the caller's own (`render`).
Pairs with the `Volume` component which attaches a built (or imported)
texture to an entity.
## Exports
- `M.create({name, width, height, depth, format?, storage?}) -> Volume` — allocate a fresh, zero-filled 3D texture and return a Volume wrapper.
- `M.wrap({name, format, occupancyName?, occupancyBrick?}) -> Volume` — wrap an existing named texture without recreating it (used by the .zvol viewer).
- `M.get(name) -> Volume?` — the live volume built under that texture name, with its dimensions, channel count, occupancy grid and brick pool.
- `M.names() -> {string}` — every name `M.get` answers to, sorted.
- `M.register(volume) -> Volume` — publish a wrapped volume under its own texture name.
- `M.unregister(name) -> Volume?` — stop answering for a name and hand back the volume that held it, leaving its GPU resources alone.
- `M.releaseTarget(name) -> boolean` — destroy a render target this module built for `render` and forget its size.
- `M.sphere(opts) -> Volume` — procedural Volume filled with a soft sphere SDF.
- `M.box(opts) -> Volume` — procedural Volume filled with a soft box SDF.
- `M.noise(opts) -> Volume` — procedural Volume filled with FBM noise.
- `M.raymarchShaderIdentity() -> string` — absolute identity of the shared raymarch shader.
- `M.compositeShaderSource() -> string` — WGSL source for the post-process composite blending `scene_volume_rt` over the scene.
- `M.FORMATS` — table of canonical format strings (`R8`, `R16F`, `R32F`, `RGBA8`, `RGBA16F`, `RGBA32F`).
- `volume:destroy()` — release the GPU texture + occupancy.
- `volume:writeBytes(bytes) / :writeFloats(floats)` — upload payload to the 3D texture (matches the texture's format).
- `volume:fill(fn)` — CPU procedural fill via `fn(x,y,z) -> color`.
- `volume:readback() -> bytes` — pull the texture's current contents back to Luau.
- `volume:buildOccupancy({brickSize, sampler?})` — build an R8 occupancy companion for empty-space skipping.
- `volume:buildSparse({brickSize?, threshold?, headroom?, capacity?, mode?})` — page the volume into bricks, keeping only the ones holding something. Yields while the brick count reads back — twice unless `capacity` says how many slots to take.
- `volume:refreshSparse()` — re-page from the volume's current contents; two dispatches and no wait.
- `volume:releaseDense()` — free the dense texture and render from the brick pool alone.
- `volume:releaseSparse()` — free the brick pool and page table and go back to rendering the dense texture.
- `volume:readSparseCounts()` — `{ bricks, wanted, overflow, capacity }` off the GPU; yields.
- `volume:sparseStats()` — byte accounting: `denseBytes`, `poolBytes`, `pageBytes`, `residentBytes`, `ratio`.
- `volume:fillCompute(shaderName, opts)` — drive a custom fill shader against this volume.
- `volume:render(opts)` — dispatch the shared compute raymarcher into a 2D storage target, using `opts.entity` for AABB. A paged volume renders through its pool with no change at the call site.
- `volume:draw(key, opts)` — stand the volume in the scene under `key`, through `opts.entity`'s AABB: the `volume` render feature marches it for every view the frame draws, against that view's camera (`@frame.camera`) and depth (`@scene.depth`), at the view's resolution, and lays it over the frame in the `medium` stage. Call it again each frame to keep the box and settings current. The `Volume` and `VolumeSequence` components draw through it.
- `M.withdraw(key) -> boolean` — take a draw down, releasing its uniforms; the last one releases the draws' target and takes the render feature down.
- `M.draws() -> { {key, volume, target} }` — the draws standing, sorted by key; `target` is the one screen-sized target every draw marches into in turn.
- `M.drawKey(prefix, id?) -> string` — a key no other draw stands under.
- `M.enqueueDraws(ctx)` — the render feature's `render`: each draw's march and composite, both stating the centre of the draw's box as their `sortPoint`, so every view runs the draws farthest from its own camera first.
## Usage
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
-- Build a procedural noise cloud + occupancy.
local cloud = Volume.noise({
name = "cloud", size = 64, scale = 4, octaves = 4, threshold = 0.55,
})
cloud:buildOccupancy({ brickSize = 8 })
-- Stand it in the scene through an entity's box: every view the frame draws
-- marches it against its own camera and depth, so what stands in front of it
-- hides it. Call it each frame to keep the box current.
local key = cloud:draw(Volume.drawKey("cloud"), {
entity = entity(id),
density = 8.0, absorption = 1.2, emission = 0.9,
color = { 1.0, 0.9, 0.7 },
})
Volume.withdraw(key) -- takes it down
-- Or raymarch it into a 2D target of your own (here scene_volume_rt) for a
-- pass of yours to read. The target is the size of the view the frame draws
-- unless targetWidth / targetHeight name one, and the rays leave from the
-- drawn camera's world pose unless `camera` names another.
cloud:render({
entity = entity(id),
target = "scene_volume_rt",
density = 8.0, absorption = 1.2, emission = 0.9,
color = { 1.0, 0.9, 0.7 },
maxSteps = 256, mode = "rgba",
})
```
The `Volume.component` is the per-entity wrapper around this module — it
resolves the name it carries through `Volume.get` and stands it in the scene
with `volume:draw` from its `update` and `editorUpdate` hooks while it is
enabled.
## Addressing a volume by name
Every volume this module builds answers to its texture name, so anything
holding only the name — an entity's `Volume` component, a second script, a
tool — reaches the volume itself:
```luau
local cloud = Volume.noise({ name = "cloud", size = 128 })
cloud:buildSparse({ brickSize = 8 })
cloud:releaseDense()
-- somewhere else entirely
Volume.get("cloud"):render({ entity = entity.find("cloud_host") })
```
What the name alone cannot express is what makes this matter: the voxel
dimensions, which channel holds density, and whether the volume is paged into
a brick pool. A holder that reconstructs a wrapper from the name gets a dense
volume that the paging may already have released.
One volume owns a name at a time: the 3D texture, the page table and the brick
pool all address it, so `create` over a name a live volume holds releases that
volume first and says so in the log. `destroy` clears the entry. A wrapper
around a texture another system owns is published with `Volume.register` and
dropped with `Volume.unregister`, which hands the volume back so it can still
be destroyed. The names live where this module is loaded — one set per Luau
VM, alongside the raymarch target registry.
`render` builds its `target` on the first call that names one and keeps its
size, so repeated renders reuse it; `Volume.releaseTarget(name)` destroys that
target and forgets the size, and the next render builds it again.
## Paging a volume into bricks
A dense volume costs its bounding box. `buildSparse` splits it into bricks,
keeps only the ones holding anything over `threshold`, and stores those in a
brick pool; a page table one texel per brick says which slot each resident
brick took, and 0 says the brick holds nothing. That page table is also the
grid the raymarcher already skips empty space with, so paging and empty-space
skipping are the same structure.
```luau
local cloud = Volume.noise({ name = "cloud", size = 128, threshold = 0.6 })
local stats = cloud:buildSparse({ brickSize = 8, threshold = 0.01 })
print(stats.bricks, "of", stats.grid[1] * stats.grid[2] * stats.grid[3], "bricks")
print(stats.poolBytes, "vs dense", stats.denseBytes)
cloud:releaseDense() -- the pool is now the only copy
cloud:render({ entity = entity.find("cloud_host") })
```
Both passes run on the GPU with no readback between them, so a volume a
compute shader rewrites keeps a matching page table for the cost of two
dispatches:
```luau
cloud:fillCompute(myFillShader, { extraResources = { { kind = "buffer", name = fillU } } })
cloud:refreshSparse()
```
The pool is fixed at the size the build measured, so a volume that grows past
it loses the surplus bricks. `refreshSparse` asks the GPU for the counts
without waiting on them and folds them in on a later call, so `sparseStats()`
reports the overflow — and the log carries a warning naming the capacity to
page at — a frame or two after the refresh that caused it. `buildSparse`'s
`headroom` buys the slots up front for a volume that is expected to grow.
What it costs:
- A block in the pool is the brick plus a one-voxel apron on every side, so a
resident brick costs `(brick + 2)³` voxels. At `brickSize = 8` that is 1.95x
per resident brick, at 16 it is 1.42x. The apron is what makes a trilinear
sample inside a brick read exactly what the dense volume would have given
it.
- A pool is always `rgba16f`: it has to be writable as a storage texture and
sampled with filtering, and that is the format that is both. A scalar volume
therefore spends more per resident voxel than it did dense (its density rides
in the pool's red channel), so `sparseStats()` reports `denseBytes` and
`residentBytes` side by side rather than assuming paging is the smaller of
the two.
- `refreshSparse` re-pages from the dense volume, so a volume that will keep
changing keeps its dense copy; `releaseDense` is for one that is finished.
- Classification reads one channel: alpha for a four-channel volume, red for a
scalar one. A four-channel volume that carries density in red — the one
`render`'s `mode = "density"` marches — has to say so, with the same word:
`buildSparse({ mode = "density" })`. A `render` that names no `mode` marches
a paged volume from the channel its pool was filled from, so the two agree
without the caller repeating the choice.
## Notes
- Volumes are GPU-owned; the Luau wrapper just holds the named handle.
`volume:destroy()` releases both the texture and any occupancy
companion.
- `render` writes one named target, and a second `render` into the same
target replaces the first one's picture. `draw` marches every draw into one
screen-sized `rgba16f` target in turn, each composited over the frame
before the next draw's march, so any number of draws costs one view-sized
image and the frame lays them over each other.
- Occupancy grids use a brick size (default 8) — smaller = more
precise skipping at the cost of grid memory.
- The `vdb_to_zvol.importer` in this package produces dense voxel
buffers consumable by `compute.writeFloatsTexture3D`, which can be
wrapped via `Volume.wrap` (the Engine Showcase world's
`zvol_viewer` scene runs the full path).
·renderfeature · born here
❒asset # volume (render feature)
Runs the passes of every volume standing in the scene (`Volume:draw`, which the
`Volume` and `VolumeSequence` components call each frame; a smoke plume or a
voxel volume in a world is one of those components on an entity): for each view the
frame draws, a `volume_draw` march against that view's camera and depth into a
screen-sized target, then `volume_draw_composite` blending it over the frame,
draw after draw. Both passes of a draw state the centre of its box as their
`sortPoint`, so each view runs the draws farthest from its own camera first and
the volume nearest that view ends in front. Every draw
marches into the same target, each one composited before the next marches. It runs in the
`medium` stage, after the cloud layer's surfaces and ahead of the aerial
perspective and the height fog.
The `volume` module brings it up with the first draw and takes it down with the
last `Volume.withdraw`, so a scene with no volume standing runs none of its
passes. `Volume.draws()` lists what stands.
# volumeDemos
Shared orchestration backend for the `volumeDemos.package` showcase
scenes. Owns the per-demo resource pack (3D texture, 2D render target,
two uniform buffers) and the auto-registered composite, exposing a
small public surface the demo scenes drive once per frame.
## Exports
- `M.spawn({name, size, fillShader, fillUniformBytes}) -> ()` — register a new demo pipeline. Creates the 3D volume, the 2D storage target, registers the per-demo fill shader, ensures the shared raymarcher is registered, and auto-installs the depth-aware composite.
- `M.destroy(name) -> ()` — release everything `spawn` created (texture + render target + buffers + composite registration).
- `M.dispatchFill(name, fillUniforms) -> ()` — pack `fillUniforms` (Lua array of f32) into the demo's fill UBO and dispatch the fill shader against the volume.
- `M.dispatchFrame(name, {camera, aabbMin, aabbMax, width, height, stepSize, maxSteps, alphaCutoff, densityGain, emissionGain}) -> ()` — pack camera + raymarch params into the shared 40-float UBO and dispatch the raymarcher into the demo's render target.
- `M.NAMES(name) -> {volume, rt, composite}` — engine-side resource names for the demo (used by the `.zvol` viewer to bypass the helpers and upload voxels via `compute.writeFloatsTexture3D` directly).
## Usage
```luau
-- From a scene's entrypoint:
local V = require("@builtin::systems.volumetrics.volumeDemos")
-- onLoad: spin up the pipeline.
V.spawn({
name = "smoke_plume",
size = { 96, 192, 96 },
fillShader = SMOKE_FBM_WGSL,
fillUniformBytes = 64,
})
-- update(dt): repaint the volume + raymarch into the RT. The rays leave
-- from the drawn camera's world pose and the RT is the size of the view the
-- frame draws; `camera`, `width` and `height` override them.
V.dispatchFill("smoke_plume", { elapsed, density_amp, spread, ... })
V.dispatchFrame("smoke_plume", {
aabbMin = { -40, 0, -40 },
aabbMax = { 40, 160, 40 },
stepSize = 0.9, maxSteps = 240,
densityGain = 2.5, emissionGain = 1.0, alphaCutoff = 0.995,
})
-- onUnload: free GPU resources.
V.destroy("smoke_plume")
```
## Notes
- `dispatchFrame` packs 40 f32s into the raymarch UBO:
`[0..16)` inv_view_proj (mat4 row-major), `[16..19)` aabb_min,
`[19..22)` aabb_max, `[22..23)` step_size, `[23..24)` max_steps,
`[24..25)` alpha_cutoff, `[25..26)` density_gain, `[26..30)`
target_width/height + inv reciprocals, `[30..31)` emission_gain,
`[31..40)` padding.
- `lastFrame(name)` reports the target size and the eye the last
`dispatchFrame` of that demo marched with.
- Pipeline state lives in module-locals keyed by `name` — the same
module instance can host many demos in parallel, but two scenes
must not pick the same `name`.
- Each demo scene supplies its own fill shader; the raymarcher is
shared (one shader name, one compiled pipeline). Replacing
`fillShader` between frames is supported; replacing the raymarcher
isn't (use the volumetrics package for that use case).
# volumeSequence
Playback for a run of `.zvol` frames, through a ring of resident volumes.
A sequence names its frames as VFS paths in playback order. It allocates
`resident` 3D textures — one frame each — and nothing else: the frames the
playhead is about to reach are read off the VFS on their own tasks and
uploaded into whichever ring slot the playhead has travelled furthest past.
So a 240-frame run and a 4-frame run cost the same on the GPU, and what a
sequence costs is decided when it is opened rather than by how long it is.
```luau
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
local frames = {}
for i = 0, 239 do
frames[#frames + 1] = string.format("/source/sim/plume_%04d.zvol", i)
end
local seq = Seq.open({ name = "plume", frames = frames, resident = 3, fps = 24 })
local s = seq:stats()
print(s.residentBytes, s.allBytes) --> 3145728 251658240
```
Drive it from a component, which is also what makes it visible:
```luau
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
or by hand, if the caller already has a tick of its own:
```luau
seq:tick(dt)
local frame = seq:current()
if frame then
frame:render({ entity = entity(id), density = 6.0 })
end
```
The playhead advances once per engine frame however many callers tick the
sequence — a component and a script, or two entities naming one run, share
one playhead rather than each moving it. Every call still promotes the frame
that has landed and starts the reads ahead of it.
## Residency
Every frame of a run has the dimensions frame 1 declares, so one ring serves
the whole run. `stats()` reports both what the ring holds (`residentBytes`)
and what holding every frame at once would cost (`allBytes`); `residency()`
says which frame each slot holds right now.
The ring needs at least two slots for a multi-frame run — one holds the
picture on screen while the other takes the read — and `open` raises the
count to two if it was asked for less. `prefetch` says how many frames ahead
of the playhead reads are started, and defaults to every slot the ring has
spare — a slot left empty is a frame that gets waited on later. It is bounded
by those same slots, so asking for more than fits reads as far ahead as it can.
## Keeping up
A tick that wants a frame no slot holds yet keeps showing the frame it had
and counts a `stall`. Playback is therefore never blank and never blocks, and
`stats().stalls` is the number that says whether the ring and the prefetch
distance are big enough for the rate: a run whose reads keep up shows a stall
count that stops rising once the ring has filled.
`errors` counts frames that failed to read or whose header disagreed with the
ring. Each one is counted and logged once, with the path and what was wrong
with it, and the run steps over it from then on rather than re-reading it
every tick — so `errors` answers how many frames of the run are broken, and a
mistyped path costs one line in the log rather than one per frame.
The rate and the playhead are the sequence's, not a caller's: `setFps` keeps
the frame the playhead stands on and the fraction of the way through it, and
`seek` lands on exactly the frame asked for.
# volumetricLighting
The settings behind the `VolumetricLighting` component, and the way to drive the
scene's participating medium from a script — fog that rolls in over a cutscene, a
quality slider that drops the step count, a room that fills with smoke.
```lua
local volumetricLighting = require("@builtin::systems.volumetrics.volumetricLighting")
volumetricLighting.set({ density = 0.06, anisotropy = 0.7 })
volumetricLighting.get() -- a copy of the settings in force
volumetricLighting.active() -- whether the march is running
volumetricLighting.clear() -- empty the air, keep the settings
```
`set` takes any subset of the fields; whatever is omitted keeps its current
value. A `density` of 0 releases the render feature rather than marching a medium
that scatters nothing, and `clear` is the named way to say the same thing.
The medium is lit by the scene's sun, its lights and its surroundings, read by
the passes every frame: the sun's direction, colour and intensity, every light
in the scene, and the light a surface standing in the air takes from the scene's
ambient term, the sky and reflection probes the environment captured and the
baked light-probe volumes (`@builtin::shaderModules.ambient_light`, the light a
`ParticipatingMedium` takes too). The sun lights the air as it lights the
surfaces, so a setting sun dims and reddens the haze in the frame the surfaces
darken; the sky lights it as it lights them, as far as each point of the air
sees the sky past the static geometry and past every surface standing over it
(a tree's crown or a roof, movable and instanced ones included), so haze stands
in for the sky it hides by day, haze under a canopy takes the sky the canopy
leaves open, a mist reads as dim haze against a night sky, and a longer
`maxDistance` changes how far the haze reaches. `skyLight` scales how much of
its surroundings' light the medium takes: 1, the default, lights it as the
surroundings light a surface standing in it. The sky's light reaches it through
the sky light `skySource` names: by default the scene's own
(`@builtin::systems.sky.skyLight`), at the diffuse strength it lights the
surfaces with, so the haze takes the sky the surfaces take; a sky light that is
not running hands it none, and an empty `skySource` takes none. With the sun,
every light, the ambient term and the sky dark the medium scatters nothing.
`color` is what the medium scatters of all of that light. `sunIntensity` and `sunColor` are a scale and a
tint on the scene's sun: at 1 and white the medium takes the sun as the surfaces
do.
`sunDirection` follows the scene's sun. Pass one to `set` when a scene wants the
medium lit along a direction of its own; a `set` without it goes back to the
scene's sun.
The module packs the settings into the `vol_params` buffer the passes read, so a
change lands on the next frame without recompiling anything.
## Cost
The march is the expensive part, and its cost is `steps` × (`shadowSteps` + the
number of live scene lights) per marched pixel. Those are the two knobs to reach
for on a budget: `steps` controls how cleanly a beam's edge resolves,
and `shadowSteps` controls whether the sun's contribution is shadowed at all.
Setting `shadowSteps` to 0 removes the per-sample visibility work entirely, which
is the single largest saving available — at the cost of the shafts, since the
medium is then lit evenly wherever it reaches.
`quality` scales both, and the grid the march runs on, by level: `high`
marches `steps` and `shadowSteps` on a grid of half the frame's resolution on
each axis, `medium` 60 % and 67 % of them on a third, `low` half of each on a
quarter (`volumetricLighting.LEVELS`). Under `auto` (the default) the level is
the one the device's quality tier draws the effect at, read again each frame, so
`renderer.setQualityTier` moves it; `drawn()` reads the level in force and what
the march draws at it.
# volumetricSky
Orchestration backend for the `VolumetricSky.component`. Owns the
GPU resources the cloud layer needs (the tiling shape and detail noise,
the weather map, the raymarch render target, the per-view accumulation
history, the composite) and exposes a small public surface the component
drives every frame.
The layer is a shell around the planet between two altitudes over the
ground (the planet `PhysicalAtmosphere` integrates over), so it reaches the
horizon. Its clouds are formed where they stand in the world: a weather map
states coverage, cloud type and density per place, and two tiling noise
textures placed in world units form the clouds. One raymarcher,
`cloud_raymarch`, draws every sky.
## Exports
- `M.spawn(opts?) -> id` — spawn the singleton sky entity, or configure the one already standing, and return its id. Every weather parameter (`coverage`, `sunColor`, `sunIntensity`, `windSpeed`, …) is settable at the top level or inside a `preset` sub-table; every `VolumetricSky` component field (`weatherRegions`, `maxSteps`, `taaBlendAlpha`, …) by its own name; `name` names the entity. Parameters left out keep their current values. An option that names neither raises, listing both sets, and leaves no entity behind. A weather parameter takes the shape its default carries — a number, or an array of that many numbers — and a value of another shape raises naming the parameter. A preset key an earlier cloud layer read (`M.RETIRED_PRESET_KEYS`: `noiseScale`, `horizExtent`, …) is accepted and read by nothing.
- `M.configure(opts) -> boolean` — apply those same weather parameters and component fields to the sky already standing. Returns `false` when none has been spawned.
- `M.defaultPreset() -> table` — a fresh copy of the weather configuration a sky spawned with no options carries. The copy is the caller's to edit.
- `M.destroy() -> ()` — release every resource `spawn` created.
- `M.fillClouds(weather) -> boolean`: fill what the clouds are formed from where it does not hold what it should, and return whether this call dispatched a fill. The tiling noise holds no weather, wind or extent, so it is filled once per render device and again after an edit to `cloud_noise`'s files; the weather map is filled when the coverage, cloud type, `weatherVariation`, `weatherExtent`, seed or `weatherRegions` in `weather` change. Each fill waits until its shader's program is resident.
- `M.volumeBakes() -> number`: how many times the tiling noise has been filled since the module loaded.
- `M.weatherBakes() -> number`: how many times the weather map has been filled since the module loaded.
- `M.weatherRegionsFault(regions) -> string?`: what is wrong with a list of weather regions, or nil.
- `M.setWeatherRegions(regions) -> boolean`: author the weather over places in the world on the active sky.
- `M.layerShell() -> table?`: where the layer stood for the last dispatch: the planet's centre and radius, the ground level, the base and top altitudes and the march's reach.
- `M.layerTarget() -> string?`: the render target holding the layer the frame's last view drew.
- `M.getShaderHandles() -> table`: the compute shaders the layer runs (`noise`, `weather`, `raymarch`, `taa`, `surfaces`), resolved and compiled.
- `M.dispatchRaymarch(renderParams, viewport) -> ()` — pack the frame the layer's passes draw (the raymarch's and the accumulation's uniforms, the layer's targets), which `M.enqueueCloudPasses` hands the renderer for every view it draws. `renderParams` is the flat table `M.renderFrame` packs from the values in force and the drawn camera.
- `M.renderFrame(ctx) -> ()`: the layer's frame, run once a frame by the `volumetricSky` render feature: the wind offset from the session clock, the fills, the raymarch's packing and the passes.
- `M.wind() -> { number }?`: how far the wind has carried the clouds, in world units.
- `M.find() -> id?` — return the id of the entity carrying the scene's `VolumetricSky`, whatever the entity is named, or `nil` when no entity carries one.
- `M.despawn() -> ()` — despawn the entity `M.find` names. Its component lets go of the cloud layer as it goes, and the last sky to let go releases the layer's GPU resources.
- `M.setCoverage(c) / M.setDensity(g) / M.setSun(dir, color, intensity?) / M.setWind(v)` — convenience setters that route through the active component's `public` fields. The clouds are lit by the scene's sun, so `setSun`'s direction moves the scene's sun; its colour and intensity are the preset's `sunColor` and `sunIntensity`, how brightly and in what tint that sun lights the clouds.
- `M.renderFrame(ctx) -> ()` — the cloud layer's frame, run once a frame by the `volumetricSky` render feature with the values in force as `ctx.settings`, in every mode: drifts the wind at `preset.windSpeed` on `multiplayer.roomTime()` (held while `engine.paused`), bakes through `M.fillClouds`, packs through `M.dispatchRaymarch` for the active camera and enqueues the passes.
- `M.wind() -> { x, y, z }?` — the wind drift the volume is drawn at, or `nil` before the layer's first frame.
- `M.enqueueCloudPasses(ctx) -> ()` — enqueue the layer's passes for the frame; the renderer runs them for every view it draws. Every pass declares `atmospherics`, so a camera stating an isolated environment draws no clouds.
## Usage
```luau
-- The component drives this module automatically. Direct M.* use is
-- rare; the canonical entry point is attaching VolumetricSky to an
-- entity (or loading a preset and passing it to component.add):
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
-- Driving the layer by hand instead, a frame at a time. Each call creates
-- the resources it needs: the noise and the weather map on the first fill,
-- the render targets at the size the viewport names:
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
Sky.fillClouds({ coverage = 0.5, cloudType = 0.5 })
Sky.dispatchRaymarch(renderParams, { width = 1280, height = 720 })
```
## Notes
- The shape noise is 128^3 RGBA8 (8 MiB), the detail noise 64^3 RGBA8
(1 MiB) and the weather map 256x256 RGBA16F (0.5 MiB), whatever the
layer reaches.
- The accumulation is a history target (`renderer.texture.create` with
`history = true`): each view the frame draws (the viewport, every
camera rendering into a texture, every capture) keeps its own pair of
RGBA16F images at its own size scaled by `renderScale`, and the pass
reprojects them through that view's own camera (`@frame.camera`). A
view's first render, and its first after a cut or a change of size,
starts from its own raymarch. A capture drawing the viewport's picture
carries the viewport's accumulation on. Set `taaBlendAlpha = 1.0` to disable
while still going through the same code path (useful for
benchmarking).
- All public setters write through to `VolumetricSky.component`'s
`public` fields, which means they replicate as Sync if the
component is sync-enabled. Tweaks survive scene reloads as long as
the same entity is alive.
- `SkyPreset` and its defaults are declared here, and the component
declares its `preset` field from them. `M.spawn` / `M.configure` read
that same key set to tell a weather parameter from a component field, so
a parameter added to the preset reaches the schema and the option routing
in one edit.
·renderfeature · born here
❒asset # volumetricSky
The cloud layer's render passes. The `VolumetricSky` component brings them up
and takes them down: to put clouds in a sky, add that component to one entity.
The layer is raymarched for the camera being drawn, each ray ending at the
surface the opaque scene drew along it (`@scene.depth`), copied into the target
the composite reads, temporally accumulated where there is a previous frame of
that view to accumulate against, and laid over the frame in two passes:
- over the pixels the opaque scene left as sky, once the opaque scene is lit
(`afterOpaqueLit`) and ahead of the transparent phase, so a particle, a glass
pane or any see-through surface that writes no depth stands in front of the
clouds behind it;
- over the pixels a surface stands on, the water a transparent draw wrote depth
for included, at the head of the `medium` stage, ahead of the air (aerial
perspective, height fog, volumetric light): `cloud_layer_surfaces` picks the
layer's cells a surface stands on out by the frame's own depth, and the
composite lays them.
A cloud in front of a surface covers it at any distance, so from above the layer
the clouds cover the ground and the sea below them, and a surface in front of a
cloud keeps it out.
Every pass but the accumulation runs for each view the frame draws, an
environment cube's six faces included — which is what puts the clouds into
reflections. The accumulation blends against the previous render of the same
view: each view (the viewport, every camera rendering into a texture, every
capture) keeps its own images of the layer's history target and reprojects
them through its own camera; a capture drawing the viewport's picture carries
the viewport's accumulation on. A cube face is rendered once with no previous
render, so the accumulation declares `environmentCapture = false` and the copy
before it is what those faces read.
The layer is part of the scene's sky and air, so every pass declares
`atmospherics = true`: a camera stating an isolated environment (an asset
preview, an icon, a portrait) draws no clouds over its backdrop.
Its `settings` are the layer's parameters: the weather configuration as one
`preset` table, the shader variant and the per-client quality knobs. A
`VolumetricSky` component or a scene setup applies it. Once a frame, in every
mode, `render` runs `volumetricSky.renderFrame`: the clouds drift at
`preset.windSpeed` on the session clock and hold still while the engine is
paused, the volume is baked when what it is baked from moved, and the raymarch
is packed for the camera the frame is drawn with. `teardown` releases
everything the layer holds.
# 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.
# 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`.
# openvdb
Reads OpenVDB files for the `.vdb` importer, which turns one into a `.zvol`
volume.
```luau
local openvdb = require("@builtin::plugins.openvdb")
local grid = openvdb.parse(vfs.read("/zero/source/fire.vdb"))
print(grid.width, grid.height, grid.depth, grid.mode)
-- grid.voxels: width * height * depth * 4 bytes, RGBA8
```
The first float grid in the file is read: density grids (smoke, fire, fuel)
normalised by their own range, and level sets (values straddling zero) with
the inside opaque. A grid larger than 256 on a side is downsampled by a whole
stride. Blosc-compressed grids are not read; re-export them with ZIP or no
compression.
It takes the file's bytes and answers the grid, and reads and writes nothing
itself.
# 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**.
# 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.
# 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`.
# Importer (asset type)
An importer is a Luau function that converts a source file (GLB,
PNG, CSV, custom binary) into one or more derived assets registered
in the engine. Importers extend the engine's file-format knowledge —
adding a new importer means "the engine now understands `.foo`
files". Importers run automatically on VFS writes that match their
claimed extensions.
## When to use one
- You're bringing a new file format into the engine and want to
derive engine-native assets from it (meshes, textures, animations,
data tables).
- You want one VFS write to fan out into multiple derived assets
(e.g. a GLB write derives mesh, texture, and animation assets).
- You want format ingestion to be idempotent + hot-reloadable —
importers re-run on source-file changes.
If you only need to consume an existing engine asset type, you don't
need an importer; just resolve it via `asset.resolve`. If you're
building an authoring tool that emits assets, that's a `.tool`, not
an importer.
## Where it lives
- Source: `/zero/source/.../<name>.importer/`
- Identity: `<name>` (the `.importer` suffix strips).
- Folder shape:
- `init.luau` (or `init.lua`) — exports `canImport` and `import`, and
`extensions`: the file extensions it claims, lower-case without the dot.
An importer that makes one asset beside its source also exports
`produces`, the type of that asset (`"texture"` makes `<stem>.texture`).
**Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- `settings.luau` — the importer's own settings schema, declared with
`Field` descriptors. Optional; an importer without one takes no settings.
- `settings.yaml` — the importer's settings values. Optional.
## Settings
An importer that takes settings declares them in its own `settings.luau` and
receives the resolved values as `ctx.settings` in `import(ctx)`.
`asset.schema(importerRef)` reports the schema, `asset.settings(importerRef)`
the values, and `asset.setSettings(importerRef, patch)` changes them. What an
importer stamps onto the assets it creates is typically one of these: the
texture, SVG and model importers each declare `textureSettings =
Field.settingsOf("@builtin::assetTypes.texture", NoSync)` — the texture type's
own fields — and pass it to `asset.create` as `importerSettings`, the importer
layer of each texture's settings. A change to an importer's settings counts as
a change to what an import is made from, so an unchanged source is imported
again after one.
## How to create one
```luau
asset.create("importer", "<name>")
-- Creates: /zero/source/<name>.importer/
-- init.luau (canImport / import stubs)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("importer", "<name>", { folder = "importers" })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.importer/` folder
indexes the importer with the importer registry.
2. **Dispatch.** When a file is written to VFS, the engine asks every
registered importer `canImport(path, bytes)` (cheap predicate).
The first importer that accepts dispatches to its `import`
function.
3. **Derivation.** `import(ctx)` builds the asset (usually with
`asset.create`) and returns `{ output, container, source }`: the asset
it made, the container a re-import regenerates, and the file the asset
keeps as its source. `ctx` carries `path`, `bytes`, `extension`,
`settings`, `output`, `container`, `retainSource`, `stem` and `dir`.
4. **Idempotency.** `import` MUST be deterministic — importing the
same source bytes twice produces identical derived assets. The
importer pipeline uses content-hashing to short-circuit re-imports
when bytes haven't changed.
5. **Hot reload.** Editing the importer reloads it; subsequent writes
use the new logic. Already-imported assets stay imported with the
old derivation until their source is imported again — writing the
source path re-dispatches the importers, and
`tools.use("importers", "run", <path>)` re-imports a target, many
targets, or a whole folder on demand.
6. **Play.** A source written while play runs lands on the play shadow
and imports there, so the source and its asset are kept or discarded
together at play-exit. A source play holds where it stands (written
before play, or by a durable write during it; `vfs.playHoldsInPlace`)
cannot be moved into a new asset while play runs, so its import is
owed: the job reads `owed` (reason `play-lock`), a notice names it,
and it imports when play ends or pauses. `tools.use("importers",
"queue")` lists owed imports and `importers.cancel` drops one.
7. **A lost live session.** While the live world session is lost and
reconnecting (`vfs.sessionLost()`), every write to authored source is
refused, so an import asked for then is owed rather than started, and
one a drop catches part way is owed rather than failed, its job carrying
the refused write as `error`; when the import had already moved its
source into the asset it makes, it runs again on the source there,
regenerating that asset around it. The job reads `owed` (reason
`session-lost`), the notice `import owed until the live session
re-establishes` names it, and it imports once the session is back,
when the notice `import resumed: the live session re-established`
names it and `import finished` (or `import failed`) settles it. A
generation waiting on such an import completes with the asset it
produces. Content this machine keeps to itself (`vfs.isSaveExcluded`:
`/source/tmp/`, `/source/local/`) is written while the session is lost,
so an import of a source there into an asset there runs at once.
## Re-importing over an asset an import made
An import keeps its source inside the asset it makes: `art/plate.svg` becomes
`art/plate.texture/` holding `plate.svg`. `import(ctx)` reads where to write
from `ctx.output` (`<dir>/<stem>.<produces>` on a first import) and keeps the
source with `ctx.retainSource(dest, opts?)`, which moves it to `dest` and
returns where it is now. `import` returns `{ output, source }`, `source` being
the file the asset keeps, which the asset's `import` provenance records as its
source.
- **The source written again beside the asset.** Writing `art/plate.svg` once
more re-imports it into the same `plate.texture`: the new bytes replace the
svg the texture retains (which keeps its guid), the written file leaves, and
the asset is made again from the new bytes. Its `import` provenance counts
the iteration on.
- **The same bytes written again.** When the source's checksum and the
importer's settings match the import that made the asset, no import runs:
the asset already holds those bytes, so the written copy is folded into it,
and `writeOutcome` answers `skipped` with reason `unchanged-content`, naming
the asset and the file that holds the bytes.
- **The asset itself.** `tools.use("importers", "run", <asset>)` re-imports a
produced asset in place from the source it retains (`ctx.container` names
it), so rewriting `plate.texture/plate.svg` and running it re-bakes the
texture. A run that makes nothing says why: each skipped result carries a
`reason` (`missing`, `no-source`, `no-claimant`, `unclaimed`).
## Discovery
- `asset.list("importer")` — every registered importer.
- `asset.inspect("<name>")` — claimed extensions, derivation
conventions, source, this type README.
- `ls /zero/source/<name>.importer` lists the files the folder holds.
- `tools.use("importers", "list")` — every registered importer, with
its name and identity.
- `tools.use("importers", "explain", <path>)` — which importers claim
a given source and which gate would block the import.
## Where a write's bytes end up
An importer that claims a written source may move it into the asset it
makes (the texture importer turns `shots/a.png` into `shots/a.texture/`
holding `a.png`), so the path the write named stops holding the bytes.
`require("@builtin::assetTypes.importer.shared").writeOutcome(path,
sinceFrame, timeoutSecs)` answers where they went, for a write made on
engine frame `sinceFrame` (`time.frameCount()` read before it): nil when
no importer claims them, else the import's `state`, the `importer`, the
asset made (`output`), the file the bytes are in now (`source`) and a
`note` saying all of it. Every write that fires its side effects is
offered to the importers by the same rule, whichever route made it, and
the MCP `write_file` and `upload_file` answers carry this outcome as
`import`. A quiet write (`{ quiet = true }`, and every `capture` save)
is offered to no importer, and its bytes stay where they were written;
`writeOutcome` answers `not-started` for one an importer would claim.
A write whose import the running play session holds back (a fresh
import moves its source into the asset it makes, and play holds a source
that predates it, or that a durable write made canonical, where it
stands) answers `owed` at once, with `reason` `play-lock`: the bytes stay
at the written path, and the import runs when play ends or pauses. One
the lost live session holds back answers `owed` with `reason`
`session-lost`, and runs when the session re-establishes.
`writeOutcomes(paths, sinceFrame, timeoutSecs)` answers a run of writes
made together (a model, then its buffer and textures) once all of them
have landed, within one wait: a folder `write_file` or `upload_file`
lands every file without waiting on any import, then answers each this
way. `write_file { awaitImport = false }` lands one file of such a run
without waiting on its import.
## Authoring conventions
- Keep `canImport` cheap — it's called for every VFS write. Match on
extension or a quick header probe; defer real parsing to
`import`.
- Declare the extensions the importer claims as `M.extensions` and have
`canImport` claim by that list. The Inspector lists them, and
`require("@builtin::assetTypes.importer.shared").extensionsOf(importerRef)`
answers them (lower-case, without the dot; nil for an importer that
declares none).
- Write the asset to `ctx.output`: on a first import that is
`<dir>/<stem>.<produces>`, beside the source. The asset lands where
the source was, and a re-import regenerates it in place.
- Make `import` pure relative to its inputs. Don't read mutable
globals or side-channel state.
- Log derivations via `print` / the script log so authors can see
what got produced from each source.
## Common pitfalls
- **Expensive `canImport`.** It runs on every VFS write; an
expensive predicate slows down the entire authoring loop.
- **Non-idempotent `import`.** Re-importing produces different
output → content hashing falsely caches stale results. Use only
deterministic transforms.
- **Conflicting importers.** Two importers claiming the same
extension causes ambiguous dispatch. First-registered wins, but
this is fragile — coordinate ownership of file extensions.
- **Derived-asset suffixes.** Make sure derived paths end in the
right `.<category>` suffix; otherwise they won't register as
recognized assets.
## Related types
- `.module` — for plain ingestion helpers that don't need the
importer dispatch path.
- `.tool` — for one-off conversions an agent invokes manually.
- `.service`: a declarative content generator; an importer converts a
file that already exists, a service makes content you don't have yet.
## In the Inspector
Imports: the extensions the importer claims (`M.extensions`), each file it imported in this session with the state its job reached, and **Find assets it produced**, which lists the assets in the world whose import provenance names this importer.
# renderFeature
A **render feature** inserts custom GPU passes into the frame pipeline. The engine
provides one generic capability — a per-frame render-pass queue and a set of
pipeline-phase insertion points — and a feature is the authored Luau that decides
what passes to enqueue, and where, every frame.
## Authoring contract
A `.renderFeature` folder holds an `init.luau` that returns a feature module:
```luau
return {
setup = function(ctx) -- optional; runs once when the feature goes live
-- A "fragment" pass's `shader` names a POST EFFECT, not a `.shader`
-- guid directly — postprocess.add compiles the shader asset under
-- that name once, here. Enqueueing a name never passed to
-- postprocess.add runs the pass as a no-op every frame (the log
-- reads "effect '<name>' not compiled — pass skipped").
postprocess.add("my_effect", asset.resolve("my.shader.guid", "shader"), { enabled = false })
end,
render = function(ctx) -- required; runs every frame
-- enqueue one or more passes. The spec shape depends on `kind` (see
-- "Pass kinds" below): this is a "fragment" pass (full-screen shader over
-- input textures); a mesh effect (outline, x-ray) is a "geometry" pass
-- with `material` + `select` (see "Geometry passes").
ctx.enqueue {
phase = "afterTransparent",
shader = "my_effect",
inputs = { src = "@scene.color" },
output = myRenderTargetGuid,
}
end,
teardown = function(ctx) end, -- optional; runs once when the feature is destroyed
}
```
Optional `materials/` and `shaders/` subfolders hold shader source the feature
constructs GPU programs from. A feature constructs its GPU programs (it does not
reference `.material` surface assets).
## `ctx`
Built fresh each frame and passed to `setup` / `render` / `teardown`:
| Field | Meaning |
|-------|---------|
| `ctx.enqueue(spec)` | Queue one render pass for the current frame. |
| `ctx.viewport` | `{ w, h }`: the size the **main viewport's** scene rasterized at, in pixels (`renderer.rasterSize()`: the viewport taken down by the render scale). |
| `ctx.time` | The instant this frame's per-frame fields are drawn at, in seconds: the running clock, or the instant a `renderer.temporal.hold` pins. Absent in a feature that states its inputs. |
| `ctx.frame` | The frame index beside that instant: it counts every frame of the loop, drawn or not, and reads 0 while a hold stands. Absent in a feature that states its inputs. |
| `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. |
| `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". |
| `ctx.authored` | The same knobs as authored: a setting declared with `Field.scaled` reads its authored value here and the value of the quality level in force in `ctx.settings`; every other setting reads the same in both. |
### Per-frame values and a still picture
A buffer a feature's passes read is part of the picture: written with new words
between two frames, it is a change of the picture, and a renderer draws for as
long as such changes arrive. A field that animates with time (film grain, a
moving noise) seeds from `ctx.time` and draws while the clock runs. The jitter
an accumulation averages over (a ray offset, a rotated sample pattern) turns
with the renders of the view instead, so the feature's parameters hold the same
words on every frame of a still scene and the renderer stops drawing once the
accumulation settles: a history target's `state` buffer
(`renderer.texture.create { history = true }`) carries in `y` how many renders
in a row the view being drawn has carried, written as each render of the view
begins, and a pass that binds it reads its jitter frame there. While
`renderer.temporal.held()`, the passes take the frame from the held instant
`@frame.clock` carries instead (the feature states the hold among its inputs
and writes a flag into its parameters), so two renders under one hold agree.
`@builtin::systems.reflections.ssr` works this way.
## Stating what a feature depends on
A feature whose `render` gives the same passes while nothing it reads moved says
what it reads, and the engine stops running `render` on the frames where none of
it did. The module states the inputs with `dependsOn`, a list of names, with
`inputs`, a function returning a value, or with both:
```luau
return {
stage = "display",
dependsOn = { "settings", "viewport" },
render = function(ctx)
ctx.enqueue(specFor(ctx.settings, ctx.viewport)) -- a spec frozen all the way down
end,
}
```
| Input | Moves when |
|-------|-----------|
| `settings` | the feature's settings in force change: a `configure`, or a quality level that scales one. Every feature that states inputs holds this one, named or not. |
| `viewport` | the size the main viewport's scene rasterizes at changes (`ctx.viewport`). |
| `renderPath` | the active render path changes (`ctx.renderPath`). |
| `camera` | the camera drawing the viewport moves, turns or changes its projection (`ctx.camera`). |
| `camera.cell:<size>` | the camera's position crosses into another cell of `<size>` world units on a side, such as `camera.cell:2` (`ctx.camera`). |
| `assets` | an asset is created, changed or removed anywhere in the world. |
| `lights` | a light the renderer shades with changes: a field of a light component, a light entity's world transform (its own or an ancestor's), a light shown, withheld, spawned or removed, the sun or the ambient term (`lighting.revision()`). |
`inputs` is called with no arguments once a frame, and its value is compared with
the one of the frame before by `==`: a number or string that counts a revision, or
a table the owner replaces when its content changes (`debugViz` answers the batch
the debug module holds).
The first render, and a render after the feature restarts or the device rebuilds,
runs whatever the inputs say. Each later frame the engine reads the inputs: when
none moved, `render` does not run, and the passes the last render handed over
stand in the frame as they stood. A render's passes stand in the frame only while
every spec it enqueued is a table frozen all the way down (the engine reads such
a spec once and keeps it); a render that hands over any other spec runs on every
frame, whatever it states. `ctx.time` and `ctx.frame` are not there to read in a
feature that states its inputs, and `ctx.viewport`, `ctx.renderPath` and
`ctx.camera` are there only when an input names them: what changes on every frame
comes from the frame's own buffer, `@frame.clock`, which every pass binds. A
feature that states nothing runs `render` on every frame.
`renderer.feature.list()` and the profiler counts `renderFeature.renders` and
`renderFeature.replays` report how many features rendered and how many stood on
their kept passes in a frame.
## Settings
A feature declares the knobs it takes as `settings`, each a Field descriptor
with a default, the way a component declares its public fields. A feature that
declares no `settings` has nothing to tune: its schema is empty, and applying it
turns it on or off.
```luau
local Fields = require("@builtin::modules.field")
local Field, NoSync = Fields.Field, Fields.NoSync
return {
settings = {
intensity = Field.number(1.0, NoSync, "How much of the effect reaches the image."),
quality = Field.enum({ "low", "high" }, "high", NoSync, "How many samples the pass spends."),
},
render = function(ctx)
local s = ctx.settings -- { intensity = 1.0, quality = "high" }, or what a caller set
...
end,
}
```
The engine holds one settings table per live feature — every declared default,
overridden by what it was handed — and passes it as `ctx.settings` on every
`setup` / `render` / `teardown`. A feature reads its knobs there and nowhere
else, so any caller tunes any feature by name:
```luau
local h = renderer.feature.create(ref, { settings = { intensity = 0.5 } })
renderer.feature.configure(h, { quality = "low" }) -- lays over the rest
renderer.feature.settings(h) -- { intensity = 0.5, quality = "low" }
renderer.feature.find(ref) -- the live handle, or nil
renderer.feature.schema(ref) -- the declared knobs, unrun
```
A knob the feature does not declare, or a value of the wrong shape, is refused
by name. A scene authors its features on one `RenderFeatures` entity — a list
of features, each with its settings — which adopts a feature already live
rather than stacking a second, and takes every one down on disable and destroy.
Each entry is an application of its asset (`applicable`): the asset holds its
one live feature, every application joins it, the settings in force are those
of the application that last stated something new, and the last to leave stops
it. A feature already running when the first application comes is adopted, and
runs on with its own settings once the last leaves. A feature stopped from
outside the asset (`renderer.feature.destroy`, a
`render` that raised) stays stopped until an application is stated again.
`render` runs **once per frame**; the passes it enqueues run **once per render
target** drawn that frame — the live viewport, every offscreen capture, every
RTT camera — each at its own resolution. So `ctx.viewport` is the main
viewport's size, not the size of the target a pass ends up drawing into. Size a
full-screen scratch RT with `screen = true` and let the engine track the drawn
target (see "Screen-sized targets") rather than deriving it from `ctx.viewport`.
## Screen-sized targets
`renderer.texture.create { screen = true }` marks a feature RT as full-screen:
before each render target's feature passes, the engine resizes it to that
target's resolution. Create it once — the engine owns its size from then on:
```luau
myRt = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
screen = true, format = "rgba16f", name = "my_effect",
}
```
A target that holds a picture of the scene is `rgba16f`, which is what the scene
target itself carries: linear light with headroom above the display's white and
no 256-step floor under a dark gradient. Omitting `format` on a screen-sized
target asks for the same thing. `format = "rgba8"` is for a mask, a weight or an
occlusion term, where 0..1 is the whole range — hand one of those back over
`@scene.color` and the frame loses every highlight and bands every gradient, and
the engine says so in the log.
`screenScale` (default `1.0`) takes a fraction of the drawn target's resolution,
for a scratch that runs below composite resolution (a half-res blur passes `0.5`).
A screen-sized RT is what makes a full-screen effect composite correctly at any
resolution. Deriving the size from `ctx.viewport` instead pins the RT to the main
viewport, and every differently-sized render target then composites a mismatched
scratch — the scene scaled into a corner with the rest black.
`screenSpace` names WHICH image a screen-sized RT follows:
| value | what it tracks |
|---|---|
| `"scene"` (default) | the scene render target, at whatever resolution the render scale asked for. Resized before EVERY render target's feature phases — the main frame and each offscreen one — and cleared to transparent before an offscreen render, so one sink never reads what another left behind |
| `"composite"` | the image the post-scene phases draw into. The presented frame's allocation is resized and drawn by the presented frame alone; an offscreen render that runs a post-scene phase (a capture, a render-to-texture camera whose picture goes through the `display` stage) draws in an allocation of its own at its own size, cleared to transparent before it draws |
The two carry the same size until the render scale drops below 1. From there,
while the renderer presents the viewport itself, the scene reaches the display's
resolution through an upscale that runs before `afterScenePost` — so a
composite-space RT is the display's size while a scene-space one is the smaller
rasterized frame. Under a UI viewport panel the panel draws the scene target at
its own rect, nothing upscales beforehand, and both spaces carry the scene's
size.
A scene-space target is scratch: whatever a pass does not rewrite this render is
transparent black. The presented frame's allocation of a composite-space target
survives every offscreen render untouched.
## History targets
An accumulation across frames (temporal antialiasing, a temporal denoiser, any
pass that reads what it wrote last time) lives in a history target:
```luau
history = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
history = true, format = "rgba16f", name = "my_accum",
}
-- in render(ctx):
ctx.enqueue {
kind = "compute", program = myResolve,
inputs = { scene_color = "@scene.color", accum_previous = history.previous.guid },
buffers = { accum_state = history.state },
storage = { accum_out = history.guid },
phase = "afterLighting",
}
```
The passes a feature enqueues run once for every view the frame draws (the
viewport, each render-to-texture camera, each capture), so an accumulation has
to be one per view. A history target keeps one pair of images per view, sized to
that view: for the length of a view's render `history.guid` names the image the
render writes and `history.previous.guid` the image the same view's previous
render wrote. Another view never resizes, clears or overwrites them, and a
view's images are freed when it stops drawing. A capture drawing the picture
the viewport's latest render drew (its camera and lens, its size, the same of
the scene its layers admit, and its shading), while the viewport samples
where `renderer.setProjectionJitter`'s sequence places it, is the one render
that draws with another view's images: for the length of its render
`history.previous.guid` names the image the viewport's latest render wrote and
`history.guid` the viewport's other image, which the viewport's next render
writes over, and `history.state` reads as it would for that next render. A
viewport whose projection `renderer.setProjectionOffset` or a reconstructing
upscaler moves samples where no capture follows, and a capture then draws with
images of its own. It follows `screenSpace` and
`screenScale` like any screen-sized target; a composite-space one is kept for
every view that runs the post-scene phases: the viewport, a capture, and a
render-to-texture camera whose picture goes through the `display` stage.
Before each render of a view the engine writes `history.state`, one
`vec4<f32>` a pass binds through `buffers`:
| field | holds |
|---|---|
| `x` | 1 when `previous` holds this view's previous image; 0 on the view's first render, its first after a camera cut or a change of size, or after a render of the view that ran without the target, and `previous` then reads transparent black |
| `y` | how many renders in a row have carried the history |
| `zw` | this render's sub-pixel projection offset, in pixels (`renderer.setProjectionJitter`) |
`renderer.setProjectionJitter` is the matching per-view sample sequence: every
view walks it by its own count of renders, so the sequence a temporal pass
expects is the one each view's renders sampled.
## Post stages
A post effect belongs to one of the frame's named **post stages**, in frame
order, each stating what the picture holds there: the space an effect there
reads and writes (`light`, the scene's own light ahead of the display
transform's exposure and tone curve, `display`, code values, or `encoded`, the
presented surface's own values) and the size
the picture is held at (`raster`, the size the scene rasterized; `output`, the
size the frame is composed and shown at):
| Stage | Space | Resolution | Runs |
|-------|-------|------------|------|
| `lighting` | light | raster | screen-space lighting terms and what draws into the lit scene: occlusion, reflections, indirect light, contact shadows, decals, splats, outlines, diagnostic views. It spans every phase up to `afterLighting`, so a pass of a feature declaring it may name one of those phases |
| `medium` | light | raster | participating media: aerial perspective, fog, volumetric light |
| `preTemporal` | light | raster | effects reading the jittered raster before reconstruction: depth of field |
| `temporal` | light | raster | the one temporal reconstruction of the raster (TAA); the stage holds one feature at a time |
| `postTemporal` | light | raster | effects reading the reconstructed picture: motion blur |
| `meter` | light | reduced | measuring the picture: the exposure histogram, a fraction of the raster |
| `optics` | light | raster, then output | lens light: bloom, flare, streaks. Its render features run on the raster; the frame then carries the picture to the output size, and the post-process chain's `scene` layer runs there |
| `display` | display | output | the display transform, then on code values the temporal upscale, debanding, edge antialiasing and sharpening; the chain's `display` layer, the film grain last |
| `ui` | display | output | the UI, drawn over the finished picture, then what grades the picture with the UI on it: `afterUI` passes, the chain's `all` layer, then `afterPost` passes |
| `output` | encoded | output | the renderer's output stage alone: the one write of the presented surface, in the surface's encoding, rounded to its bit depth with a blue-noise dither (`renderer.output`). It takes no render feature and no chain effect |
A feature declares the stage it belongs to, and each pass it enqueues with no
`phase` runs in that stage, at the stage's phase and its band of orders plus the
pass's own local `order` (a whole number from 0 to 99):
```luau
return {
stage = "postTemporal",
render = function(ctx)
ctx.enqueue { kind = "fragment", shader = "my_effect", inputs = { src = "@scene.color" }, order = 0 }
end,
}
```
Passes sharing an order run in the order they were enqueued, so a chain of
passes over shared targets can run at one order, in sequence.
The `meter` and `optics` stages are the camera's film. A pass placed in one of
them, stating neither `postProcessing` nor `presented`, is part of the camera's
post-process chain (`postProcessing = true`): a camera running no
post-processing, such as a capture asking for the scene ungraded or an
environment cube face, skips it. A pass stating `postProcessing = false` runs on
every camera.
`render` runs once a frame, but each view the frame draws (the viewport, a
capture, a render-to-texture camera, an environment cube face) looks at the
world from its own camera, so an order that depends on where the camera stands
is stated per pass rather than chosen in `render`. A pass that composites
something standing in the world states the world point it stands at as
`sortPoint`: `{ x = .., y = .., z = .. }`, `{ x, y, z }` or a `vector`, so an
entity's `position` is one. Among the passes of one phase sharing one `order`
that run together (its fragment, compute and raster passes; its geometry
passes, which run ahead of those), the ones stating a point trade the places
they were enqueued in so that every view runs the one farthest from its own
camera first and the nearest last: composites laid over the frame by each of
them leave the nearest in front from wherever the view looks. Depth is
taken along the view (the distance in front of a perspective camera, the depth
into an orthographic one's box). Passes at the same depth keep the order they
were enqueued in, so the passes of one effect stating one point (a march into a
target and the composite reading it) stay together, and a pass stating no
point keeps its place:
```luau
for _, item in ipairs(items) do
ctx.enqueue { kind = "compute", program = march, storage = { out = scratch.guid }, order = 2, sortPoint = item.center }
ctx.enqueue { kind = "fragment", shader = composite, inputs = { src = scratch.guid }, blend = true, order = 2, sortPoint = item.center }
end
```
A draw or splat pass takes no `sortPoint`, and a value that is not three finite
numbers is refused by `ctx.enqueue`.
A pass may name a
`stage` of its own in place of the feature's, placed the same way: a feature
whose work spans two stages declares one and names the other on those passes,
the way temporal antialiasing declares `temporal` for its resolve and names
`display` on its sharpening passes. A pass naming both a `stage` and a `phase` is refused. A stage the
frame does not have is refused by `renderer.feature.create`, naming the stages
there are, and a second feature declaring the `temporal` stage while one stands
in it is refused naming both; the `temporal` stage takes the passes of the
feature declaring it alone. A pass that names a `phase` runs at that phase and
`order`, as below. `renderer.post.stages()` reports every stage and what stands
in it: a feature by the stage its passes' position falls in, marked `declared`
where that is the stage the feature declares or a pass names. Every built-in
render feature declares its stage; `postStages`'s README lists where each
built-in effect runs.
## Pass phases
`enqueue` runs a pass at a named pipeline boundary — a real seam between the
scene's discrete passes — ordered within a phase by `order`. Each phase is the
point where the scene colour holds a specific, nameable state:
| Phase | Scene colour there |
|-------|--------------------|
| `afterDepthPrepass` | the visibility raster written: `@scene.depth` holds this frame's complete opaque depth, and `@scene.motion` its opaque motion, before anything shades. Scene colour is not yet drawn; `@scene.colorHistory` holds the previous frame's lit colour, and the deferred g-buffer the previous frame's surfaces (`readsPrevious`) |
| `afterShadows` | shadow maps populated; scene colour not yet drawn. `@scene.depth` and `@scene.motion` hold what the visibility raster laid at `afterDepthPrepass` |
| `afterSky` | sky only. `@scene.depth` holds the frame's opaque depth, so a pass here tells the pixels the geometry pass draws over (depth above 0) from the ones that stay sky (depth 0) |
| `afterOpaque` | opaque drawn, before transparents. `@scene.depth` (and the deferred G-buffer) are populated. Forward: lit opaque. Deferred: lit opaque too, which the geometry pass shades straight into the scene colour, on a render no pass reads or writes `@scene.shaded` in; on one that does, the opaque surfaces are in the G-buffer's shaded channel, so the colour is still sky only until the composite (use `afterOpaqueLit`). Radiance stamped into `@scene.emissive` reaches the colour at the composite |
| `afterOpaqueLit` | the lit opaque scene, still before transparents, on **both** paths — the forward opaque draw, or the deferred geometry pass and composite. The background a refractive or transmissive surface samples: the one phase whose colour holds what is behind such a surface without holding the surface itself. A pass that lights or changes the opaque scene runs here, ahead of the air that hazes it (the aerial perspective at 98, the height fog at 100) and of the transparent phase: the built-in lighting terms (probe field, sky light, image-based environment, area lights, local contact shadows, surface weather, capsule occlusion, subsurface scattering, cached indirect, resampled direct, ray-traced shadows), the splat clouds and the outline shells stand at orders 1-96, so the haze covers their light and a see-through draw in front of a surface is not lit by that surface's light |
| `afterTransparent` | transparents drawn, before the OIT composite |
| `afterLighting` | deferred-lighting + OIT composite done — fully lit, final geometry on **both** paths. Where the air hazes the scene (aerial perspective, height fog), the opaque scene here is already hazed, so light a pass adds here lands over the fog and over every see-through draw |
| `afterScenePost` | the chain's `scene` layer and the display transform done: display code values, before the chain's `display` layer and the UI |
| `afterUI` | scene + UI composited |
| `afterPost` | the chain's `all` layer done — the finished picture in display code values, before the output stage writes it to the surface. A pass here reads that picture as `@scene.color` and draws over a copy of it |
The last three are the post-scene phases, and they work on the COMPOSITED image:
`@scene.color` there is the target the UI lands on, not the scene render target.
`@scene.depth` and `@scene.motion` still bind — they are the scene's own buffers
for the frame just drawn, which is what lets a pass at these phases reproject the
composite it is handed — and on the deferred path so do the G-buffer channels
(`@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive`), the
surfaces of that same frame, so a look drawn over the finished picture reads
what each pixel's surface is without copying the G-buffer at an earlier phase.
All of them keep the SCENE's resolution. Whenever the
render scale is below 1 on the presented frame, that is smaller than
`@scene.color`, so a pass here maps between the two by uv rather than by texel
index, and takes its own output size from the target it writes.
**A texture is a texture.** A pass's sampled input names any texture the engine
holds by the handle that made it: a render target or a texture
`renderer.texture.create` returned (its guid), or a storage texture a compute
shader created (`ref:createStorageTexture2D`, its `key`). Which one it is decides
nothing about whether the pass accepts it. A pass sees the contents a texture
holds when the pass runs: a compute shader that wrote the texture in an earlier
pass of the same frame, or in a `dispatchEx` recorded at the start of the frame,
is read by a pass at any later point of the frame, and a pass that reads a
target an earlier phase of the frame draws sees that draw once the phase has run.
The `@scene.*` inputs (`@scene.color`, `@scene.depth`, …) bind the live frame
buffers; the deferred g-buffer channels (`@scene.normal`, `@scene.shaded`, …)
resolve only on the deferred path. Before the pass that shades has drawn — at
`afterDepthPrepass` — a g-buffer channel holds the previous frame's surfaces,
and a pass reading it there names the slot in `readsPrevious`
(`readsPrevious = { "scene_normal" }`); one that does not is held back rather
than handed a stale normal. `@scene.colorHistory` is the lit colour the target's
previous render ended with, kept by the engine per render target and never
cleared by a frame: what a pass tracing at `afterDepthPrepass`, against this
frame's depth, takes its light from — reprojected through the previous
view-projection `@frame.camera` carries. A capture drawn once, or a camera drawn
again after a pause, is drawn lit first when a pass reads the history, so its
first frame holds one.
Every `@scene.*` channel, what it holds, its format, the phase it is first
valid from, and the other names it answers to:
| Name | Holds | Format | Valid from | Also named |
|---|---|---|---|---|
| `@scene.color` | the scene's lit colour; the display composite at a post-scene phase | the scene target's format at a scene phase, the display composite's at a post one | every phase | — |
| `@scene.depth` | opaque depth, reversed (1.0 near, 0.0 far/empty sky) | `Depth32Float` — binds through a `texture_depth` compute slot, not `texture2d` | `afterDepthPrepass` on | — |
| `@scene.motion` | screen-space NDC velocity since the previous frame | `Rg16Float` | `afterOpaque` on | — |
| `@scene.normal` | world-space normal + the per-pixel surface-flag field | `Rgb10a2Unorm` | deferred path, `afterOpaque` through `afterPost` (previous frame's before — declare `readsPrevious`) | — |
| `@scene.shaded` | what a surface SENT — its shaded colour, linear and scene-referred | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.albedo` |
| `@scene.material` | what a surface IS — base colour (RGB565) + metallic + perceptual roughness | `Rgba8Uint` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.mr` |
| `@scene.emissive` | radiance a pass stamped on the surface, added at the composite | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | — |
| `@scene.ao` | scene occlusion a feature wrote, read back by shading: occlusion in r, the bent normal laid flat on the octahedron in g and b, and in a whether a bent normal was written | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.sunOcclusion` | the share of the sun's direct light a feature found taken on the way to each pixel's surface (`.rgb`, 0 none to 1 all), read back by the sun's term alone | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.reflection` | traced reflection radiance (`.rgb`) + confidence (`.a`) | `Rgba16Float` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.indirect` | the indirect diffuse light the surfaces closing each pixel's hemisphere send it (`.rgb`, in the ambient term's units) + the share of the closed hemisphere it answers for (`.a`), read back by the diffuse term through `zero_scene_indirect_here`; the second layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | every scene phase (cleared at the top of every scene render) | — |
| `@scene.decal` | the base colour stamped over each pixel's opaque surface, premultiplied by its coverage (`.rgb`), with that coverage (`.a`); written at `afterDepthPrepass` (blend `premultiplied`), and every opaque surface takes it into its own base colour before it is lit (`zero_take_scene_decal`, which `zero_pbr_shade` calls), so the stamp is lit, shadowed and written to `@scene.material` with the surface; the third layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | `afterDepthPrepass` through `afterSky` (cleared at the top of every scene render and again once the opaque surfaces have shaded, so a surface drawn after them takes none) | — |
| `@scene.colorHistory` | the lit colour the target's previous render ended with | `Rgba16Float` | every phase | — |
| `@scene.media` | the media trace's coverage by kind: what the participating media and the see-through draws laid in front of each pixel's opaque surface, as the share the cloud layer covers (`.r`), a volumetric medium (`.g`: a volume, smoke, fire, a volume sequence, a fog bank) and a see-through surface (`.b`: every blended draw, such as water, glass, particles and cards, and a fluid surface) cover, premultiplied, with their coverage in `.a`. A blended draw covers the share of the pixel its blend equation changes: its alpha under `alpha` and `premultiplied`, the strength of the light it adds (its brightest channel, saturating at 1) under `additive`, and how far its factor departs from 1 under `multiply`. Each producer blends its trace premultiplied source-over what stands behind it, so the nearer hold the larger share. A view keeps it only while a pass reads it; a pass writing it alone runs only on such a view. `@builtin::shaderModules.media_trace` reads and writes it | `Rgba16Float` | `afterSky` through `afterPost`, the post-scene phases included (cleared at the top of every scene render) | none |
| `@scene.mediaSurface` | the distance from the camera to what covers each pixel (`.r`, world units) and its world normal laid flat on the octahedron (`.gb`; a medium states the direction back toward the camera), premultiplied by the coverage in `.a`; the second layer of the texture `@scene.media` is the first of | `Rgba16Float` | as `@scene.media` | none |
| `@scene.lights` | the punctual-light storage buffer: 1024 light entries of eleven vec4s each (the light, then its projection, which names the shadow record it casts through), the light grid, then the virtual shadow map's region: a shadow record per casting light and their page tables. A loop runs over the first `@frame.camera[4].w` entries, the lights in use; the buffer's length counts the regions after the lights too, so `arrayLength` does not size a light loop | storage buffer | every phase | — |
| `@scene.shadowPool` | the depth pool every shadow-casting light renders its shadow pages into, read beside `@scene.lights` through `@builtin::shaderModules.light_shadows` (`zero_light_shadow`): the shadow a point, spot or area light casts at any world point, the one the surfaces take. A frame with a pass reading it keeps the coarsest page of every map of each casting light whose reach meets the view | `Depth24Plus` — binds through a `texture_depth` compute slot | scene phases only | — |
| `@scene.sunShadow` | the sun's virtual shadow map as the view being drawn reads it: its basis, depth range, clipmap levels and window origins and where its page table starts in `@scene.lights`, read beside `@scene.lights` and `@scene.shadowPool` through `zero::sun_shadow` (`zero_sun_visibility`): how much of the sun reaches any world point, past the occluders that shadow the surfaces. A frame with a pass reading it keeps the sun's pages under the air the view looks through | storage buffer (`ZeroVsmUniform`, a `kind: buffer` slot with `array: false`) | scene phases only | — |
| `@scene.environment` | the reflection-probe cube array | texture cube array | scene phases only | — |
| `@scene.environmentSampler` | the filtering sampler for `@scene.environment` | sampler | scene phases only | — |
| `@scene.reflectionProbes` | the environment buffer: the probe blend data naming which probe reaches a point, then the irradiance light-probe volumes | storage buffer | scene phases only | — |
The rendering and ray-tracing guides (`guides { path = "topics/rendering" }`,
`guides { path = "topics/raytracing" }`) point here rather than repeating this
table.
**What a full-frame pass reads, at each stage, on each path.** A full-frame
pass is a fragment or compute pass of a render feature, or an effect of the
post-process chain (`postprocess.add`). The G-buffer channels above are what the
deferred path knows about each pixel's surface, and they are the four the paths
differ on:
| Channel | Deferred path | Forward path |
|---|---|---|
| `@scene.color`, `@scene.depth`, `@scene.motion` | every stage (depth and motion from `afterDepthPrepass` and `afterOpaque` on, as the table states) | the same |
| `@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive` | `afterOpaque` through `afterPost`: the `lighting`, `medium`, `preTemporal`, `temporal`, `postTemporal`, `meter`, `optics`, `display` and `ui` stages, and every layer of the chain. Before `afterOpaque` a pass naming one in `inputs` reads the previous frame's surfaces (`readsPrevious`), and the surface helpers read their stated substitute with `zero_scene_surfaces_drawn()` false | none: the forward path draws no G-buffer. A pass naming one as an input is skipped, and the log names the channel and the reason. A shader reading one through the surface helpers reads its stated substitute (zero) and `zero_scene_surfaces_drawn()` reads false, so it draws a picture of its own there |
Two readers reach them. A pass names a channel in `inputs` (or a compute
binding), as above. A fragment pass's shader, or a chain effect's, reads them
by screen uv through the post framework's surface helpers (`zero_scene_normal`,
`zero_scene_material`, `zero_scene_shaded`, `zero_scene_emissive`; the shader
type README's post-process section has the table), which spend none of the
pass's input slots. Either way a render keeps a channel only when
something reads it: a queued pass naming it, a queued fragment pass whose
shader calls its helper, or a running chain effect that does. The channels
are at the scene's resolution, so a pass after an upscale reads them by uv.
A pass before the `temporal` stage reads each channel as the raster drew it,
with this render's sub-pixel offset. With temporal antialiasing running
(`@builtin::systems.antiAliasing.temporalAntiAliasing`), a reader after the
`temporal` stage reads `@scene.depth`, `@scene.normal` and `@scene.material`
restated at each pixel's centre, with no sub-pixel offset, so under a still
camera they hold still the way the resolved picture does: the restatements
run on a frame where a pass after them names the channel or a shader reads it
through its helper, and a chain effect reading the helpers is such a reader.
`@scene.shaded` and `@scene.emissive` keep the raster's sub-pixel offset at
every stage. `ctx.renderPath` names the path a feature's
`render(ctx)` runs on, and `postprocess.status()` lists, for each effect, the
channels it `reads` and, after a frame it drew with their substitute, the
`substituteReason`.
**Two g-buffer channels describe the surface, and they answer different
questions.** `@scene.shaded` is what a surface SENT — the colour the geometry
pass shaded it to, linear and scene-referred, so a surface lit above the
display's peak reads above 1 there. `@scene.material` is what the surface IS:
the base colour it reflects, its metallic and its perceptual roughness, each in
[0, 1] and each independent of how brightly the surface happens to be lit. A
pass that multiplies incoming light by a reflectance — a bounce multiplier, a
Fresnel tint, an ambient floor — reads `@scene.material`; a pass that filters
the picture reads `@scene.shaded`.
`@scene.material` is an `Rgba8Uint` channel packing all three into 32 bits, so
its slot declares `sample: uint` and the module unpacks it:
```yaml
# bindings.yaml
- { name: scene_material, kind: texture2d, sample: uint }
```
```wgsl
#include "@builtin::shaderModules.gbuffer_material"
let m = zero_gbuffer_material(scene_material, coord);
let bounce = incoming * m.base_color;
```
`@scene.albedo` is another name for `@scene.shaded` (the SHADED lit colour) and
`@scene.mr` for `@scene.material` (the material channel). The engine logs the
substitution once per name, naming the canonical one to write.
`@scene.motion` carries screen-space velocity: the NDC displacement each pixel's
surface underwent since the previous frame, so a still surface under a still
camera reads `(0, 0)`. Opaque geometry contributes it on both render paths:
the visibility raster writes it for every surface it records, and an opaque
surface whose depth state the raster cannot express writes its own where it
draws. A moving entity, a moving camera and an animated pose all reach it in
the viewport; transparents, particles and sky carry none. A surface a
material's `vertex()` hook displaces carries the displacement's own velocity. A render target's own camera and a
capture keep no view history, so velocity there is the entity's motion with no
camera term.
`@frame.camera` is a reserved **buffer** input carrying the camera CURRENTLY
being drawn: 18×`vec4<f32>` = the inverse view-projection (columns `[0..4)`,
column-major) + camera world position (`[4].xyz`, with the number of lights
`@scene.lights` holds in `[4].w`) + the previous render's view-projection
(columns `[5..9)`), which projects a point into the picture that render left +
the view-projection itself (columns `[9..13)`), which projects a world point
onto the view being drawn and is the matrix the scene rasterized with + the
sub-pixel offset that matrix carries (`[13].xy`, in NDC; zero without a
temporal upscale) + the view-projection with no sub-pixel offset (columns
`[14..18)`), the matrix the view's next render states as its previous one, so
a view drawn again from where its camera stands reads `[14..18)` word for word
equal to `[5..9)`. A compute pass declares a
`buffer` binding and binds it via `inputs = { name = "@frame.camera" }`, then
reconstructs a pixel's world position from `@scene.depth`:
```wgsl
let inv_vp = mat4x4<f32>(cam[0], cam[1], cam[2], cam[3]);
// ndc.z is the `@scene.depth` sample itself. Scene depth is reversed — 1.0 is
// the near plane, 0.0 the far plane and empty sky — and this matrix inverts
// that same range, so a sample goes in unmodified.
let wh = inv_vp * vec4<f32>(ndc, 1.0);
let world_pos = wh.xyz / wh.w;
```
Like `@scene.*`, the engine resolves it **per render target** — so the same pass
reconstructs against the live viewport's camera on screen and against an
offscreen capture's / RTT camera off screen. (Pack a camera matrix into your own
buffer instead and the offscreen render reconstructs against the wrong camera.)
> Render-feature passes run in the main viewport render **and** in offscreen
> captures / render-to-texture, each against its own camera. The `capture` tool's
> `source = "position"` / `"entity"` therefore run the pass queue too; using
> `@frame.camera` is what keeps those captures matching the live viewport.
### The view's matrices
`@frame.view` is a reserved **buffer** input carrying the view CURRENTLY being
drawn as the separate matrices a view-space algorithm is written against, which
`@frame.camera` states only as their product: 17×`vec4<f32>`, every matrix
column-major and none carrying a sub-pixel offset. Columns `[0..4)` hold
world-to-view; `[4..8)` hold view-to-clip, so `[4..8)` times `[0..4)` is
`@frame.camera`'s view-projection with no sub-pixel offset (`[14..18)`).
`[8..12)` and `[12..16)` hold the same two matrices as the view's previous
render drew with, the pair `@frame.camera`'s `[5..9)` is the product of; a view
with no previous render, or one that opens a new shot, states its own matrices
there. `[16]` holds the camera's near distance in `x` and its far distance in
`y` (both 0 where the view's projection is handed in whole, an environment
face, whose view-to-clip holds that whole matrix under an identity
world-to-view), and in `zw` the sub-pixel offset the render's projection
carries in pixels of the raster it is drawn at, along the NDC axes (x to the
right, y up; zero without a temporal upscale).
Like `@frame.camera` it is resolved **per render target**: the viewport, a
capture and a render-to-texture camera each read their own camera's matrices.
Its words differ from view to view and frame to frame, so a versioned pass that
binds it is refused. A pass that stands from frame to frame reads it on the
GPU like the other `@frame.*` buffers.
```yaml
# bindings.yaml
- { name: frame_view, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
let world_to_view = mat4x4<f32>(frame_view[0], frame_view[1], frame_view[2], frame_view[3]);
let view_to_clip = mat4x4<f32>(frame_view[4], frame_view[5], frame_view[6], frame_view[7]);
let near = frame_view[16].x;
let jitter_pixels = frame_view[16].zw;
```
```luau
inputs = { frame_view = "@frame.view" }
```
### The scene's light
`@frame.light` is a reserved **buffer** input carrying the scene's sun and
ambient term as the camera being drawn is shaded by them, the values the lit
passes read in the same frame: 3×`vec4<f32>` = the direction the sun's light
travels (unit, world space) with its intensity in `w`, the sun's colour with
`w` 1 while it casts shadows, and the ambient colour with its intensity in `w`.
A pass that lights a participating medium (clouds, haze, fog) reads its sun
here rather than carrying one of its own, so a day cycle, a scripted sun and a
sun switched off reach the medium in the frame they reach the surfaces, and a
scene with the sun and every light at zero leaves it black. `#include
"@builtin::shaderModules.frame_light"` reads it, and states the sun's light
either in the units the scene's lights are stated in
(`zero_frame_light_sun_irradiance`), for a medium that scatters those lights
too, or as the share of a medium's authored brightness the sun lights (its
intensity up to a unit sun, `zero_frame_light_sun_tint`):
```yaml
# bindings.yaml
- { name: scene_light, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
#include "@builtin::shaderModules.frame_light"
let light = zero_frame_light(scene_light[0], scene_light[1], scene_light[2]);
let toward_sun = zero_frame_light_toward_sun(light);
let sun = zero_frame_light_sun_tint(light) * authored_brightness;
```
```luau
inputs = { scene_light = "@frame.light" }
```
### The frame's clock
`@frame.clock` is a reserved **buffer** input carrying what the frame is doing:
3×`vec4<f32>`, the same for every view drawn in the frame. `[0]` holds the
shading time in seconds (the instant a `renderer.temporal.hold` pins while one
stands) in `x`, the seconds the frame advanced it by in `y`, that step in
sixtieths of a second in `z`, and the frame index in `w`, counted from the
engine's start and wrapping at 2^24 so a float holds it exactly (0 while a hold
stands, with a step of 0). `[1]` holds four values drawn uniformly from [0, 1)
by hashing the frame index: the seed a pass derives its per-frame random
rotation, jitter or sample offset from. `[2]` holds in `x` the wall-clock
seconds since the renderer drew its previous frame (at most 1), which runs in
every mode, paused play and a `renderer.temporal.hold` included: the step a
rate on the wall clock, such as an exposure adapting, advances by. A pass
reads these words, so a feature
whose passes stand from frame to frame writes none of them into a buffer of its
own, and states no `version`: a versioned pass that binds the clock is refused,
since the words differ on every frame.
```yaml
# bindings.yaml
- { name: frame_clock, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
let time = frame_clock[0].x;
let step_scale = frame_clock[0].z;
let frame = u32(frame_clock[0].w);
let seed = frame_clock[1];
let wall_step = frame_clock[2].x;
```
```luau
inputs = { frame_clock = "@frame.clock" }
```
### The environment
A compute pass reads the scene's captured surroundings — the reflection-probe
cube array, its sampler and the environment buffer (the probe blend data, then
the irradiance light-probe volumes) — through three reserved inputs, bound to
bindings of the shapes group(0) binds them in:
```yaml
bindings:
- { name: environment_map, kind: textureCubeArray }
- { name: environment_sampler, kind: sampler }
- { name: zero_environment, kind: buffer, access: read, element: ZeroEnvironment, array: false }
```
```luau
inputs = {
environment_map = "@scene.environment",
environment_sampler = "@scene.environmentSampler",
zero_environment = "@scene.reflectionProbes",
}
```
Named like that, `#include "zero::environment"` in the shader resolves the
environment at a world point along a direction — `zpbr_sample_environment(world_pos,
dir, lod)`, the probes whose radius reaches the point blended by rank and
proximity, each through its proxy volume, and the sky under them — exactly as a
material's environment term does, so a reflection a pass draws and one a
material draws agree about the room they are in. A pass that reads several
directions at one point selects the probes once, `let probes =
zpbr_select_probes(world_pos);`, and gathers each direction with
`zpbr_gather_environment_with_probes(probes, world_pos, dir, lod)`, which answers
the radiance in `rgb` and the share of it the probes and sky claimed in `a`.
The three bind at the scene phases; a post or UI phase carries none. A `textureCubeArray` binding takes
`@scene.environment` alone, and a fragment pass has no slot of that shape.
## Pass kinds
`enqueue` runs one of six kinds (the `kind` field; default `"fragment"`):
- **`"fragment"`** — a full-screen shader over input textures. The program is a
GPU **material** (or `shader`) the feature constructed; `inputs` bind live
textures (`@scene.*` or RT guids), `output` is the target RT (omit = the
phase's default scene target). Post-process, blur, edge effects.
**Writing named G-buffer channels (`outputs`).** Instead of the single `output`
RT, a fragment pass may declare an `outputs` array — one or more targets, each a
named engine channel (`@scene.shaded` / `@scene.normal` / `@scene.emissive` /
`@scene.color`) or an RT guid — each with its own blend mode:
```luau
ctx.enqueue {
kind = "fragment",
shader = myShaderKey,
outputs = {
{ target = "@scene.shaded", blend = "under" }, -- premultiplied dst-over-src
{ target = "@scene.emissive", blend = "additive" }, -- one fullscreen pass, two targets (MRT)
},
phase = "afterOpaque", -- deferred: G-buffer filled, before the composite
}
```
Blend modes — the keywords every pass's `blend` takes, `src` being what the
pass returns and `dst` what the target holds:
| Keyword | Result |
|---|---|
| `"replace"` | `src` — overwrites |
| `"alpha"` | `src.rgb * src.a + dst.rgb * (1 - src.a)` — straight-alpha source-over |
| `"premultiplied"` | `src + dst * (1 - src.a)` — source-over for a colour already multiplied by its alpha |
| `"additive"` | `src + dst` — sums |
| `"under"` | `src * (1 - dst.a) + dst` — premultiplied destination-over-source: what the target holds stays in front, which accumulates coverage-weighted contributions |
A keyword outside the table raises from `ctx.enqueue`, naming the field. A
`@scene.*` channel resolves only where it exists (the deferred
G-buffer at a pre-composite phase); a pass whose targets are all unavailable at
its phase is skipped (logged). `output` + `blend = true` remains the shorthand
for a single alpha-blended target. The shader's returned colour is written to
every target in the set.
A fragment shader returns `vec4<f32>`, so the channels it can target are the
float ones. `@scene.material` (also named `@scene.mr`) is
`Rgba8Uint`, which binds as `uint` — naming it as an output is refused by
name, with the channel's format and class in the log, and the rest of the
frame draws. A fragment pass's `inputs` reads through the same fixed float
slot, so naming `@scene.material` there is refused the same way; a compute
pass reads that channel through a `sample: uint` slot instead.
**What a pass with no `inputs` samples.** A fragment pass that declares no
`inputs` reads `@scene.color` — the shape of an effect that filters the scene
image. A pass that names `@scene.color` among its own `outputs` samples a 1x1
transparent texel instead, because the scene colour is that pass's render
target and one texture is a colour attachment or a sampled resource in a render
pass, never both. Declare `inputs = { src = "@scene.color" }` and write an RT
to read the scene image and write somewhere else in one pass.
- **`"compute"`** — a workgroup dispatch (`shader`, `storage`, `buffers`, `dispatch`;
see "Compute passes").
- **`"geometry"`** — draw scene geometry with a constructed pipeline. The program
is a **material** the feature built (`renderer.material.create`); the engine
draws the scene's render-objects with that material's pipeline + uniforms.
- **`"draw"`** — rasterize the feature's OWN geometry: `geometry` names a buffer
created with `usage = { "vertex" }`, `storage.index` one created with
`usage = { "index" }`, and `select` the one entity whose transform and
material the draw lands through. `params[0]` is how many indices to submit —
or name a buffer under `storage.indirect` (created with
`usage = { "indirect" }`, holding a `DrawIndexedIndirectArgs` block: index
count, instance count, first index, base vertex, first instance) and the count
comes from the GPU instead, so a compute pass that compacts geometry pays only
for what it kept and nothing waits on a read-back. `first_instance` must be 0;
the engine resolves the entity's per-instance data another way, because a
non-zero one needs a device feature WebGPU does not guarantee.
- **`"splat"`** — rasterize a compute buffer of particle records as instanced
camera-facing billboards into feature RTs (see "Splat passes").
- **`"raster"`** — draw geometry the feature makes itself with a `.rasterShader`
of its own: `vertexCount` vertices for each of `instanceCount` instances,
pulled from the buffers the pass binds, into the scene or the feature's
targets, depth-tested against the scene (see "Raster passes").
### Geometry passes
A geometry pass re-draws the scene's meshes with a material you supply — the
generic primitive for mesh-space effects (the engine names none of them):
```luau
ctx.enqueue {
kind = "geometry",
material = myMaterial, -- the HANDLE renderer.material.create
-- returned (or its registry-key string)
geometry = "@geometry.opaque", -- which drawables: "@geometry.opaque" |
-- "@geometry.transparent" | "@geometry.all"
select = { entityA, entityC }, -- OPTIONAL: restrict to these entities
-- (entity refs); omit = every matching mesh
phase = "afterLighting", -- afterLighting = lit scene + valid depth
}
```
`select` restricts the draw to the given entities — the per-instance signal that
turns a whole-scene pass into a chosen-meshes effect. A pass with no `select`
also draws the instanced populations (`renderer.mesh.drawInstanced`) its
`geometry` set takes, every copy at its own slot, so a whole-scene pass sees an
instanced forest as it sees the entities around it. The **material** decides how
those meshes are drawn; you control three things:
- **Pipeline render-state.** `renderer.material.create` takes a `render` block —
`cull` (`back`/`front`/`none`), `depthWrite` (bool), `blend`
(`opaque`/`alpha`/`additive`) — so the pass can rasterize differently from the
surface pass:
```luau
local myMaterial = renderer.material.create({
shader = myShaderKey, -- a .shader you authored (identity, not guid)
render = { cull = "none", depthWrite = false },
properties = { outline_color = { 1, 0.4, 0, 1 } }, -- seed the shader's uniforms
}, "my_pass_mat") -- pass `myMaterial` (or "my_pass_mat") as the pass `material`
```
- **The shader.** A geometry `.shader` is a surface shader: author `fn vertex(v:
VertexData) -> VertexData` to move vertices (object-local `v.position` /
`v.normal`) and `fn fragment(input: FragmentData) -> vec4<f32>` for the colour.
- **Its properties.** A shader reads ONLY the uniforms IT declares in
`properties.yaml`, via `material.<yourProp>`. Referencing a field it didn't
declare (e.g. a StandardMaterial `material.base_color`) fails to compile and the
mesh renders **magenta** — declare the property or use a constant.
What effect those three produce (outline, x-ray, wireframe, highlight, …) is
yours to design — the engine just draws the selected geometry with your pipeline.
#### What a pass starts its target from (`load`)
A geometry or draw pass with no `output` draws over the phase's own scene target,
which holds the frame as it stands. A pass naming an `output` render target begins
by setting that target's colour and depth to a starting state, and `load` says
which:
| `load` | the target starts as |
|---|---|
| `"clear"` (default) | empty: transparent colour and the far depth, so the target holds only what this pass draws |
| `"keep"` | what it holds: colour and depth as the last pass to draw into it left them, so this pass draws over that, depth-tested against it |
Two geometry passes naming one `output` therefore leave only the second one's draw
by default, since the second pass starts from an empty target. State `keep` on the
second to draw both, the way one camera draws many entities into one target:
```luau
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupA, phase = "afterLighting", order = 0 } -- starts from empty
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupB, phase = "afterLighting", order = 1,
load = "keep" } -- draws over groupA's
```
`keep` loads what the target holds when the pass begins: the draws of the passes
before it this frame, and the previous frame's picture where none drew it first
(and where a screen-sized target is made again, an empty one). The first pass to
draw a target each frame says `"clear"` so the target starts the frame empty; an
accumulation across frames is the one that says `"keep"` there too. `load` is
refused, naming the field, on a pass that is not a geometry or draw pass or that
has no `output`. A splat pass loads its targets with `blend = true`, and a raster
pass clears them with `clear = true`.
**How much of each mesh it draws.** A pass drawing into a small map (a
top-down cover or height map, a coarse occlusion mask) holds none of the
detail finer than a texel, and two fields keep it from paying for that detail:
- `detail = 1.0` states the world-space size of the finest detail its target
holds. Each static mesh then draws at the coarsest cut of its cluster
hierarchy whose error, placed at the object's scale, stays within that size,
the cut the scene's own draw takes for a distant object: a building keeps its
walls and roof and a tree its crown, in far fewer triangles than their full
detail. A mesh drawing from its own vertex streams (a skinned or morphing
mesh, one with no cluster set yet) and an instanced population draw in full.
- `rigid = true` leaves out every mesh a skeleton poses or morph targets blend,
so a crowd of characters costs the pass nothing.
`renderer.feature.drawn()` reads what each geometry pass drew on the last drawn
frame, as `{ objects, triangles }` keyed by its material, so the difference
either makes is a number.
**Where each surface stands.** A geometry pass draws every object through the
pass's own material, at that material's depth bias. `objectDepthBias = true`
adds to it the depth bias (`depthBias`, `depthBiasSlope`, `depthBiasClamp`) each
object's own material states, so a pass testing against the scene's depth meets
a decal or an overlay its material lifts toward the camera at the depth the
frame drew it at; the `zfighting` capture view counts surfaces this way. A clamp
either side states caps the sum, and a versioned pass stating it draws in every
view.
### Compute passes
A compute pass dispatches a `.computeShader` program over a workgroup grid:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
storage = { outTex = myStorageRtGuid }, -- slot -> storage-texture RT guid
buffers = { particles = "my_particle_buf" },-- slot -> named compute buffer
inputs = { camera = "@frame.camera" }, -- slot -> @frame.*/@scene.* buffer
dispatch = { x = 64, y = 1, z = 1 },
}
```
**`dispatch` is optional.** Omit it and the pass is dispatched over what it
WRITES: a grid covering its first `storage` texture, at the `@workgroup_size` the
shader's entry point declares. With a screen-sized storage target that grid
tracks the render target being drawn, so a screen-space effect covers the live
viewport, an offscreen capture and an RTT camera without the feature knowing any
of their resolutions:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
inputs = { scene_color = "@scene.color", cam = "@frame.camera" },
storage = { outTex = myScreenSizedRt.guid }, -- screen = true
phase = "afterLighting",
}
```
State an explicit `dispatch` for a grid that is not one thread per output texel
(a reduction, a particle sim), or when the shader's `@workgroup_size` is an
override/const expression the engine cannot read.
**`dispatch = { indirect = <buffer>, offset = <bytes> }`** takes the grid from the
GPU: the pass runs the workgroup counts (x, y, z, three `u32`) found `offset`
bytes into the named compute buffer (default 0; a multiple of 4), which a pass
earlier in the frame wrote. A scheduling pass counts the work that exists this
frame, writes the counts, and the passes after it dispatch over exactly that
work, so a pass that touches one object in ten costs the one in ten:
```luau
-- the buffer is created with usage = { "indirect" }; the first pass writes its
-- three counts, the second dispatches over them
local args = schedule:createBuffer("args", { type = "f32", len = 3, usage = { "indirect" } })
ctx.enqueue { kind = "compute", program = schedule, buffers = { args = args }, dispatch = { x = 1, y = 1, z = 1 }, order = 1 }
ctx.enqueue { kind = "compute", program = work, buffers = { items = items }, dispatch = { indirect = args }, order = 2 }
```
`indirect` takes the buffer's handle or its name. A pass naming a buffer that does
not exist, was created without `usage = { "indirect" }`, or holds fewer than
three `u32` from `offset`, is skipped with a warning naming the buffer. A count
of zero in any dimension runs no workgroups. The pass that dispatches from a
buffer does not bind that buffer as a writable storage binding (the GPU reads
the counts while the pass runs); each count stays within the device's
`max_compute_workgroups_per_dimension` (65,535 on the WebGPU baseline), so a
count past it is split over x and y by the pass that writes it. `dispatch` states
either `x`, `y`, `z` or `indirect`, not both. Native and the web build dispatch
the same way.
Each WGSL storage-buffer binding in the shader resolves its bound slot in this
order: an explicit `buffers` mapping (the handle a buffer's owner holds, or a
name), then `inputs` (`@frame.camera` / `@frame.view` / `@frame.light` / `@scene.lights` /
`@scene.reflectionProbes`), then — when a slot has neither — a buffer whose
engine-side name equals the slot's own name. `buffers`
is the seam a pass binds through: the buffers a shader works over are the ones
handed to it, whatever each is called. `storage` binds storage TEXTURES (RT
guids) the same way, one map per resource kind.
**A table built from a few settings.** A compute pass whose targets follow
from inputs that rarely change (a lookup table, a baked noise volume) states
the version of those inputs as `version`, a string or a number. The pass runs
in a view only while some render target it writes holds no picture this
program recorded at this version, so the table is built in the first view
after the version moves and skipped in every later view and frame:
```luau
ctx.enqueue {
kind = "compute", program = bakeLut,
buffers = { settings = settingsBuf },
storage = { lut_out = lutRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g", density, falloff),
}
```
A pass reading the table later in the frame reads the picture it holds. The
table is built again when the version changes, when the pass's own
`params`, `dispatch`, `buffers` or `storage` change, when the program's
pipeline is rebuilt (an edit to its source), when a render target it reads
through its `inputs` holds a new picture (so a table built from another table
is built again whenever that one is, and one built from a camera's target or a
video target whenever that target draws), when another texture it reads there
holds new texels, when a pass of any other version or none writes the target,
when the target is reallocated or cleared, and when the device reports an error
after the build was recorded. What the build reads from a buffer's contents or
from a value its program holds (`ref:setParam`) belongs in the version. A pass reading a
texture a GPU producer outside the texture cache writes, a 3D texture, or the
scene's acceleration structure and hit tables is built in every view.
**A table built from the view being drawn.** A table that follows the camera
too (a sky seen from the camera's altitude) binds `@frame.camera`, and names
what its program reads of the view in `viewReads`: `"@frame.camera.position"`
(the camera's world position, `@frame.camera[4].xyz`) and `"@frame.light"`
(the whole light buffer). The engine names the build by those values as each
view holds them, so the table is built in a view drawn from where it was not
built and stands in every view and frame drawn from where it was. `render`
runs once a frame and states what follows from the frame alone in `version`;
the engine adds what each view holds:
```luau
ctx.enqueue {
kind = "compute", program = skyTable,
inputs = { cam = "@frame.camera", lut = transmittanceRt.guid },
buffers = { settings = settingsBuf },
storage = { sky_out = skyRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g,%.17g", sun.x, sun.y, sun.z),
viewReads = { "@frame.camera.position" }, -- built again when the camera moves
}
```
Every view of a frame shares the target, so a capture or a render-to-texture
camera standing elsewhere builds the table for its own camera, and the next
view drawn from the viewport builds it again for the viewport's. The program
reads nothing else of the camera buffer: its orientation, its projection and a
temporal upscale's sub-pixel offset move from frame to frame and name no build.
A geometry pass drawing a map of the scene into a render target of its own
(`output`) takes a `version` too. Its build is its material (the shader's
install, the row it draws with: its property values, textures, render state
and
# Shader module (asset type)
A `.shaderModule` is a block of WGSL that other shaders **include** rather than
copy — a lighting model, a set of colour-space helpers, one package's shared
prelude. It declares no entry point and is never dispatched or drawn on its own
account; it exists to be expanded into the shaders that name it.
## Folder shape
```
<name>.shaderModule/
module.wgsl # the WGSL — helpers, structs, constants (required)
README.md # what THIS module provides (required)
.metadata # tags and free-form fields (required)
```
Each file carries a committed `.meta` sidecar pinning its stable guid, and the
folder carries one of its own.
## Including one
A shader names a module by identity, and the identity is what records the
dependency — so a shader that is packed, pulled or published carries the modules
it includes with it:
```wgsl
#include "~.colour" // a module under the same `~.`
#include "@builtin::shaderModules.pbr_shading" // one from the builtin library
```
A missing module is a hard error at compile: a shader that names an interface
which no longer exists fails loudly rather than compiling against a stale copy.
Each module is expanded at most once per shader, so two shaders that both
include the same module — or a module that includes another — produce one copy,
not a duplicate-definition error.
## Writing one
Write only what other shaders need in scope: functions, structs, constants. A
module may reference a binding its includers declare, which is how a package's
prelude can read that package's uniform block.
```wgsl
const LUMA: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
let lo = c / 12.92;
let hi = pow(max(c + vec3<f32>(0.055), vec3<f32>(0.0)) / 1.055, vec3<f32>(2.4));
return select(hi, lo, c <= vec3<f32>(0.04045));
}
```
## Answering to another name
A module declares extra names it answers to with `@alias` lines in the header of
`module.wgsl`:
```wgsl
// @alias: colour_helpers
// @alias: @mypack::shaderModules.colour
```
Each becomes an alias on the asset, so the name resolves everywhere an identity
does: `asset.resolve`, an `#include`, and the publish gate alike.
Only the header is read — the scan stops at the first line that is not a
comment, so a directive cannot hide in the module body. A name another asset
already holds is refused and reported, since an alias extends the identity
namespace rather than taking a name out of another asset's hands.
## Registration & hot reload
Writing `module.wgsl` registers the module under every name the asset answers to
— its guid, its identity, and any alias — so a shader includes it by whichever
name it holds. Saving re-registers it and the shaders that include it recompile,
with no world reload. A compile reaches each module an include names and files it
again; a module whose `module.wgsl` holds the content version it held, whose names
are the ones it answered to and whose own includes resolve to the modules they
resolved to files the text it filed before, with the file neither read nor parsed.
## Discovery
- `asset.list("shaderModule")` — every registered module.
- `moduleRef:getSource()` — the module's WGSL.
## Related types
- `.shader` — render-domain shaders (surface, sky, post-process, screen).
- `.computeShader` — compute programs.
## In the Inspector
Selecting a shader module opens its **Module** section: how many lines it holds, the aliases a shader `#include`s it by, and an opener for `module.wgsl`.
# Preset (asset type)
A preset is a named set of typed values for one declarer's settings
schema: the texture assetType's, an importer's, a component's, any asset
that declares its own settings. Capture the settings something has now,
then apply them to anything the same declarer governs, instead of setting
the same values by hand each time.
## When to use one
- The same settings recur across many assets or entities (e.g. "pixel
art": every sprite texture with `filter = nearest` and no mipmaps; a
tuned locomotion set for every character of one rig).
- Designers swap configurations without editing code.
- A configuration needs a stable name other content can refer to.
If you're capturing a whole entity assembly, use a `.bundle`. If
you're factoring shared logic (not configuration), use a `.module`.
## Where it lives
- Source: `/zero/source/.../<Name>.preset/`
- Identity: `<Name>` (the `.preset` suffix strips).
- Folder shape:
- `preset.yaml` — the target and the values. **Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields (`title`,
`description`). **Required.**
## The document
```yaml
target: { __ref: "8cc28fc8-ed63-48ee-83a6-15f4192e27e1", type: assetType, name: texture }
values:
filter: nearest
generateMipmaps: false
```
- `target` names the declarer by a guid envelope: `__ref` is its guid;
`type` and the plain `name` tell a person reading the file what it
points at.
- `values` holds only the fields this preset sets. Fields it leaves out
keep whatever the asset or component has.
A component preset has the same shape, its target the component:
```yaml
target: { __ref: "18dfece3-fe1b-4630-b7ad-0996f5043a2e", type: component, name: Locomotion }
values:
walkSpeed: 1.4
runSpeed: 2.5
```
## How to create one
```luau
-- Capture what an asset has now:
local p = preset.capture("hero_sprite", "pixel_art")
-- Capture a component's live values on an entity:
local tint = preset.capture({ entity = id, component = "Model" }, "red_tint")
-- Both land at /zero/source/presets/<name>.preset/ (an absolute `.preset`
-- path lands where it says; `{ overwrite = true }` re-authors an existing
-- preset, keeping its guid).
-- Or author it directly:
asset.create("preset", "pixel_art", {
target = "@builtin::assetTypes.texture", -- an identity or a guid
values = { filter = "nearest" },
})
```
Each checks every value against the target's schema and refuses the whole
write on any violation, naming each one.
## How to use one
- `preset.values(p)` returns `(values, report)`. Every value is checked
against the target's current schema: valid fields are returned, and
each invalid one is listed by path in `report.rejected`.
- `preset.apply(p, into)` writes the valid values into an asset the
target governs, or into a component on an entity named
`{ entity = <id>, component = <name> }` whose component is the target.
A struct group merges field by field; any other field is written whole.
Applying to something another declarer governs raises, naming both.
- `preset.setValues(p, values)` replaces the whole values table, checked
first. Inside an undo operation the write is recorded into it, so undoing
the operation puts back what `preset.yaml` held.
- A preset is a snapshot, not a live binding: applying it writes values
once.
```luau
preset.apply("pixel_art", "enemy_sprite")
preset.apply("synty", { entity = id, component = "Locomotion" })
local values, report = preset.values("synty")
```
## Defaults for new things — the Preset Manager
A world's Preset Manager rows make a preset the starting point for what is
created from then on:
```luau
local p = preset.capture("hero_sprite", "pixel_art") -- or asset.create("preset", …)
preset.addDefault(p, { filter = "sprites/**" }) -- new things only
```
Each row names a declarer, a preset for it, and a filter. For a declarer,
the first row whose filter matches the new thing's path applies. The rows
live in `.world_settings` as `[[presets]]` blocks, sync with the world, and
are edited in the Settings panel's **Preset Manager** section.
**The layers a new thing's settings take**, each over the ones before it,
field by field (a struct group merges field by field):
1. the schema's declared defaults;
2. the type's own `settingsDefaults`;
3. the first matching Preset Manager row;
4. the creating importer's settings for the type;
5. the values the caller passed.
A component takes its `public` defaults, then the row, then the values the
caller passed.
**Rows change only new things.** A row's values are stamped into what is
created while it stands. Editing or removing a row changes nothing that
already exists, and opening a world applies nothing to its saved content. A
re-import or an `overwrite = true` re-authoring keeps the settings the asset
already holds.
**The three creation moments, and what each filter reads:**
| Moment | The row's declarer | The filter reads |
|---|---|---|
| `asset.create` | an assetType whose instances share its schema | the new asset's path under `/source` (`sprites/hero.texture`); a runtime asset reads the path the same call would give a durable one |
| an import | an importer | the source file's path under `/source` at its first import (`sprites/hero.png`) |
| `component.add` | a component | the entity's hierarchy path, names from the root down joined with `/` (`level/props/crate`) |
A component takes a row when it is added in edit mode, and in any mode
inside a scene build (a scene's `build.luau`, a `SceneModule` placement). A
component put back from existing content (a saved scene, a peer's record, a
template, a bundle's hierarchy, what a component's own code adds outside a
build) takes none. A rebuild restates a component only when its code states
it differently, so a row edit alone changes nothing a build already placed.
**Checking what applies:**
- `preset.defaults()` lists the rows in order, each resolved, with every
problem that keeps it from applying.
- `preset.defaultFor(declarer, path)` returns the values a new thing at
`path` would take from the rows, and the row that gives them.
## In the Inspector
Selecting a preset shows, beside its identity:
- **Target** — the declarer as an asset chip and the guid the preset names
it by, with a notice when the target changed since the preset pinned it
or does not resolve.
- **Values** — every field of the target's current schema as its typed
control, the way the target's own Settings section shows it. An edit is
checked against that schema, written with `preset.setValues`, and is one
undo step. A stored value the schema refuses is named with the reason.
Beneath the fields, **Apply to selection** writes the preset into every
selected asset its target governs and into the target component on every
selected entity, as one undo step.
Every asset's and component card's Settings section offers **Save as
preset**, which captures the values it shows as a preset targeting their
declarer and selects it, and **Apply preset…**, which lists the presets
targeting that declarer and applies the one picked.
## How the target stays bound
- The preset resolves its target by the envelope's guid, and the preset's
`.refs` pins that guid together with the target's checksum, so the link
survives the target being renamed or moved. The envelope's `name` is
never an identity, so the guid is the preset's one link to its target.
- Every read re-checks the values against the target's schema as it is
now. `report.pinned` is true once `.refs` pins the target;
`report.targetChanged` is true while the target's checksum differs from
the one pinned, and a field the target dropped or retyped is then
rejected by name while the rest still apply.
## Discovery
- `asset.list("preset")` — every registered preset.
- `asset.inspect("<name>").detail` — `target`, `targetGuid`, `format`,
`values`, `rejected`, `pinned`, `targetChanged`.
- `asset.validate("<name>")` — `preset.target_unresolved` when the target
does not resolve, `preset.value_rejected` for each value its target
rejects.
## Authoring conventions
- Name presets by the configuration they capture (`pixel_art`,
`hdr_skybox`, `synty`), not by the declarer.
- Keep `values` to the fields that define the configuration; fields left
out stay as each asset or component has them.
## Common pitfalls
- **Hand-edited values.** A value the target's schema rejects is
reported, not applied, and every edit of the file warns naming it.
- **A table-valued component field** (a `Field.table`) is written whole
by `preset.apply`, so a preset holding one provides every key of it.
## Related types
- `.assetType` / `.importer` / `.component` — the declarers whose
settings a preset holds.
- `.bundle` — for multi-component / multi-entity assemblies.
# Raster shader (asset type)
A `.rasterShader` is a GPU program a render feature draws with: a vertex stage
that makes every vertex itself, from its `@builtin(vertex_index)` and
`@builtin(instance_index)` and whatever it pulls from the buffers it binds, and
a fragment stage that colours what those vertices cover. No mesh and no vertex
buffer stand behind it, which is what an instanced field of grass, kelp,
leaves, debris or sprites wants: one buffer of per-instance records, one draw.
It is drawn by a render feature's `kind = "raster"` pass (`renderFeature`
assetType README, "Raster passes"), with its own pipeline, depth and blend —
the shape a hand-written renderer ports into. An instanced field can also be
drawn through an engine material: the guide `topics/rendering-instance-data`,
section "Instanced foliage built in the vertex shader — grass, kelp, hair
cards, debris", builds it in a surface shader's `vertex()` from
`zero_object_data(v.instance_id, lane)` and `v.vertex_index` on a mesh drawn
with `renderer.mesh.drawInstanced`, and that field is lit, casts and receives
shadows, writes motion vectors and takes fog and post-processing as every
material does.
## Folder shape
```
<name>.rasterShader/
shader.wgsl # `@vertex fn vs_main` + `@fragment fn fs_main` + helpers (required)
bindings.yaml # the binding + params schema (required)
README.md # what this shader draws (required)
.metadata # asset metadata
```
`bindings.yaml` is the schema a `.computeShader` declares — the same `kind`s,
`access`, `element`, `array`, `format`, `sample` and `params:` — and the engine
generates every `@group(0) @binding(i)` line from it, so `shader.wgsl` holds no
binding declaration of its own. The `computeShader` assetType README carries the
full table.
- **A binding the vertex stage reads is `access: read`.** A writable storage
buffer or storage texture is laid out for the fragment stage alone, and a
`vs_main` reading one is refused at the compile, naming the binding.
- `vertices` (a mesh's vertices) and `acceleration_structure` are compute
bindings; a raster shader declaring one is refused.
- A `sampler` states how it samples (`filter`, `mipmap`, `address` /
`addressU` / `addressV` / `addressW`, `anisotropy`), and one stating
`compare` is a `sampler_comparison` for `textureSampleCompare` on a
`texture_depth` — a shadow map a pass drew, bound as `@depth.<guid>`.
- Each stage holds the device's per-stage counts: 8 storage buffers, 4 storage
textures, 16 sampled textures and 16 samplers. A read binding counts in both
stages.
## The two entries
```wgsl
struct VOut { @builtin(position) clip: vec4<f32>, @location(0) uv: vec2<f32> };
@vertex fn vs_main(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> VOut { ... }
@fragment fn fs_main(in: VOut) -> @location(0) vec4<f32> { ... }
```
`fs_main` returns one `@location(i)` colour per target the pass draws into (a
struct of them for several). A pass whose target count differs from what
`fs_main` writes is skipped, and the log says both numbers.
## The camera
Bind `@frame.camera` to a read buffer and the vertex stage places its vertices
with the camera of the view being drawn — the live viewport, a capture, a
render-to-texture camera — each through its own matrix:
```yaml
- { name: cam, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
let view_proj = mat4x4<f32>(cam[9], cam[10], cam[11], cam[12]);
out.clip = view_proj * vec4<f32>(world_position, 1.0);
let camera_position = cam[4].xyz;
```
`cam[9..13)` is the view-projection the scene rasterized with this render, so
a clip position it produces lands on the scene's own depth. `cam[5..9)` is
the previous render's view-projection and `cam[13].xy` the sub-pixel offset this
render's matrix carries, which a pass writing `@scene.motion` reads. The rest
of the buffer is in the `renderFeature` README (`@frame.camera`).
## Compile errors
A compile that fails logs `[rasterShader] Compile of raster shader
'<folder>' (<key>) failed: <reason>` with the WGSL error or what the entries
lack, and a pass drawing the shader states the same reason once, when it is
first skipped.
## Compiling
A raster shader compiles when it is written and when its world loads; there is
no setup step. `ref:compile()` compiles it now and answers `false, reason` with
the WGSL error or what the entries lack; `ref:state()` answers `"pending"`,
`"ready"` or `"failed", reason`. `ref:getBindings()` lists the declared schema
and `ref:setParam(name, value)` sets a `params:` uniform.
```lua
local leaves = asset.resolve("leaves", "rasterShader")
print(leaves:state()) -- "ready"
```
# Shader (asset type)
A shader is a WGSL program that runs on the GPU. Materials reference shaders and
supply property values; renderable entities reference materials, not shaders
directly. This README is the canonical reference for writing **every** kind of
shader — it covers all domains, the surface authoring contract, the material
property schema, the engine library functions you can call, and how a shader
registers and compiles.
> New to how shaders, materials, meshes, and textures relate as assets and live
> GPU resources? Read `core/resource-model` first.
## Folder shape
A `.shader` is a folder asset:
```
<name>.shader/
shader.wgsl # the WGSL body (required)
properties.yaml # the material property schema (optional; surface shaders)
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 `.shader` suffix strips).
A shader's material properties are exactly the ones its `properties.yaml`
declares: a shader with no `properties.yaml` declares none, and the engine
reads no property from the WGSL body. A `.wgsl` file standing on its own,
outside a `.shader` folder, is WGSL source rather than a shader: a material
draws with the `.shader` folder that holds it as `shader.wgsl`. Materials and other assets
reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw
string.
## Domains
The first line of `shader.wgsl` declares the domain:
```wgsl
// @domain: surface
```
| Domain | What it is | You write |
|---|---|---|
| `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. |
| `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `compute` | GPU data processing, no rasterization. | An `@compute @workgroup_size(...)` entry over storage buffers; you write the `@group/@binding` lines yourself. For compute work, the `.computeShader` assetType (see below) generates them for you. |
`// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui`
as further spellings of `post-process` and `screen`. A body carrying no
`@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body
declares, a further spelling as the domain it names. Any other name is refused where the shader
registers, with an error naming the spellings that resolve, so a shader reaches
the renderer only under a domain the compiler scaffolds.
Particles are drawn and simulated through these domains like anything else: the
particle package's `particle_sprite` and `particle_mesh` are `surface` shaders,
and its simulation, culling and sorting steps are `.computeShader` assets.
## Texture coordinate space
A shader that samples a texture through a coordinate it builds itself declares
which space that coordinate lives in, on a line beside `@domain:`:
```wgsl
// @domain: surface
// @uv_space: world
```
| Value | The coordinate | A material's `uv_scale` means |
|---|---|---|
| `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. |
| `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. |
Texture residency reads the declaration to work out how finely a frame samples
each texture: a material laying eight copies of its texture across a surface
samples each copy at an eighth of the surface's size, and the mip level that
serves it is three levels coarser than the surface's own footprint implies.
Leaving the line out puts the shader in mesh space, which is what sampling
`input.uv` is. `renderer.textureStreaming().textures` reads back the span each
texture was measured at and the level that span asked for.
**Compute shaders have their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`.
**Surface**, **sky**, **post-process**, and **screen** shaders all get
engine-generated scaffolding — you write only `fragment()` and declare properties in
`properties.yaml`; the engine generates the entry points and the group(1) material
interface. (Each domain's `fragment` takes a domain-specific input instead of
`FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and
"Post-process & screen shaders" below.) Compute shaders get the same treatment via
the separate `.computeShader` assetType (write only `@compute fn main`, declare
bindings in `bindings.yaml`). The `compute` domain here writes its own
entry points directly — see `man compute`.
## Surface shaders
A surface shader writes **only** the parts that are unique to it. The engine owns
all the scaffolding — the vertex stage, every render-mode entry point
(`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights,
shadows, and the material rows), and the material interface generated from
`properties.yaml` (`material` and your texture slots). Adding a render path never
touches your shader.
Inside `fragment()` you have access to exactly four things — nothing is hidden:
1. **`input: FragmentData`** — the interpolated per-fragment surface data the
engine hands you: world position, world normal, uv, view direction, vertex
colour, and more. Every field is in the `FragmentData` table below.
2. **`material.*` and your textures** — the material inputs **you** declare in
`properties.yaml`. The mapping is mechanical: a scalar property named `foo`
becomes `material.foo`; a texture property named `bar` becomes `bar` (the
texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields
your `properties.yaml` declares and no others — to add an input, add a property.
List what a shader exposes with `shaderRef:getProperties()` or
`asset.inspect("<name>")`.
3. **Engine state** — the scene's camera, lights, time, and shadows that the
renderer binds for every surface shader. In a surface shader `uniforms.*`
(sun direction/colour, ambient, `camera_pos`, `time`) and the punctual
lights (`zero_point_light(i)`) are always in scope (a post-process shader
has neither; its section below names what it reads instead); the shadow functions come from `#include "@builtin::shaderModules.shadows"`,
and the light of the sky, the reflection probes and the light-probe volumes
from `zero_pbr_surroundings_light` in `@builtin::shaderModules.pbr_shading`. This is how
you light a surface **without** the prebuilt PBR — see "Engine state" and
"Writing your own shading" below.
4. **Library functions** you `#include` (see "Library includes").
A shader and its property schema go together. The two files below are a complete
surface shader:
`properties.yaml` — declares the material inputs:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: base_color_texture, type: texture, default: white }
```
`shader.wgsl`; those declarations are read as `material.base_color`,
`material.roughness`, `material.metallic`, and the `base_color_texture` /
`base_color_texture_sampler` pair:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes"
fn fragment(input: FragmentData) -> vec4<f32> {
var s = zero_pbr_default_surface(input);
s.albedo = material.base_color.rgb
* textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb;
s.perceptual_roughness = material.roughness;
s.metallic = material.metallic;
return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a);
}
```
`fragment()` returns the final colour. The engine forces no lighting model on
you — flat, toon, PS1, dithered, or PBR are all just different `fragment()`
bodies. Calling `zero_pbr_shade` is opt-in.
### The two surface bodies, and what each gives up
A surface shader exposes one of two entry points, and which one decides how
much of the shader the engine can see:
| Body | The engine gets | PBR debug passes and the G-buffer read |
|---|---|---|
| `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the surface behind it where the body hands one over: `zero_pbr_shade` hands over the `PbrSurface` it lights, and a body that lights itself hands over its own with `zero_publish_shaded_surface` | the surface the body handed over; where it handed none, the debug passes draw magenta, the "no data here" marker |
| `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the surface |
Both are first-class: `fragment()` is what you want when the shader owns its
own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }`
(and `roughness` / `metallic` / `ao` / `emissive`) answers about your material
for either body wherever the engine has the surface — writing the same
`PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives
one answer per channel. `pbr.shader` exposes `surface()`.
#### Handing the engine the surface a self-lit body draws
A `fragment()` body that lights itself by its own math (toon, cel, flat, PS1,
dithered) states the surface it draws with one call, always in scope in a
surface shader:
```wgsl
zero_publish_shaded_surface(albedo, normal, emissive, perceptual_roughness, metallic, occlusion);
```
| Argument | Type | What it states |
|---|---|---|
| `albedo` | `vec3<f32>` | the colour the surface reflects, linear, in [0, 1] |
| `normal` | `vec3<f32>` | the world-space normal the body shades with (normal map applied) |
| `emissive` | `vec3<f32>` | the light the surface gives off, linear |
| `perceptual_roughness` | `f32` | 0 a mirror, 1 fully rough |
| `metallic` | `f32` | 0 a dielectric, 1 a metal |
| `occlusion` | `f32` | the material's own ambient occlusion, 1 none |
The call changes nothing about the pixel the body returns; it states what that
pixel is a picture of. The last call before `fragment()` returns is the one
the engine reads, and it reads it into:
- **The debug passes**: `albedo`, `roughness`, `metallic`, `ao`, `emissive` and
`reflection` answer with the stated surface instead of magenta, and `normal`,
`shadow` and `shadow_depth` read the stated normal.
- **The G-buffer**, on the deferred render path: its normal (`@scene.normal`,
`zero_scene_normal`) carries the stated normal, and its material
(`@scene.material`, `zero_scene_material`) the stated albedo, metallic and
roughness. Every screen-space feature and full-frame pass that reads the
surfaces reads these, among them screen-space reflections, contact shadows,
capsule occlusion, area lights, the environment lighting and radiance cache
passes, surface weather, temporal antialiasing's surface restate, and a
post-process effect or render feature reading the surface helpers.
A `fragment()` body that hands over nothing leaves the G-buffer holding the
triangle's interpolated normal, a base colour equal to the colour it returned
brought into [0, 1] by its largest component, metallic 0 and roughness 1, so
a pass that reads roughness takes it for a fully rough dielectric.
The emissive argument reaches the `emissive` debug pass. The light a surface
gives off is already in the colour its body returns, so it adds nothing to the
frame; `@scene.emissive` holds the light a later pass stamps onto the surface.
A cel-shaded body, its surface handed over:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = zero_take_scene_decal(material.base_color.rgb);
let sun = normalize(-input.light_direction);
// The sun's N·L rounded to the nearest third: 0 on a face turned from the sun.
let band = round(max(dot(n, sun), 0.0) * 3.0) / 3.0;
let lit = input.light_color * input.light_intensity * band / ZPBR_PI
+ zero_pbr_surroundings_light(input, n, albedo);
zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0);
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
`capture { pass = "normal" }` is a geometry read rather than a material one, so
it answers for every shader: the normal of the surface where one was handed
over, and the interpolated normal of the triangle where none was. It is the same
normal the frame's normal buffer carries, which is what a screen-space pass
reading `@scene.normal` sees.
`shaderRef:shadingModel()` reports which one a shader ended up with —
`"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`.
#### Decals on a self-lit body
A decal projector stamps its colour over the opaque surfaces before anything
shades (`@scene.decal`). `zero_pbr_shade` lays it over the base colour it
lights, so a `surface()` material and a `fragment()` body lighting through
`zero_pbr_shade` show the decal lit and shadowed like the rest of the surface.
A body that lights itself takes the decal the same way by passing its base
colour through one call before its lighting:
```wgsl
let albedo = zero_take_scene_decal(material.base_color.rgb);
```
A body that takes none gets the decal laid over the colour it returned, unlit,
and over the albedo it published.
### Optional vertex hooks
```wgsl
// Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the
// already-skinned, morph-applied local position). Return the modified vertex.
// The `v` parameter is immutable (WGSL function params are), so copy it into a
// `var` first and modify that.
fn vertex(v: VertexData) -> VertexData {
var out = v;
out.position += out.normal * sin(out.time) * 0.1;
return out;
}
// Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two
// things you can do here, separately or together:
// * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering;
// * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its
// world_normal + the light context and the engine forwards the result into the
// interpolated `vertex_color` the fragment reads.
fn vertex_clip(v: ClipVertex) -> ClipVertex {
var out = v;
// Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading).
let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0);
let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l;
out.color = vec4<f32>(v.color.rgb * lit, v.color.a);
out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap
return out;
}
```
#### Geometry built per instance: grass, kelp, hair cards, debris
`vertex()` knows which vertex of which instance it places:
`VertexData.vertex_index` is the vertex's index in its mesh and
`VertexData.instance_id` the instance's slot, whose lanes
`zero_object_data(v.instance_id, lane)` reads. A hook can therefore build its
geometry rather than displace it: a strip mesh drawn thousands of times by
`renderer.mesh.drawInstanced`, each copy shaped, sized and bent from the lanes
of its `instanceDataBuffer`, becomes a field of grass blades, kelp fronds or
hair cards that sway with `v.time`. Being a surface shader, it is lit,
shadowed (it casts the shape the hook built), motion-vectored and fogged like
the rest of the scene. The rendering-instance-data guide
(`guides { path = "topics/rendering-instance-data" }`) has a worked blade
field; a render feature's raster pass (`types/rasterShader`) is the
hand-written alternative, a vertex and fragment program with its own pipeline.
#### Declaring how far a hook moves geometry: `vertexBoundsDilation`
Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges:
```yaml
properties:
- { name: sway, type: float, default: 0.5, min: 0, max: 4 }
# 0.4 x sway, at sway's largest value.
- { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 }
```
Each material sets its own value (a material that sways less can set less, one moved farther sets more), and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; no camera view culls its geometry, by frustum, screen size or occlusion, so every camera draws it wherever it stands.
### Structs the engine passes you
`FragmentData` (input to `fragment()`):
| Field | Type | Meaning |
|---|---|---|
| `world_position` | `vec3<f32>` | fragment world-space position |
| `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) |
| `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) |
| `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) |
| `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping |
| `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) |
| `view_position` | `vec3<f32>` | camera world position |
| `view_direction` | `vec3<f32>` | normalized world-space direction the camera sees this point from: toward the camera's position under a perspective projection, against its forward axis (the same for every point) under an orthographic one |
| `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down |
| `light_color` | `vec3<f32>` | sun colour |
| `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera |
| `ambient_color` | `vec3<f32>` | the colour of the scene's flat ambient term, one colour for every direction. The light of the reflection probes and the light-probe volumes along a normal, which a PBR surface takes as well, is `zero_pbr_surroundings_light`; a sky light adds the sky's light to the surface the G-buffer holds on the deferred path, and `zero_pbr_surroundings_light` holds it on the forward path (see "Engine state") |
| `ambient_intensity` | `f32` | the flat ambient term's intensity as it reaches this pixel: the scene's ambient occlusion is already in it (times `ambient_visibility`), so a crease darkens under the ambient with no work in the shader |
| `ambient_visibility` | `f32` | the share of the light of its surroundings that reaches this pixel: 1 minus the scene's ambient occlusion here, 1 where nothing occludes it. Multiply it into any light of the surroundings you gather yourself (a sky colour, a reflection-probe or environment sample); `ambient_intensity` already carries it. `zero_scene_bent_normal(input.frag_coord.xy, n)` names the direction the open part of the hemisphere faces, `n` where no pass wrote one |
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither |
| `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows |
| `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name |
| `instance_id` | `u32` | per-instance: the instance's slot, the value `VertexData.instance_id` carries. `zero_normal_matrix(input.instance_id)` is the transform that turns an object-space normal into a world normal |
| `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes |
| `front_facing` | `bool` | true for front faces (double-sided shading) |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
`shader_data` is the per-instance channel, and it is what lets ONE material serve
many entities that differ in a value — a dissolve at its own progress per subject,
a hit flash at its own age, a fill level per instance. The alternative is a
material per entity, which is a separate pipeline binding and a separate row in
the material table for every one of them.
```wgsl
const DISSOLVE_LANE: u32 = 0u;
fn fragment(input: FragmentData) -> vec4<f32> {
let progress = input.shader_data[DISSOLVE_LANE].x;
...
}
```
```lua
-- one material on twenty entities, each at its own progress
renderer.instanceData.set(subject, 0, progress)
renderer.instanceData.clear(subject) -- back to zero lanes
```
The engine attaches no meaning to a lane: a shader and whatever writes it agree
what each one carries. Name the indices in the module that writes them.
`renderer.instanceData.laneCount()` is how many there are. The same lanes reach a
hardware-instanced population through `renderer.mesh.drawInstanced`'s
`instanceDataBuffer`, on slots no entity owns.
`VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph
applied; on a skinned mesh, where this frame's pose holds it), `rest_position`
(object-local, where the vertex stands at rest: before its morph targets and its
pose, the same place every frame, so a pattern or a placed image laid in it stays
on the skin however the skeleton moves it; on a mesh no skin poses, the position
as the mesh stores it; in a depth view, the position), `normal`, `uv`, `color`,
`time`, and which vertex of which instance it
is: `instance_id` (`u32`, the instance's slot — `zero_object_data(v.instance_id,
lane)` reads the lanes the fragment gets as `shader_data`) and `vertex_index`
(`u32`, the vertex's index in its mesh). Both hold the same values in the colour
pass, the depth views, every shadow page and the previous-frame evaluation, so
geometry a hook builds from them — a blade placed and bent by its instance's
lanes, a strip shaped by its vertex's index — lands in the same place in each.
The rendering-instance-data guide has a worked blade field.
`ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context:
`clip_position`, `world_position`, `world_normal`, `uv`, `view_position`,
`view_direction`, `light_direction`, `light_color`, `light_intensity`,
`ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of
the frame being evaluated), and where the vertex stands on its instance:
`local_position` (its position in the mesh, after `vertex()` and before the
instance's world transform), `object_origin` (the world position of the instance's
origin), `object_scale` (the world length of the instance's x, y and z axes) and
`object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) —
what a camera-facing card, a shard grown about its own base, or anything placed
per instance is built from. **Writable:** `clip_position` (snap /
jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the
engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's
own vertex colour passes through).
`vertex()` and `vertex_clip()` run in the vertex stage, which reads the frame
uniforms (`uniforms.*`, and the `ClipVertex` members built from them), the scene
buffer (`zero_object_data`, `zero_object_visuals`, the node transforms), the
material interface and a `read` buffer property. The point, spot and area lights
(`zero_point_light`, `zero_punctual_projection`), the shadow maps, the
environment and light probes, the feature textures, the scene depth, colour and
reflection copies and a `@group(2)` buffer the shader declares `read_write` are
visible to the fragment stage alone: read them in `fragment()` or `surface()`. A
shader whose vertex hook reaches one fails to compile, and the error names the
stage, the binding and the calls that reach it.
### Each hook runs twice: this frame and the one before it
A vertex hook decides where the surface IS, so it also decides where the surface
WAS. The engine runs every hook a shader declares a second time, over the same
vertex standing one frame back — the previous-frame position stream, with
`time` = the clock that frame was drawn at and (for `vertex_clip()`)
`view_proj` = the view-projection it was drawn with. The motion vector the
renderer publishes is taken between the two results, so a displacement that
moves with time reports the velocity of the displaced surface, and a
displacement that does not move reports the motion of the transform alone
because the identical offset appears on both evaluations and cancels.
What that asks of a hook:
- **Take the frame from the argument.** `v.time` is the clock of the evaluation
being run; `uniforms.time` is always this frame's. A displacement built on
`uniforms.time` is identical on both evaluations, so its motion vector cancels
to exactly zero. The same holds for `v.view_proj` against
`uniforms.view_proj`: a clip hook that rebuilds its position from world space
through `uniforms.view_proj` reprojects the previous frame with this frame's
camera, and reports no camera motion at all. The wind helpers come in both
shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)`
inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one.
- **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously
— a falling drop that restarts at the top, a looping offset — differences its
jump as velocity on whichever frame it wraps. Compute the wrap COUNT from
`uniforms.time` and the position within the cycle from `v.time`, and both
evaluations share the same cycle, so the surface reports the speed it fell at.
`@builtin::shaders.rain_material` and `snow_material` do exactly that.
The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and
camera-position context are this frame's on both evaluations, so a hook that
displaces along its normal reports the motion of the transform plus this frame's
displacement.
## Engine state — point lights & shadows
This is what the renderer binds for a **surface** shader. A post-process
shader reads none of it: its engine state is `PostEngineData` (see
"Post-process & screen shaders"), and a full-frame effect driven by the scene's
lights takes the render-feature route that section names.
The common lighting state — the sun (`input.light_direction` / `light_color` /
`light_intensity`), the scene's flat ambient term (`input.ambient_color` /
`ambient_intensity`), the camera (`input.view_position` / `view_direction`), and
`input.time` — is already on `FragmentData`, so most shaders never touch the raw
engine state. The flat ambient term is one colour for every direction; the
light the reflection probes and the baked light-probe volumes hand a surface
along its normal comes from `zero_pbr_surroundings_light(input, n, albedo)`
(`@builtin::shaderModules.pbr_shading`), which holds the flat term as well and is
the ambient light a PBR surface is lit by. The sky's light reaches a surface
through a sky light (`@builtin::systems.sky.skyLight`). On the deferred path it
adds that light to every lit pixel by the surface the G-buffer holds there: a
self-lit body's is the one it publishes (see "Handing the engine the surface a
self-lit body draws"), so a body that publishes its surface takes the sky's
light a PBR surface takes. On the forward path, and for every surface the
G-buffer pass does not draw (transparent, water), the sky light fills the
environment's sky slot and `zero_pbr_surroundings_light` holds its diffuse
light. The one thing not
on `FragmentData` is the punctual-light array (its length varies), which is always
in scope. A scene can hold up to 1024 lights, so a fragment walks the ones the
light grid lists where it stands, which hold every light that can reach it:
| Expression | Type | Meaning |
|---|---|---|
| `zero_lights_near(world_pos)` | `ZeroLightsNear` | the lights that can reach a fragment at `world_pos`; `.count` of them |
| `zero_light_near(near, k)` | `u32` | the index of the `k`th of them, for `zero_point_light` |
| `uniforms.point_light_count` | `u32` | number of lights the frame shades under, every one of them |
| `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) |
| `zero_punctual_projection(i)` | `PunctualProjection` | a spot or area light's projection: `view_proj`, the frustum its cookie and shadow are placed by, and `cookie_layer` |
`PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`,
`cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot).
Shadows come from `#include "@builtin::shaderModules.shadows"`:
- `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed.
- `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each.
- `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch.
- `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing.
## Writing your own shading
The engine forces no lighting model — `zero_pbr_shade` is just one option. You can
light a surface yourself from the state above. Here is a complete custom-lit
(Lambert diffuse) surface that takes the engine's lights and surroundings and
no PBR BRDF:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light; brings in the shadow functions
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = material.base_color.rgb;
// Directional (sun) light: Lambert N·L, attenuated by its shadow.
let sun = normalize(-input.light_direction); // surface -> sun
let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction);
var direct = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow;
// Point + spot lights: the ones that can reach this fragment.
let near = zero_lights_near(input.world_position);
for (var k = 0u; k < near.count; k = k + 1u) {
let pl = zero_point_light(zero_light_near(near, k));
let to_light = pl.position - input.world_position;
let dist = length(to_light);
let l = to_light / max(dist, 1e-4);
let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0);
direct += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten;
}
// A Lambert surface sends back albedo / π of the direct light on it,
// the diffuse lobe of the PBR model.
var lit = direct / ZPBR_PI;
// The light of the surroundings: the flat ambient, the reflection probes
// and the baked light-probe volumes, with the scene's ambient occlusion in
// it — the ambient light a PBR surface takes. It is irradiance already
// weighed for a diffuse surface, so it takes no π.
lit += zero_pbr_surroundings_light(input, n, albedo);
// The surface this pixel draws, for the debug passes and the G-buffer; a
// sky light adds the sky's light to the surface stated here.
zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0);
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
The example declares `base_color` in its `properties.yaml`:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
```
- **Unlit:** skip the lights and return your colour directly.
- **Toon / PS1 / custom:** start from the body above and band, quantize, or warp
it however you like. Keep the direct light over π and `zero_pbr_surroundings_light`
as the ambient term, and the surface stands at the brightness of the PBR
materials around it; the flat
ambient (`input.ambient_color * input.ambient_intensity`) alone leaves out the
reflection probes and the light-probe volumes.
- **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes")
instead of writing the BRDF by hand. It hands the engine the surface itself.
## Material properties — `properties.yaml`
A surface shader declares its material properties in a sibling `properties.yaml`.
The engine GENERATES the entire group(1) interface from it — the uniform struct
(`material.<name>`) plus a texture/sampler pair per declared texture. You write
no `@group`/`@binding` lines.
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: emissive, type: color, default: [0, 0, 0, 1] }
- { name: base_color_texture, type: texture, default: white }
- { name: normal_texture, type: texture, default: flat_normal }
```
| `type` | WGSL field type | Notes |
|---|---|---|
| `float` | `f32` | optional `min`/`max` for editor sliders |
| `float2`/`float3`/`float4` | `vec2/3/4<f32>` | |
| `color` | `vec4<f32>` | linear RGB colour and alpha, default is `[r,g,b,a]`; the shader reads it as written |
| `int` | `i32` | |
| `bool` | `u32` | |
| `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) |
A `color` holds linear RGB, the space lighting is computed in, the way `base_color` multiplies a colour texture's
linear sample. A colour picked from a picture or written as a hex code is sRGB, and written as it is it reads paler
and less saturated than picked: convert it first, `color.toLinear(assert(color.hex("#ff8800")))` (`{ r, g, b, a }`:
`#ff8800` is `{ r = 1, g = 0.246, b = 0, a = 1 }`), and write that.
In the shader you read scalars as `material.<name>` and sample textures as
`textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture
samples its default, so a shader can always sample — no presence flag needed.
`vertex()` reads the same material interface, so a height or deformation map
drives displacement from the slot it was bound to. A vertex stage has no implicit
derivatives, so sample it at an explicit mip there:
`textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`.
## Sky shaders
A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only**
`fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each
pixel — and declare tunables in `properties.yaml` exactly like a surface shader
(read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`).
The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface,
and reconstructs the world-space ray; there is no separate sky renderer — a sky
material runs through the same material pipeline, just on a fullscreen triangle.
A sky pipeline binds group(0) and the group(1) interface alone, so a sky that
reads a `buffer` property or any other `@group(2)` binding fails to compile, and
the error names the binding and the calls that reach it.
`SkyInput` (the only argument) carries:
| Field | Type | Meaning |
|---|---|---|
| `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel |
| `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` |
| `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) |
| `camera_pos` | `vec3<f32>` | world-space camera position |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `constants` | `SkyConstants` | what the shader's `sky_constants()` returned for this draw (zeros when it declares none) |
```wgsl
// @domain: sky
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up);
return vec4<f32>(col * material.exposure, 1.0);
}
```
Day/night comes from `sun_direction.y` (the directional light's elevation), so a
sky shader never needs a time-of-day uniform — orient the light and the sky
follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`,
`equirect_sky`) are all authored this way; author a custom sky material and point
a `Skybox` component at it.
`fragment()` runs once for every pixel of the view and every texel of each
environment-capture face. A value that holds for the whole draw (a colour mixed
from the material and the sun's elevation, a `cos` of an angular size, an
exponent derived from a property) goes in an optional
`fn sky_constants(in: SkyConstantsInput) -> SkyConstants`, which the generated
vertex stage evaluates once per draw. `fragment()` reads its result as
`in.constants`. `SkyConstantsInput` carries `sun_direction`, `camera_pos` and
`time` (the same values `SkyInput` holds), `sky_constants()` reads the material
as `material.<name>` like `fragment()`, and `SkyConstants` is eight `vec4<f32>`
slots, `v0` to `v7`, packed however the sky likes:
```wgsl
// @domain: sky
fn sky_constants(in: SkyConstantsInput) -> SkyConstants {
let day = clamp(in.sun_direction.y * 2.0, 0.0, 1.0);
var c: SkyConstants;
c.v0 = vec4<f32>(mix(vec3<f32>(0.02), material.zenith_color.rgb, day), day);
c.v1 = vec4<f32>(mix(vec3<f32>(0.01), material.horizon_color.rgb, day), 0.0);
return c;
}
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
return vec4<f32>(mix(in.constants.v1.rgb, in.constants.v0.rgb, up), 1.0);
}
```
A branch on an `in.constants` value is taken or skipped by every pixel of the
draw together, so a term that only contributes some of the time (stars at
night) costs nothing while it is off. The vertex stage has no implicit
derivatives, so a texture read in `sky_constants()` is `textureSampleLevel`.
## Post-process & screen shaders
`// @domain: post-process` and `// @domain: screen` shaders are authored exactly
like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>`
(post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables
in `properties.yaml` (read as `material.<name>`, textures via
`textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen
`vs_main`/`fs_main` and the group(1) material interface. **There are no
`uniforms.params[i]` slots** — that convention is retired; every input is a named
property.
A **post-process** shader's `properties.yaml` carries one further, top-level key
beside `properties:` — `space`, either `light` (the default) or `display`:
```yaml
space: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
`light` is the scene's linear radiance — what every surface, the sky and every
`afterLighting` feature write, unbounded above 1.0. `display` is the code values
the `__display__` pass leaves behind after applying exposure and its tone curve
— the 0-1 range a colourist's tool and a dithered or quantized effect expect.
`postprocess.add`'s `opts.space` overrides what the asset declares for one
registration. The chain converts at both ends of an effect that runs on a
segment in the other space, so a light-space vignette still darkens a frame
graded after `__display__`, and a lookup table built from a `.cube` export
always sees the code values it was authored against, wherever the chain
runs it.
`space` also decides which layer a registration that names none lands on: a
`light` shader grades `scene`, the segment holding the scene's own light, and a
`display` shader grades `display`, the picture after `__display__` and before
the UI lands on it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom",
"shader"))` thresholds highlights that still stand above 1.0, and a lookup
table registered the same way reads the code values it was built for and leaves
every screen in the colours it declares. `opts.layer` names one explicitly —
`"all"`, after the UI, is what an effect that must grade the interface says.
A post-process shader may also declare the post stage of the frame it runs in,
`stage:` — `optics` (the `scene` layer), `display` (the `display` layer) or
`ui` (the `all` layer); `renderer.post.stages()` lists every stage with the
colour space and resolution its picture is held in. A registration takes the
declared stage unless `opts.stage` or `opts.layer` names another seam, and a
stage the frame does not have, or one only render features run in, is refused
naming the stages there are:
```yaml
space: display
stage: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
A **post-process** shader's `properties.yaml` carries a further, optional
top-level key — `passes:`, the pass list the frame draws through, in order:
```yaml
space: light
passes:
- { name: bright, entry: bright, scale: 0.5, inputs: [scene] }
- { name: down1, entry: downsample, scale: 0.25, inputs: [bright] }
- { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] }
- { name: composite, entry: composite, inputs: [scene, up0] }
```
Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the
one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the
view a pass draws at; the LAST pass takes none, since it draws at the view's
size and writes the chain's output. `lines`, optional, is a frame height the
pass's size is measured against: a pass declaring `lines: 1080` draws at the
size it has in a 1080-line view of the same shape, `scale` times 1080 texels
tall and as wide as the view's shape makes it, so each of its texels spans
the same share of the view's height at every output resolution and a filter
measured in its texels covers the same share of the picture on a phone, a
monitor and a 4K screen. A pass that would draw larger than the view draws
at the view's own size. `maxLines`, optional, is the tallest view the pass's
size is measured against: a pass declaring `scale: 0.5, maxLines: 1080` draws
at half of a view 1080 lines tall or shorter, and at the size it has in a
1080-line view of the same shape on a taller one, 540 texels tall at 1440 and
at 2160 lines, so it costs a 4K screen no more texels than a 1080p one while a
smaller view draws it at its own half. A pass declares one of `lines` and
`maxLines`. `inputs` names what a pass reads —
`"scene"`, the chain's input for this effect, or the name of an EARLIER pass —
and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body;
every input, `inputs[0]` included, is also reachable by index through
`zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place
the two reads of `inputs[0]` disagree: in an effect whose declared space
differs from the segment it draws on, `zero_sample_scene` converts a `scene`
input into that space while `zero_pass_input(0, uv)` hands back the segment's
own, unconverted value. A shader declaring no `passes:` is one pass whose
entry is `fragment`, and its generated WGSL is byte-identical to what it is
without the key.
A pass that is not the last writes a scratch target the effect owns — in the
space the shader declared, at the size its `scale` and `lines` or `maxLines` give it —
allocated on the first draw and replaced whenever the size changes. `engine.params`, below,
carries the drawing pass's own index, the fraction of the view it draws at
(its `lines` or `maxLines` applied), and its first input's texel size, so one shader body serves every
level of a chain built this way.
The worked example is the bloom: `@builtin::shaders.post.bloom` declares
sixteen passes — a threshold pass, seven downsamples, seven tent upsamples and
a composite — out of four entries, since the seven downsamples share one and
the seven upsamples share another, each level reading the one below it through
`zero_pass_input`, telling itself apart by its own size (`engine.resolution`)
and its inputs' (`zero_pass_input_size`), and weighing itself by the share of
the frame's height its texel spans. Its own README
walks the declaration.
A declaration is refused at compile time — reported through `compileStatus()`,
`postprocess.add`'s second return value, or a live effect's
`status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does
not define; an input naming a later pass, or naming neither `scene` nor an
earlier pass; a `scale` outside `(0, 1]`; a `scale`, a `lines` or a `maxLines` declared
on the last pass; a negative or non-finite `lines` or `maxLines`; a pass declaring both
`lines` and `maxLines`;
a `buffer` property (group(2) carries the pass inputs); or a shader whose
group(0) plus declared texture slots plus widest pass's inputs ask for more
than the 16 FRAGMENT sampled textures one shader stage has.
A **post-process** shader runs as a full-screen pass over the already-rendered
frame. Its `fragment` argument and framework helpers:
`PostInput`:
| Field | Type | Meaning |
|---|---|---|
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) |
| `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right |
Framework helpers (always in scope — no include needed):
| Call | Returns | Meaning |
|---|---|---|
| `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) |
| `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" |
| `zero_linear_depth_through(d, engine.view_proj, zero_camera_position())` | `f32` | that sample as a distance in metres along the camera's view axis, read through the camera that drew it: its near and far planes and its kind of projection — the one inversion of the reversed range (`zero_linear_depth(d, near, far)` is the perspective inversion given the planes themselves) |
| `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` |
| `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads |
| `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain |
| `zero_view_size()` | `vec2<f32>` | the size in pixels of the view the pass draws for: the frame the chain delivers, whatever fraction of it the pass draws at. A filter measured against it (a fraction of the frame's height) holds one look at every output resolution |
| `zero_camera_position()` | `vec3<f32>` | the world position of the camera the render being drawn looks from — the camera `engine.view_proj` belongs to, so on a capture or a render-to-texture camera it is that camera's. With a world position reconstructed from `zero_scene_depth(uv)` and `engine.inv_view_proj`, `normalize(world - zero_camera_position())` is the view ray |
| `zero_scene_surfaces_drawn()` | `bool` | whether the scene's surface channels (the helpers below) hold the surfaces of the render being drawn: true on the deferred path from `afterOpaque` on, false on the forward path, which draws no G-buffer |
| `zero_scene_normal(uv)` | `vec3<f32>` | the world-space normal of the surface at `uv` (`@scene.normal`), unit length; +Z where no surface stands, (0, 0, 0) where `zero_scene_surfaces_drawn()` is false |
| `zero_scene_surface_flags(uv)` | `u32` | the surface flags the geometry pass wrote at `uv` (`@builtin::shaderModules.surface_flags`' `ZERO_SURFACE_FLAG_*`, in scope with the helper); 0 where `zero_scene_surfaces_drawn()` is false |
| `zero_scene_material(uv)` | `ZeroGbufferMaterial` | what the surface at `uv` IS (`@scene.material`): `.base_color`, `.metallic`, `.perceptual_roughness`, each in [0, 1], unpacked by `@builtin::shaderModules.gbuffer_material`, which the surface group includes |
| `zero_scene_shaded(uv)` | `vec4<f32>` | what the surface at `uv` SENT (`@scene.shaded`): its shaded colour, linear, with its coverage in alpha |
| `zero_scene_emissive(uv)` | `vec4<f32>` | the radiance passes stamped on the surface at `uv` (`@scene.emissive`) |
| `zero_display_exposure()` | `f32` | the exposure in force: the gain `__display__` multiplies the scene's light by before its curve, the value this frame's display pass draws with (1 where the chain carries none). Light times it is light in the units the picture shows it at, so a threshold judged against `light * zero_display_exposure()` picks the same highlights at every exposure |
| `zero_middle_grey()` | `f32` | for an effect in light: the light `zero_sample_scene` reads that the picture shows as middle grey, 0.18 over the exposure in force on a segment holding the scene's light and 0.18 on a segment `__display__` already drew. What a grade pivots its contrast on, so middle grey holds where the picture shows it at every exposure |
| `zero_picture_white()` | `f32` | for an effect in light: the light the picture's white stands at, the peak a grade holds. 1 (the white an SDR picture peaks at) on a segment `__display__` already drew, and 0 on a segment holding the scene's light, which has no peak |
Engine data uniform `engine` (a `PostEngineData`):
| Field | Type | Meaning |
|---|---|---|
| `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height |
| `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index |
| `view_proj` | `mat4x4<f32>` | this frame's view-projection |
| `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) |
| `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) |
| `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. |
| `exposure` | `vec4<f32>` | `x`=the exposure in force (what `zero_display_exposure()` reads) |
| `camera_position` | `vec4<f32>` | `xyz`=the world position of the camera being drawn (what `zero_camera_position()` reads) |
| `surfaces` | `vec4<f32>` | `x`=1 where the surface helpers read the render's own surfaces (what `zero_scene_surfaces_drawn()` reads) |
| `view` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height of the view the pass draws for (what `zero_view_size()` reads); the same as `resolution` on a pass drawn at the view's size |
The engine fills all of it **per render target**. A registered effect runs over
the live viewport's frame AND over every offscreen one — a `capture` from a
world-space station or orbiting an entity, a capture of a named camera, a
render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj`
and `inv_view_proj` are the camera THAT render was drawn from, while
`resolution` is that target's own pixel size. So a pass reconstructing world
space from `zero_scene_depth(uv)` reconstructs against the station and lens the
capture asked for, and an offscreen frame is a picture of the effect as it
stands at that station. (A render feature's passes reach an offscreen render the
same way, against the same camera — the `renderFeature` assetType README carries
that half, including `@frame.camera`, its own per-target camera input.)
**The scene's surfaces.** The surface helpers above read the deferred path's
G-buffer, the same channels a render feature names as `@scene.normal`,
`@scene.material`, `@scene.shaded` and `@scene.emissive`, by screen uv at the
exact texel (the channels are at the scene's raster size, so a pass at a
`scale`, or after an upscale, reads the surface that stands at that point of
the picture). A shader that names any of them compiles with the surface group,
`group(3)`, which spends four of the stage's sampled textures beside its own
slots and pass inputs; the render keeps a channel only while a running effect,
or a render-feature pass's shader, reads it; a channel counts as read when an
entry point of the compiled shader reaches its helper, so a helper in an
included function nothing calls reads nothing. They hold this frame's surfaces
at every layer of the chain and at every render-feature phase from
`afterOpaque` on. With temporal antialiasing running, every layer of the chain
reads the normal and the material restated at each pixel's centre, with no
sub-pixel offset, so an outline found in the normals holds still under a still
camera; `zero_scene_shaded` and
`zero_scene_emissive` read the raster's own, with its sub-pixel offset. The
renderFeature type README states the whole contract by stage and path.
The forward path draws no G-buffer, so there every helper reads zero and
`zero_scene_surfaces_drawn()` false: a look that needs the surfaces draws a
picture of its own there (from depth, say) instead of reading a wrong one, and
`postprocess.status()` names the channels the effect `reads` and, after a frame
it drew with the substitute, the `substituteReason`.
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let c = zero_sample_scene(in.uv);
if !zero_scene_surfaces_drawn() || zero_scene_depth(in.uv) <= 0.0 { return c; }
let n = zero_scene_normal(in.uv);
let m = zero_scene_material(in.uv);
let rim = pow(1.0 - abs(n.y), 4.0);
return vec4<f32>(mix(c.rgb, m.base_color, rim * material.amount), c.a);
}
```
**Lights.** A post-process shader reads no light data: `uniforms`,
`zero_point_light(i)` and the light grid are the surface framework's, and a
post shader naming them does not compile. An effect driven by the scene's
lights (light shafts, a glow around each lamp, a scatter through fog) is a
render feature pass at a scene phase (`afterDepthPrepass` through
`afterLighting`) that binds `@scene.lights`, the punctual-light buffer (the
renderFeature type README states its layout), with `@frame.camera` for the
camera; the beams lights throw through the air are already the built-in
`VolumetricLighting` component, whose `lightScattering` render feature
(`@builtin::systems.volumetrics`) marches the view rays through the scene's own
lights.
An offscreen render keeps no view history of its own, so `prev_view_proj` there
holds that same matrix rather than the frame before it, and a pass taking camera
motion from the two reads none. On the viewport the pair is a frame apart, so
camera motion is the one reading a capture answers differently from the screen.
`postProcessing = false` on a capture is the one control that takes the chain
off the frame it returns; it names the camera property the ephemeral capture
camera is built with, so it scopes to that one capture. What a capture opts out
of is the registered effects; `__display__` still runs on it, so the exposure
and tone curve that turn the scene's light into a picture are on what a capture
returns.
A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses
`__display__` itself, since a channel like that is a reading of the scene
rather than a graded picture of it. The environment-cube capture bypasses it
too, and for the same reason: a probe face carries radiance into the cube
array, and `__display__` would fit that radiance to a display's code values —
a picture of it rather than the value the PBR indirect term multiplies into
its lighting.
A complete post-process effect — a vignette via `fragment()` + `properties.yaml`:
`properties.yaml`:
```yaml
properties:
- { name: intensity, type: float, default: 0.5, min: 0, max: 1 }
- { name: radius, type: float, default: 0.75, min: 0, max: 1 }
- { name: softness, type: float, default: 0.45, min: 0, max: 1 }
```
`shader.wgsl`:
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let color = zero_sample_scene(in.uv);
let intensity = max(material.intensity, 0.01);
let radius = max(material.radius, 0.01);
let softness = max(material.softness, 0.01);
let center = in.uv - vec2<f32>(0.5);
let dist = length(center);
let vignette = smoothstep(radius, radius - softness, dist);
let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity);
return vec4<f32>(darkened, color.a);
}
```
The asset above **defines** the effect. It enters the frame when something
registers it:
```luau
postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 })
```
The registration names no layer, so the effect grades the layer its `space`
belongs to: this vignette reads light, so it runs on `scene`, over the picture
before the UI reaches it. Registering it is the one step that makes it render,
so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards
recompiles every effect registered from it, in place — the pass keeps its enabled
state, priority, layer, tuned property values and bound textures, and draws the
new pixels on the next frame. `postprocess.remove(name)` takes it back out of the
chain and leaves the asset alone.
Drive the named properties at runtime with `postprocess.setProperty(name, prop,
value)` and bind texture properties with `postprocess.setTexture(name, prop, path)`
(both keyed by the **property name**, never a slot index — see the post-process
section of `man shaders` / the `postprocess.*` API).
Read them back with `postprocess.describe(name)`: it carries the chain state
`postprocess.status()` lists for that effect, the `properties` schema it was
registered with, and the `values` each of those properties currently holds. Before
the effect exists, `shaderRef:getProperties()` on the asset names the same schema,
so what a pass takes is answerable either side of the registration.
A **screen** shader is a standalone full-screen visual (UI background, procedural
pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene
to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a
`ScreenEngineData`:
| Field | Type | Meaning |
|---|---|---|
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `scroll` | `f32` | UI scroll offset |
| `resolution` | `vec2<f32>` | render-target size in pixels |
| `mouse` | `vec2<f32>` | mouse position |
| `velocity` | `f32` | scroll velocity |
```wgsl
// @domain: screen
fn fragment(in: ScreenInput) -> vec4<f32> {
let t = engine.time * 0.5;
let col = vec3<f32>(
sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5,
sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5,
material.brightness
);
return vec4<f32>(col, 1.0);
}
```
## Library includes
A library module is a **`.shaderModule` asset**: it only EXPOSES functions and
structs and does nothing on its own (exactly like a Unity `.cginc`). You must
call what you include. Include one by its identity, the same string you would
hand `asset.resolve`:
| Include | Exposes |
|---|---|
| `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting); `zero_pbr_indirect_visibility(FragmentData, PbrSurface) -> ZpbrIndirectVisibility` (the share of the surroundings' light each indirect lobe takes from the scene's ambient occlusion: `diffuse` with the light a crease bounces back, `specular` from the open cone around the bent normal, and `specular_traced`, the material's own occlusion alone, for the part of the reflection a screen-space trace found); `zero_pbr_shade_with_visibility(FragmentData, PbrSurface, ZpbrIndirectVisibility) -> vec3<f32>` (the same lighting with that share stated by the caller); `zero_pbr_surroundings_light(FragmentData, n, albedo) -> vec3<f32>` (the diffuse light the surroundings hand the surface along `n` as `zero_pbr_shade`'s diffuse lobe takes it — lightmap, flat ambient, reflection probes, light-probe volumes, the sky light's diffuse light where the G-buffer pass does not draw the surface, the scene's occlusion — for a self-lit body to multiply by its colour); `zero_pbr_sun_visibility(FragmentData, PbrSurface) -> vec4<f32>` (the sun as it reaches the surface: rgb what translucent casters and a medium leave of it, a the share its shadow maps leave, zero where it puts no light on the surface), which a surface scales on its own terms and hands back in `PbrSurface.sun_visibility` |
| `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)`; each light's `_with_kernel` form takes a shared `ZShadowKernel` (`zshadow_kernel()`) so several lookups of one fragment derive its filter rotation once |
| `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access |
| `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions |
| `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) |
| `@builtin::shaderModules.periodic_noise` | Value noise that repeats along x, for a pattern laid around a circle (a sky over the azimuth, a ring): `zero_azimuth(dir)` (the azimuth about +Y as a fraction of a turn, wrapping along -X), `zero_periodic_noise(p, period)`, `zero_periodic_fbm(p, period, octaves, lacunarity)` (each octave fits a whole number of cells in `period`, so the sum repeats every `period` and a pattern whose x runs over one period per turn closes with no seam), `zero_wrap_cell(cell, period)` and `zero_hash21(p)` for a lattice of one's own |
| `@builtin::shaderModules.parallax` | Parallax occlusion for any lit shader with a height map: `zero_parallax(depth, max_steps) -> ZeroParallax` (the relief's depth in UV units, its steps, its fade distances and whether R is height or depth); `zero_parallax_march(FragmentData, height_texture, height_sampler, uv, ZeroParallax) -> ZeroParallaxHit` (the UV to read every map at, with `ddx`/`ddy` for `textureSampleGrad`); `zero_parallax_sun_visibility(FragmentData, PbrSurface, height_texture, height_sampler, hit, ZeroParallax) -> vec4<f32>` (the sun with the relief's self-shadow, for `PbrSurface.sun_visibility`, marched only where the sun lights); `zero_parallax_self_shadow(...)`