# DeprecatedParticleEmitter (deprecated)
> **Deprecated.** This belongs to the earlier particle substrate. It stays loadable by identity and guid for content that already uses it; nothing new should use it, and search does not offer it. Particles are procgen sim nodes (`sim.spawn`, `sim.particles`, `sim.shader`) played through an effect: use `@builtin::assetTypes.effect`.
The component drives an emitter of the `engine` module from fields the entity carries. Its identity is `@builtin::deprecated.deprecatedParticles.DeprecatedParticleEmitter`; the other emitter component of the package is `@builtin::deprecated.deprecatedParticles.DeprecatedSimpleParticleEmitter`.
# DeprecatedSimpleParticleEmitter (deprecated)
> **Deprecated.** This belongs to the earlier particle substrate. It stays loadable by identity and guid for content that already uses it; nothing new should use it, and search does not offer it. Particles are procgen sim nodes (`sim.spawn`, `sim.particles`, `sim.shader`) played through an effect: use `@builtin::assetTypes.effect`.
Roblox-shaped declarative particle system. Sits on top of `NumberRange`,
`NumberSequence`, and `ColorSequence` to describe an emitter's emission
cadence, per-particle motion, and per-particle visuals as data — no
imperative per-frame code on the user side.
The simulation and rendering run on the GPU: a compute pass integrates
every particle each frame and the whole system draws from one instanced
pass. A single emitter carries thousands of live particles at a fixed
per-frame CPU cost. The component is a thin adapter over the particles
engine module (`@builtin::deprecated.deprecatedParticles.engine`).
## Construct
The engine registers two builtin components under the leaf name
`ParticleEmitter`, each with its own field vocabulary: this one, and
`@builtin::deprecated.deprecatedParticles.DeprecatedParticleEmitter`. Address this one by its full
identity, `@builtin::deprecated.deprecatedParticles.DeprecatedSimpleParticleEmitter` — the fields below are the
ones it declares.
```luau
local em = entity.spawn("flame")
em.localPosition = { 0, 1, 0 }
em.component.add("@builtin::deprecated.deprecatedParticles.DeprecatedSimpleParticleEmitter", {
rate = 50,
lifetime = NumberRange.new(1.0, 1.5),
speed = NumberRange.new(2.0, 3.0),
acceleration = { 0, 5, 0 },
color = ColorSequence.new({
{ time = 0, value = { 1, 0.9, 0.3 } },
{ time = 1, value = { 0.6, 0.1, 0 } },
}),
size = NumberSequence.new(0.4, 0.05),
transparency = NumberSequence.new(0, 1),
depthFade = 1.5,
})
```
`depthFade` is the distance, in world units, over which a particle dissolves
into the surface drawn behind it, so a plume meeting a floor settles onto it
instead of cutting a straight line along it. The default is 0, which is off.
The particles engine module's README has the whole surface.
`castsShadows` states whether these particles block light — a caster is drawn
into the shadow map as the geometry it is, so debris and rubble declare it while
smoke and dust leave it alone. The default is false. `renderLayer` names the
render layers the particles draw on, as a layer name or a space-separated
string, so a camera or a capture can take the scene with the effect in it or
without; the default is `"default"`.
## Instance methods
```luau
local em = entity.find("flame").component.get("@builtin::deprecated.deprecatedParticles.DeprecatedSimpleParticleEmitter")
em:emit(50) -- burst spawn 50, independent of rate / emitting
em:clear() -- clear every live particle right now
em.emitting = false -- stop new emission; live particles complete
```
## Permissive input shapes
The component accepts either the strict constructed handle or the
common shorthand for each sequence/range field:
| Field | Strict | Shorthand accepted |
|------------------|-------------------------------------|-----------------------------------------------------|
| `lifetime`, `speed`, `rotation`, `rotSpeed` | `NumberRange.new(min, max)` | scalar, `{min, max}`, `{min=, max=}` |
| `size`, `transparency`, `squash` | `NumberSequence.new(...)` | scalar, `{a, b}`, `{{time, value, envelope?}, ...}` |
| `color` | `ColorSequence.new(...)` | `{r, g, b}`, `{r, g, b, a}`, keypoint array |
| `acceleration`, `emitterSize`, `spreadAngle`| Vector record / array | same |
## Emitter shape
`shape` selects where particles spawn and which way each one starts
moving. It takes one of six names, in any letter case: `Point`, `Box`,
`Sphere`, `Cylinder`, `Disc` or `Cone`. Any other name is refused when
the emitter starts, with the six in the message. `Box`, `Sphere`,
`Cylinder` and `Disc` are centred on the emitter, and `emitterSize` gives
their extent along each axis; the table states where `Point` and `Cone`
sit.
| `shape` | Where particles spawn | Starting direction | `shapeStyle` | `shapePartial` |
|------------|--------------------------------------------------------------------------|--------------------------------------------|---------------------------------------|-----------------------------------------------------------------------------------------|
| `Point` | The emitter's origin | Straight up (+Y) | Unused | Unused |
| `Box` | A box `emitterSize` across | `Volume`: away from the centre. `Surface`: out of the face it spawned on | `Volume` fills it, `Surface` spawns on its faces | Unused |
| `Sphere` | An ellipsoid whose diameters are `emitterSize` | Away from the centre | `Volume` fills it, `Surface` its shell | Above 0 keeps the upper half, flattened toward the equator; at 1 only the equator ring |
| `Cylinder` | An upright cylinder, `emitterSize.y` tall, diameters `emitterSize.x` / `.z` | Out from the axis, level | `Volume` fills it, `Surface` its side wall | Shortens the band particles spawn in about the centre, to half the height at 1 |
| `Disc` | A flat ellipse in the XZ plane, diameters `emitterSize.x` / `.z` | Out from the centre, level | `Volume` fills the ring between the inner radius and the rim, `Surface` spawns half on the rim and half on the inner edge | The inner radius as a fraction of the outer; at 0 the inner edge is the centre |
| `Cone` | The base of a cone whose apex is the emitter's origin and whose axis is +Y, `emitterSize.y` above the apex | Along the line from the apex | Unused | The half-angle as a fraction of 90 degrees; 0 is a single line straight up |
`shapeInOut` sets the starting direction against the table's: `Outward`
keeps it, `Inward` reverses it, and `InAndOut` picks one of the two for
each particle. `spreadAngle` then tilts each direction by up to its larger
component, in degrees, so every particle leaves within that angle of the
direction the table gives it.
`emissionDirection` names the side of the emitter the shape's +Y faces, and
turns the whole shape there: where particles spawn and the directions they
leave in. It takes one of six names: `Top` (+Y, the default, which is the
table as written), `Bottom` (-Y), `Right` (+X), `Left` (-X), `Front` (-Z, the
way an entity faces) or `Back` (+Z). Any other name is refused with the six
in the message: a write to a running emitter keeps the side it had, and an
emitter added with one does not start. The turn is the shortest one from +Y,
so a `Point` emitter set to `Bottom` sprays straight down, a `Cone` set to
`Front` opens along -Z, and a `Disc` set to `Right` stands upright in the YZ
plane with `emitterSize.z` still along Z. The sides are the world's axes:
the emitter follows its entity's position, not its rotation.
```luau
local flame = entity.spawn("flame")
flame.component.add("@builtin::deprecated.deprecatedParticles.DeprecatedSimpleParticleEmitter", {
shape = "Cone",
emitterSize = { 0.6, 1.2, 0.6 },
shapePartial = 0.4,
rate = 40,
})
```
The emitter tracks its owning entity's world position each frame, so
parenting it to a moving part sweeps the emission origin along with the
part.
## Demo
The campfire showcase — a warm flame emitter + slow gray smoke emitter
on a log, lit by a warm point light — lives on ZeroMind as the public
world "Campfire" (3d69d10d-5388-4bee-88f4-b48eb85ae222).
·computeshader · born here
❒asset # curl_noise_update
Advects particles along a curl-noise field, so they swirl instead of falling
straight. A drop-in replacement for the default particle update: same bindings,
same state layout.
Pass it to a particle system as its update shader:
```luau
particles.create { updateShader = asset.resolve("~.demo.curl_noise_update", "computeShader") }
```
## Bindings
| name | kind |
|------|------|
| `particles` | `buffer` (read_write, f32) |
| `vertices` | `buffer` (read_write, u32) |
| `params` | `buffer` (read_write, f32) |
# deprecatedParticles Module (deprecated)
> **Deprecated.** This belongs to the earlier particle substrate. It stays loadable by identity and guid for content that already uses it; nothing new should use it, and search does not offer it. Particles are procgen sim nodes (`sim.spawn`, `sim.particles`, `sim.shader`) played through an effect: use `@builtin::assetTypes.effect`.
The Luau surface for particle emitters of the earlier substrate, required as
`local particles = require("@builtin::deprecated.deprecatedParticles.deprecatedParticles")`. It creates emitters, enumerates the live ones, and answers what
each is simulating and drawing right now.
## Reading what an emitter is doing
`particles.observe()` answers "what are this engine's emitters producing, and
why is one producing nothing" in a single read. Every number in it comes from
the engine's own state — the lifetimes the spawns wrote, the simulated time the
dispatches advanced, the entity that draws the emitter — rather than from a
value content set.
- `particles.observe() -> ParticleObservation` — every live emitter plus the
totals: `{ emitters, count, alive, spawned, capacity, silent, bytes, takenAt }`.
- `particles.observe(sys) -> ParticleReading` — one emitter's document.
- `particles.list() -> { ParticleSystem }` — the live emitters, from the
emitter registry rather than by walking entities.
- `particles.whySilent(sys) -> reason?, detail?` — the reason and its detail
line, or nil when the emitter is producing.
- `particles.silenceReasons() -> { { reason, means } }` — the closed set, in
resolution order.
## The three counts, and what each one means
| Field | What it counts |
|---|---|
| `alive` | particles live right now — slots whose lifetime has not elapsed under `simulatedTime` |
| `spawned` | slots emission has filled since the last `clear()`, saturating at `capacity` |
| `drawn` | slots the renderer is submitting geometry for |
`alive` falls to 0 when the last particle ages out. `spawned` does not — it is
the emission schedule's own total, which is what a burst timeline is asserted
against.
`drawn` counts what the renderer was actually told to submit, which is a
different number on each of the two draw paths. A sprite emitter draws through
one renderable registered over every slot it can ever fill — a slot holding a
dead particle is written as a degenerate quad the rasterizer drops — so `drawn`
is its `capacity` however few particles are in it. A mesh emitter draws one
instance per filled slot, so `drawn` follows `spawned`. Either way a renderable
that has been despawned or switched off submits nothing, and `drawn` is 0.
`sys:getActiveCount()`, `sys:getSpawnedCount()` and `sys:getSimulatedTime()`
are the same three numbers on the emitter handle.
`aliveBound` says which kind of number `alive` is. A particle ends when its
lifetime elapses, and the emitter knows both the lifetime each slot was given
and the simulated time its dispatches have advanced, so `alive` is `"exact"`.
The one response that ends a particle any other way is a collision response of
`kill`: it ends it where it touches a collider, ahead of the lifetime the slot
carries, and only the device sees that. An emitter carrying `kill` colliders
reads `aliveBound = "upperBound"`, and `confirmation.alive` is the count that
includes those deaths.
The death clock costs 4 bytes of CPU memory per slot — 20 KB at a capacity of
5 000, 4 MB at a million — beside the 64 bytes per slot the state buffer holds
on the device.
## What a reading costs
Simulating costs the same whether or not anything observes: an emitter's
`update` measures 0.033 ms at a capacity of 5 000 and 0.033 ms at 100 000, the
same as before there was anything to read. The population is counted by the
caller that asks for it, once per simulated instant — 0.20 ms over 5 000 filled
slots and 4.0 ms over 100 000, and nothing at all for an emitter that has
spawned nothing or whose last scheduled death is behind its clock. Reading a
large emitter every frame is the one case that adds up; `confirmation.alive`
answers the same question off the device for the cost of a dispatch.
## Confirming the population against the GPU
`alive` is derived from what the emitter wrote into the state buffer and what
its dispatches advanced. `reading.confirmation` is the other end of the same
question: a census pass counts the live slots on the device and reads the
counter back.
The pass rides on the emitter's dispatches, so the first reading of an emitter
carries `state = "pending"` and a later one carries the count — every state
carries a `means` line saying which of the two it is and what to do about it.
```
confirmation = {
state = "confirmed" | "pending" | "unavailable",
means = "…", -- what this state is, on every reading
alive = 128, -- what the device counted
stepped = 128, -- how many of those a dispatch had already aged
simTime = 2.5, -- the simulated time the census was taken at
derived = 128, -- what `alive` read at that same instant
agedBy = 0.033, -- how far the clock has moved since
matchesReading = true,
}
```
Reading an emitter arms the next census, and the answer arrives a few frames
later — `state = "pending"` until then, and until the emitter's first dispatch
runs, since the pass rides on it. `derived` is the reading taken at the very
instant the pass was queued, which is what makes `matchesReading` a comparison
of the same moment rather than of two different ones. `stepped` below `alive`
is a state buffer the emitter has filled and the simulation has not run over.
## Why an emitter is producing nothing
`reading.reason` resolves to exactly one entry of `silenceReasons()`, nearest
cause first, and `reading.detail` names what that reason is about:
| Reason | Means |
|---|---|
| `destroyed` | the emitter released its buffers and its renderable |
| `renderableMissing` | the thing that draws this emitter is gone |
| `renderableInactive` | the renderable exists and its hierarchy is inactive |
| `materialMissing` | what draws this emitter has nothing to shade with |
| `simulationNeverStepped` | no dispatch has run for this emitter yet |
| `simulationNotStepping` | the last step is older than the stall window |
| `disabled` | emission is switched off |
| `awaitingDelay` | the timeline has not reached the start of emission |
| `durationElapsed` | a one-shot timeline ran past its duration |
| `lifetimeZero` | a particle's lifetime is zero, so it dies where it spawns |
| `rateZero` | nothing is scheduled to spawn — no rate and no bursts |
| `allExpired` | every particle the emitter spawned has aged out |
The render-side reasons resolve whether or not particles are alive: an emitter
simulating a full buffer into a renderable that has been despawned reads
`renderableMissing`, and a sprite emitter whose quads never got a material to
shade with reads `materialMissing` — which is what separates each of them from
a healthy emitter carrying the same counts.
`materialBound` says whether the material named in `material` is the one on
what draws the emitter, and `materialFault` carries the error from the last
bind that failed. An emitter that bound a material and then named one that does
not resolve keeps drawing under the material it had, so it reads
`materialBound = false` while it is still producing. A mesh emitter registers
its population under the renderer's error shader when the name reaches no
material, which puts magenta on the screen rather than nothing: it reads
`materialBound = false` with the resolve error in `materialFault`, and stays
`silent = false`.
A bind puts the named material on the thing that draws the emitter. Whether the
renderer then built a pipeline for the program that material names is the
renderer's own record, and `shading` carries it: `shading.state` reads
`itsMaterial` where the program the material names is what reached the screen,
`errorMaterial` where the renderer bound the magenta placeholder in its place —
with `shading.reason` from the closed set `renderer.drawDiagnostics()` names,
the compiler's message in `shading.detail`, the program the material asked for
in `shading.program` and the whole reading in one sentence in `shading.means`.
So an emitter whose shader compiles and whose pipeline the renderer refuses
reads `materialBound = true` beside `shading.state = "errorMaterial"`, which is
what tells it apart from a healthy emitter carrying the same counts. Reading
arms the renderer's per-draw recording, so the first reading after boot can
carry `shading.state = "pending"` and a later one carries the answer; a shader
that compiles on a later edit puts the emitter back on `itsMaterial`.
A mesh emitter draws as a population registered against its material rather
than through a render entity, so its reading is the renderer's word about that
material. Preparing a material is what builds the pipeline its draws are looked
up by, so a program the renderer refuses leaves the key with no prepared
material at all and `shading.state` reads `nothingBound` with
`shading.reason = "materialNotPrepared"` beside the program the material names.
`renderer.shadingOf(subject)` is the same reading for any entity or material.
The reasons cover the population, the timeline driving it, and whether the thing
that draws the emitter is there, switched on and carrying its material;
`shading` covers what the renderer made of the draw. What a camera then makes of
it is `renderer.drawStats()` and a capture.
## What an emitter costs
`reading.bytes` breaks the emitter's GPU footprint down by the buffer holding
it — `state`, `params`, and then `vertices` / `prevVertices` / `indices` for a
sprite emitter or `transforms` / `instanceData` for a mesh one — plus `total`.
Each emitter allocates its own buffers, so the total is attributable to that
emitter.
# `modules.particles` — Generic GPU-driven Particle System (deprecated)
> **Deprecated.** This belongs to the earlier particle substrate. It stays loadable by identity and guid for content that already uses it; nothing new should use it, and search does not offer it. Particles are procgen sim nodes (`sim.spawn`, `sim.particles`, `sim.shader`) played through an effect: use `@builtin::assetTypes.effect`.
A generic, GPU-driven particle substrate for VFX. Every active particle lives
in a GPU storage buffer; physics runs entirely as a compute dispatch each
frame; per-frame vertex output feeds the renderer directly via
`renderer.mesh.create` — no CPU readback, no re-upload. Spawning happens on
the CPU (cost bounded by the emission **rate**, not the active particle
**count**) and writes new particle slots directly into the GPU state buffer.
It is the substrate behind the `ParticleEmitter` component but works equally
well as a script-side API for hand-rolled effects, custom WGSL update
shaders, and per-particle scripted state.
## Quick start
```lua
local particles = require("@builtin::deprecated.deprecatedParticles.engine")
local NumberSequence = particles.NumberSequence
local ColorSequence = particles.ColorSequence
local fire = particles.create({
maxCount = 2000,
rate = 120, -- particles/sec
lifetime = { 0.8, 1.6 },
speed = { 1.5, 3.0 },
shape = { kind = "cone", size = {0.6, 1.2, 0.6}, partial = 0.4 },
gravity = { 0, 1.5, 0 }, -- buoyant
drag = 0.4,
size = NumberSequence.new({
{ time = 0, value = 0.25 },
{ time = 0.3, value = 0.7, envelope = 0.15 },
{ time = 1, value = 0.0 },
}),
color = ColorSequence.new({1, 0.9, 0.3}, {1, 0.2, 0.05}),
transparency = NumberSequence.new(0, 1),
blendMode = "additive",
brightness = 2.0,
})
-- Each frame, in your update tick:
fire:setOrigin(torch.position.x, torch.position.y, torch.position.z)
fire:update(dt)
```
For a declarative wrapper that lives on an entity, use the
`DeprecatedSimpleParticleEmitter` component (`deprecated/deprecatedParticles.package/DeprecatedSimpleParticleEmitter.component`).
## Why GPU-driven
| | CPU per-particle | GPU per-particle |
|---|---|---|
| 1 000 particles | OK | OK |
| 10 000 particles | starts skipping frames | trivial |
| 100 000 particles | impractical | trivial |
| 1 000 000 particles | impossible | feasible on mid-tier GPU |
| Custom physics | per-particle Lua call | one WGSL update shader |
| Trail / mesh particles | extra CPU work | extra WGSL pass |
The substrate also leapfrogs Roblox-class engines on the long list of
features they can't offer in their CPU-only model: mesh particles, particle
↔ world collision, neighbour queries, custom force fields, curl noise.
## Architecture
### Storage buffers, per system
Every system holds its particle state and its params. What it holds beyond that
depends on how it draws.
| Buffer | Size | Written by | Read by |
|---|---|---|---|
| `<id>_state` | `maxCount * 64 B` | CPU spawn, GPU update | GPU update |
| `<id>_params` | 1556 floats (~6 KB) | CPU each frame + on change | GPU update |
A **sprite** emitter builds a quad per particle:
| Buffer | Size | Written by | Read by |
|---|---|---|---|
| `<id>_verts` | `maxCount * 4 * 92 B` (GPU vertex buffer, carrying the per-particle channel in its tangent words) | GPU update | renderer, and the material's fragment stage |
| `<id>_indices` | `maxCount * 6 * 4 B` (GPU index buffer) | CPU once at create | renderer |
The vertex + index buffers are created with `vertex=true`/`index=true`
flags so `renderer.mesh.create` can wrap them as a renderable mesh with
zero CPU copy. The renderer binds the same GPU allocation the compute
shader just wrote to.
A **mesh** emitter uploads its source mesh once and draws it once per particle,
so it holds a placement and a colour instead of geometry:
| Buffer | Size | Written by | Read by |
|---|---|---|---|
| `<id>_xforms` | `maxCount * 64 B` (one column-major 4x4 per particle) | GPU update | renderer |
| `<id>_instdata` | `maxCount * 64 B` (four `vec4` shader-data lanes per particle) | GPU update | the material's fragment stage |
Those two buffers are what `renderer.mesh.drawInstanced` reads: the matrices
place each copy, and the lanes arrive in the fragment stage as
`input.shader_data[lane]`, which is how copies sharing one mesh and one material
each keep their own colour. 100 000 cube particles (24 verts) hold 12.8 MB this
way, against the 220 MB the same emitter would hold as replicated geometry.
### What one particle carries into its material
A material a particle system draws with reads four numbers belonging to the
particle covering the fragment — its `life` (normalised age, 0 → 1), its own
`seed` in [0, 1] fixed for its whole life, the world-space `size` it is drawn
at, and `alive`. Include the reader and take them off either emitter kind:
```wgsl
#include "@builtin::deprecated.deprecatedParticles.particle_data"
fn fragment(input: FragmentData) -> vec4<f32> {
let p = particle_sprite_data(input); // particle_mesh_data for a mesh emitter
let flicker = 0.6 + 0.4 * sin(input.time * 8.0 + p.seed * 6.2831);
return vec4<f32>(input.vertex_color.rgb * flicker, input.vertex_color.a * (1.0 - p.life));
}
```
A sprite emitter carries the four in the four words of each vertex the render
pipeline reads as the tangent, a mesh emitter in the instance lane beside its
colour, and `particle_layout` declares the order both compute passes pack. The
seed is what lets a population vary out of unison: it differs between the
particles of one emitter and reproduces for the same particle at any age, so a
noise phase or an atlas frame chosen from it holds still while that particle
lives. `@builtin::deprecated.deprecatedParticles.fx.fx_noise` takes it as a phase or an offset.
`renderer.instanceData` is the per-ENTITY channel: an emitter is one entity, so
the lanes it sets there are shared by every particle the emitter draws.
### Per-particle state (16 f32 = 64 bytes)
```
[0..2] position (xyz)
[3] age (seconds since spawn; >= lifetime means dead)
[4..6] velocity (xyz)
[7] lifetime (seconds)
[8..10] tint rgb (per-particle multiplicative tint; default 1)
[11] base size (sampled at spawn)
[12] rotation (degrees, current)
[13] rot speed (degrees/sec)
[14] per-particle seed in [0, 1] (used for envelope sampling)
[15] reserved / user data
```
### Params buffer layout
The first 32 floats are per-frame data; the next 32 are a user-controlled
param block for custom WGSL update shaders; the next 4 × 49 floats are
NumberSequence packs (size, transparency, squash, rotSpeed); the final 129
floats are the ColorSequence pack. See `init.luau`'s `PARAM_LAYOUT` for
the canonical offsets and `particle_layout.shaderModule` for the matching
WGSL constants. Past the ColorSequence pack come the collision header, the
collider records, and the grid a bound world distance field covers.
### Frame loop
```
1. CPU: spawn pending particles → writeBuffer on state buffer
2. CPU: pack per-frame uniforms → writeBuffer (first 32 floats only) on params
3. GPU: dispatch update shader → reads state, integrates, samples curves,
and writes this particle's output: a sprite
emitter's 4 vertices, or a mesh emitter's
matrix + shader-data lanes; collapsed to
nothing with area if dead
4. GPU: renderer draws the mesh — as an entity's model for a sprite emitter,
as a population for a mesh emitter
```
Vertex buffer is rebuilt every frame from the latest particle state. Dead
particles emit a zero-area quad that the rasterizer drops for sub-pixel
cost. That quad sits on the particle's own position, and a slot that has
never carried a particle holds the emitter's origin — the vertex buffer is
part of the scene's geometry, so a pass that gathers it (a distance field,
a bake, a BVH) covers an extent the emitter actually occupies.
## Curves: NumberSequence + ColorSequence
```lua
-- constant
NumberSequence.new(1.0)
-- two-point lerp
NumberSequence.new(0, 1)
-- full keypoint table (up to 16 keypoints; envelope is ± range per keypoint)
NumberSequence.new({
{ time = 0, value = 0.0 },
{ time = 0.3, value = 1.0, envelope = 0.2 },
{ time = 1, value = 0.0 },
})
-- a number keypoint list also takes its entries written positionally
NumberSequence.new({ { 0, 0.0 }, { 0.3, 1.0, 0.2 }, { 1, 0.0 } })
ColorSequence.new({ 1, 0.5, 0 }) -- constant
ColorSequence.new({ 1, 0, 0 }, { 0, 0, 1 }) -- lerp
ColorSequence.new({
{ time = 0, value = { 1, 1, 1 }, envelope = { 0.1, 0.0, 0.1 } },
{ time = 1, value = { 0, 0, 0 } },
})
-- a keypoint list also takes its entries written positionally, and a list of
-- bare colours spreads its stops evenly across [0, 1]
ColorSequence.new({ { 0, { 1, 1, 1 } }, { 1, { 0, 0, 0 } } })
ColorSequence.new({ { 1, 0.85, 0.35 }, { 1, 0.35, 0.05 } })
```
Every field of a keypoint reaches the GPU pack as one float, so a time, value,
channel or envelope that is not a number is refused by the constructor, naming
the keypoint's index and the types it read. Both classes pack a fixed 16 stops:
a longer list is resampled down to 16 keeping both endpoints, and the resample
logs a warning naming the cap and how many stops it dropped.
Sampling:
```lua
seq:evaluate(t) -- deterministic
seq:sample(t) -- envelope-randomized (math.random under the hood)
seq:sample(t, seed) -- envelope-randomized with a specific seed
```
The GPU shader samples each curve per particle per frame using the
per-particle seed stored at state slot 14, so envelope randomness is
deterministic across frames for a given particle and runs with no per-frame
CPU cost.
## Emission shapes
```lua
shape = {
kind = "cone", -- "point" / "box" / "sphere" / "cylinder" / "disc" / "cone"
size = { x=1, y=1, z=1 },
style = "volume", -- "volume" | "surface"
inOut = "outward", -- "outward" | "inward" | "inandout"
partial = 0, -- shape-specific (hemisphere cap, annulus inner, taper)
spreadAngle = 0, -- cone broadening around the sampled direction, degrees
}
```
Sampling runs on the CPU at spawn time only — the cost is per emitted
particle, not per active particle. Shapes are pure functions in
`shapes.module/init.luau`.
## Collision
An emitter meets things when `collision` names what a hit does — `"bounce"`,
`"stop"` or `"kill"` — and its collider list says what it can hit:
```luau
local sys = particles.create({
rate = 400, lifetime = 6, speed = 0, gravity = { 0, -9.81, 0 },
collision = "bounce", restitution = 0.3, friction = 0.4,
colliders = {
{ kind = "world" }, -- the scene itself
{ kind = "sphere", position = { 0, 2, 0 }, radius = 1.5 },
},
})
```
`plane`, `sphere` and `box` are shapes the emitter carries — eight at most,
because they ride the params buffer the update shader already binds.
`world` is the scene's own geometry: terrain, stairs, a rock, anything nobody
described as a shape. It reads the distance field `sceneProxy` builds — the
same coarse volumetric stand-in long-range lighting queries use — so contact
costs one texture read wherever a particle happens to be, on- or off-screen.
The first emitter to ask for one builds it (`worldResolution` voxels per axis,
64 by default); after the scene changes, `sceneProxy.refresh()` rebuilds it and
the emitter picks the new grid up on its next update.
Two things follow from the field being coarse: contact lands within about one
voxel of the true surface — raise `worldResolution` or the collider's `radius`
to place particles where you want them — and a particle that starts deep inside
geometry has no direction to be pushed out along, so it is pushed up.
The field is unsigned — it says how far the nearest surface is, not which side
of it a point is on — so the world collider resolves against the segment the
particle travelled this frame rather than against where it ended up. The march
starts from the position the particle held last frame, which the previous
resolve left outside, and stops where that path first comes within `radius` of a
surface. Contact therefore lands on the side the particle approached from, and a
step of any length is caught rather than carrying the particle through.
The world collider is resolved by the built-in sprite update. A mesh emitter
runs the mesh-instance update, which integrates without resolving colliders, so every
collider it carries reports no contact. An emitter running its own WGSL binds no
distance field, so the world collider reports no contact there while its other
colliders resolve as that shader resolves them. Both are said out loud, once per
emitter, the first time one runs.
## Shadow casting and render layers
An emitter declares whether its particles block light and which render layers
they draw on. Both reach the sprite path and the mesh path through the same
value, so an emitter's kind decides neither one:
```lua
local debris = particles.create({
mesh = "cube", maxCount = 300,
castsShadows = true,
renderLayer = "vfx",
})
debris:setCastsShadows(false)
debris:setRenderLayer("vfx fpsWeapon")
print(debris:getRenderLayer()) -- "vfx fpsWeapon"
print(debris:observe().castsShadows) -- false
```
`castsShadows` defaults to **false**. A caster is drawn into the shadow map as
the geometry it is — a sprite emitter's quads as quads, a mesh emitter's copies
as copies — so a soft alpha card casts the hard outline of its whole quad. That
is right for debris, rubble and solid mesh copies, which declare it, and wrong
for the smoke, dust and spark sheets that make up most of what an emitter draws,
which leave it alone.
`renderLayer` takes a layer name, an array of names, or a space-separated
string, and defaults to `"default"` — the layer a renderable with no layer of
its own sits on. A camera or a capture whose include spec names the layer draws
the emitter and one excluding it does not, so a reflection probe, a portal
camera, a minimap, a clean screenshot or an agent's `capture` takes the scene
with the effect in it or without:
```lua
capture({ renderLayers = "all !vfx" }) -- the scene, no emitters
```
Naming a layer interns it, which is what puts it in `renderLayer.list` and makes
it addressable from a capture's include spec.
Both are readable back — `:getCastsShadows()`, `:getRenderLayer()` — and both
are reported by `observe()`, so what an emitter declares is checkable without
capturing a frame and without reaching for the render host.
## Depth fade
A particle card that runs into a floor, a wall or a prop draws a straight line
along the intersection, which is what makes a large soft sprite read as a flat
billboard. `depthFade` is the distance, in world units, over which the card
dissolves into that surface instead:
```lua
local smoke = particles.create({
maxCount = 400, rate = 60, lifetime = { 2, 4 },
size = NumberSequence.new(0.5, 3),
depthFade = 1.5, -- world units
})
smoke:setDepthFade(2.5)
print(smoke:getDepthFade()) -- 2.5
print(smoke:observe().depthFade)
```
The quantity the distance is compared against is the straight-line distance
between a fragment and the surface already drawn behind it, both taken in world
space — so the ramp covers the same number of metres however far the camera
stands from it. A fragment at least `depthFade` in front of that surface keeps
its alpha whole; one standing on the surface is fully transparent; and one with
nothing behind it keeps its alpha, there being nothing to dissolve into.
The default is 0, which is off: an emitter that declares no fade draws through a
program that reads no depth at all, and the frame it draws in copies none for
it. Both emitter kinds take it — a sprite emitter's card and a mesh emitter's
copy alike. The value has to be a finite number at or above 0; anything else is
refused where it is declared rather than accepted and thrown once a frame.
An emitter drawing an authored material (`material = ...` / `:setMaterial`)
shades through that material's own shader, and fades over the distance that
shader reads from the material's own `depth_fade`. The emitter says so once,
because the material is shared by every entity drawing it and holds one distance
for all of them. A particle material carries a fade by declaring a `depth_fade`
float property, turning its shader's `DEPTH_FADE` feature on, and shading
through a shader whose block for that feature includes `zero::scene_depth` and
scales its alpha by `zero_scene_depth_fade(frag_coord.xy, world_position,
depth_fade)`. `particle_sprite.shader` is the worked form.
## Custom WGSL update shaders
Pass `updateShader = "/source/path/to/file.wgsl"` to `particles.create`.
The shader must match the binding layout:
```wgsl
// sprite emitter
@group(0) @binding(0) var<storage, read_write> particles: array<f32>;
@group(0) @binding(1) var<storage, read_write> vertices: array<u32>;
@group(0) @binding(2) var<storage, read_write> params: array<f32>;
// mesh emitter
@group(0) @binding(0) var<storage, read_write> particles: array<f32>;
@group(0) @binding(1) var<storage, read_write> transforms: array<f32>;
@group(0) @binding(2) var<storage, read_write> instance_data: array<f32>;
@group(0) @binding(3) var<storage, read_write> params: array<f32>;
```
Inside the shader, read per-frame data from the `params` array at the
offsets documented in `particle_update.computeShader/shader.wgsl` (and exported
as Lua constants from `particles.PARAM_LAYOUT`). A sprite shader writes the
engine's standard 23-u32 Vertex layout into `vertices`; a mesh shader writes a
column-major 4x4 per particle into `transforms` and four `vec4` lanes per
particle into `instance_data`, the shape
`particle_mesh_instance.computeShader/shader.wgsl` documents.
User uniforms live at `params[32..63]`. Set them from Luau:
```lua
system:setUserParam(1, 0.5) -- writes params[32] = 0.5
system:setParam("user1", 0.5) -- same
```
See `demos/particles_showcase/ParticlesShowcase.component/init.luau` for a
worked example with a curl-noise field driving 4000 particles.
## Performance notes
* **Compute pass cost** is proportional to `maxCount`, not to active count
— dead slots still execute one workgroup invocation each, but only do
the dead-check + degenerate-quad write (~10 instructions).
* **CPU spawn cost** scales with the per-frame emit count
(`rate × dt + bursts`), not with maxCount. A typical effect doing
100 particles/sec at 60 fps spends ~1.7 spawns/frame on the CPU.
* **GPU memory** is dominated by the vertex buffer at `368 B/particle`.
For 100 k particles that's ~37 MB. For 1 M particles ~370 MB — still
fits on a mid-tier GPU but profile first.
* **Sorting:** a sprite emitter that alpha-blends rewrites its own index
buffer every frame, on the GPU, into the order that walks its particles
back to front against the camera the frame is drawn from. While the
emitter can be holding at most 2 048 live particles it does that in ONE
compute dispatch (`particle_sort_local`: one workgroup sorts the live
particles' depth keys in workgroup memory and writes the index buffer),
so a step costs two dispatches, the simulation and the sort, whatever
`maxCount` is, and the sort holds 32 B of buffers. Past 2 048 live it
orders them by radix: a key pass, three dispatches per eight bits of
key and the index write, eight dispatches at the default bucket count,
over `maxCount`, in buffers of 12 B/particle plus a 1 KB digit
histogram for every block of 256 slots. What a sorted emitter spends is
dispatch overhead far more than per-particle work, so the dispatch
count is the cost to read: eleven emitters of 2 100 slots holding
~800 particles each spend 22 dispatches a frame rather than 99.
`sys:observe()` reports `sortPath` (`"local"` or `"radix"`),
`dispatchesPerStep` for the population the emitter holds now,
`lastStepDispatches`, and the running totals `computeDispatches`,
`sortDispatches` and `localSorts`. An emitter that adds skips all of it:
addition commutes, so its draw order cannot change its image.
`sort = false` on the spec (or `sys:setSorted(false)`) turns it off;
`sort = true` turns it on for an additive emitter. `sys:observe().sorted`
reports which way an emitter resolved, and `getGpuBytes().sort` what the
buffers cost it.
The order is a total order on (depth bucket, slot): two particles the
bucketing cannot tell apart keep slot order between them, and both paths
produce the same order, byte for byte in the index buffer. `sortBuckets`
is that resolution: 65535 by default, each bucket spanning 0.018% of its
own depth, which at five metres is under a millimetre. The one-dispatch
sort needs the bucket and the slot index to fit 32 bits together, which
the default does for every emitter of up to 65 536 slots. On the radix
path every eight bits of bucket index is one more radix pass and three
more dispatches, so `sortBuckets = 255` sorts in five dispatches instead
of eight at 2.7% of depth per bucket.
`simulate` reorders once at the end of the prewarm rather than once a
step: each step rewrites the index buffer the step before it wrote, so
only the last step's order can reach a draw.
What this orders is one emitter's particles against each other. Two
emitters are two draws, and the renderer orders draws rather than the
particles inside them, so two overlapping alpha plumes still composite
by draw order. Particles composite against opaque geometry through the
depth test, as they always did, and against other transparent surfaces
by draw order. A mesh emitter draws instanced copies rather than an
index buffer, and is not sorted.
* **Frustum culling:** a sprite emitter's mesh AABB is set to ±10 000 m so
per-emitter culling never trims active particles — emitter-level culling
happens at the entity level via the host entity's transform. A mesh emitter's
copies are culled one by one, each against the source mesh's own extent under
that particle's matrix. A dead particle's matrix is zero, which parks its copy
at the world origin with no area — it survives the cull whenever the origin is
on screen and then emits no fragments. The submitted count is the slots the
emitter has ever filled, not its cap: emission walks a write pointer from slot
0, so an emitter with a cap of 100 000 that has spawned five particles submits
five instances.
## Roadmap (follow-up issues)
The substrate is intentionally minimal. The follow-up issues track
features that build on top:
| Issue | Layer |
|---|---|
| #2674 ParticleEmitter component (38-property Roblox-shape surface) | shipped here as `deprecated/deprecatedParticles.package/DeprecatedSimpleParticleEmitter.component` |
| #2682 GPU compute backend (VFX-Graph-shaped) | shipped here |
| #2673 NumberSequence + ColorSequence Luau bindings | shipped here in Luau (Rust FFI is the future home) |
| #2679 Emission shapes | shipped here |
| #2680 Orientation modes | FacingCamera + FacingCameraWorldUp + VelocityParallel + VelocityPerpendicular shipped here |
| #2678 Flipbook texture animation | future — needs texture-atlas UV math |
| #2684 Particle ↔ world collision | analytic shapes and the scene's own geometry shipped here; see "Collision" below |
| #2685 Force fields / curl noise | curl-noise demoed via custom WGSL; first-class ForceField component is future work |
| #2681 LightEmission / LightInfluence HDR | brightness shipped; LightInfluence (read GI) future |
| #2683 Mesh particles | shipped here — one instanced draw of the source mesh, placed and coloured per particle by the compute pass |
| #2690 VFX editor (curve inspector, profiler) | future |
| Back-to-front sorting for alpha-blended emitters | shipped here — see "Sorting" above |
## Parts
The module is a folder of parts, each a module of its own that `init.luau` requires:
- `Particles.spec`: the readers that check each emitter spec field against the shapes it takes.
- `Particles.spawnBatches`: the spawn batches an emitter keeps and the particles they can still hold alive.
## API reference
See the `--!desc` doc-comments at every public method in `init.luau`,
`curves.module/init.luau`, and `shapes.module/init.luau` for the
authoritative API surface. `lsp.describe("particles/create")` and
`lsp.search("particles")` from the engine also work after the engine has
indexed the module.
# fx_noise
Procedural noise for effect shaders — the integer hashes underneath it, value
and gradient noise in 2D and 3D, fBm over either, curl noise, and
worley/voronoi carrying a distance and a cell id.
```wgsl
#include "@builtin::deprecated.deprecatedParticles.fx.fx_noise"
```
Pure math — no bindings. A Surface-domain shader and a `.computeShader` see
different generated frameworks and can share a function only when it touches
neither, so a plume's material and the compute pass that simulates it read one
field rather than two that drift apart.
Every generator takes an explicit `seed` as its last argument, so one shader
draws several uncorrelated fields from the same coordinates.
## Hashes
`fx_hash_u32`, `fx_hash_u2`, `fx_hash_u3` mix 32-bit words; `fx_unorm` and
`fx_snorm` turn a word into a float in `[0,1)` or `[-1,1)`. `fx_hash11`,
`fx_hash21`, `fx_hash31`, `fx_hash22` and `fx_hash33` take floats and hash the
bits `fx_bits` reads off them, which folds `-0.0` onto `0.0` so both spellings
of the number reach the same word.
The mixing is integer, which is what makes a value the same bit pattern
wherever the shader runs — the same on native and on the web.
## Noise
| Function | Range | Property it guarantees |
|----------|-------|------------------------|
| `fx_value_noise2(p, seed)` | `[0,1)` | at an integer `p` the value is `fx_lattice21(p, seed)` exactly |
| `fx_value_noise3(p, seed)` | `[0,1)` | at an integer `p` the value is `fx_lattice31(p, seed)` exactly |
| `fx_gradient_noise2(p, seed)` | `[-1,1]` | exactly `0` at every integer `p` |
| `fx_gradient_noise3(p, seed)` | `[-1,1]` | exactly `0` at every integer `p` |
`fx_lattice21` / `fx_lattice31` read a corner's value directly, and
`fx_gradient2` / `fx_gradient3` read the unit gradient a corner carries.
`fx_fade` is the quintic both interpolate across a cell with.
## fBm
`fx_fbm2(p, octaves, lacunarity, gain, seed)` and `fx_fbm3(...)` sum octaves of
gradient noise, each `lacunarity` times the frequency of the one before it and
its amplitude scaled by `gain`, divided by the amplitudes summed — so the range
stays `[-1,1]` for any gain, and one octave returns that octave exactly.
`fx_ridged_fbm3` folds each octave about zero so the field's peaks are creases.
`gain` is read as a magnitude — how fast the amplitudes fall away, which is a
size rather than a direction. That is what keeps the sum of amplitudes a
positive number the total is divided by, and so keeps every range above true
whatever the caller passes.
`octaves` is held to `FX_FBM_MAX_OCTAVES` (12), which is the loop the shader
compiles.
## Curl noise
`fx_curl_noise3(p, seed)` is the curl of `fx_curl_potential3`, taken over the
step `FX_CURL_EPSILON`. A vector field built as a curl is divergence-free: a
particle advecting along it is neither piled up nor torn away from its
neighbours.
## Worley / voronoi
`fx_worley2(p, seed)` and `fx_worley3(p, seed)` return `dist`, the `cell` that
owns the nearest feature point, and a stable `id` in `[0,1)` for that cell — the
value a caller tints a voronoi region by. `fx_cell_point2` / `fx_cell_point3`
give where inside its own cell a cell's feature point sits, so a caller can
place a sample exactly on one; `fx_cell_id2` / `fx_cell_id3` give the id
directly. `fx_worley_fbm2` sums inverted octaves of the distance.
# fx_sdf
Signed distance fields for effect shaders — the primitives an effect is shaped
out of, the boolean and smooth-boolean operators that combine them, and the
domain operators that repeat, round and hollow them.
```wgsl
#include "@builtin::deprecated.deprecatedParticles.fx.fx_sdf"
```
Pure math — no bindings. A Surface-domain shader and a `.computeShader` see
different generated frameworks and can share a function only when it touches
neither, so a shield's material and the compute pass that fills its volume
measure one distance.
Every primitive is centred on the origin and takes the sample point in its own
space, so a caller places one by transforming `p` rather than by passing a
centre. Every one returns the signed distance to the surface: negative inside,
positive outside, zero on it.
## Primitives
| Function | Surface |
|----------|---------|
| `fx_sd_sphere(p, r)` | radius `r` about the origin |
| `fx_sd_box(p, b)` | half-extents `b` |
| `fx_sd_round_box(p, b, r)` | half-extents `b` with edges rounded by `r`; the solid still reaches `b` |
| `fx_sd_torus(p, major, minor)` | ring of radius `major` in XZ, tube radius `minor` |
| `fx_sd_plane(p, n, h)` | plane through `-h * n` with normal `n` |
| `fx_sd_capsule(p, a, b, r)` | radius `r` around the segment `a`→`b` |
| `fx_sd_cylinder(p, h, r)` | radius `r`, half-height `h`, axis Y |
## Operators
`fx_op_union` is `min`, `fx_op_intersect` is `max`, and `fx_op_subtract(a, b)`
carves `b` out of `a`.
`fx_op_smooth_union`, `fx_op_smooth_intersect` and `fx_op_smooth_subtract` take
a fillet width `k` and weld the surfaces over it. A smooth union is never
greater than `min(a, b)` and never less than `min(a, b) - k / 4`, so it reaches
its hard counterpart as `k` approaches zero.
`fx_op_round` grows the field outwards, `fx_op_onion` hollows it into a shell,
and `fx_op_blend` morphs one field into another.
## Domain operators
These transform the point rather than the distance, so a primitive evaluated at
the result is the one that repeats or stretches: `fx_op_elongate` stretches
along each axis, `fx_op_repeat` folds the point into one cell of an infinite
grid, `fx_op_mirror` folds it into the positive octant.
# fx_shaping
The curves and UV transforms that turn a field into a look — remapping, easing,
gradient ramps over a small keypoint set, polar and radial UV, and flow-map
distortion.
```wgsl
#include "@builtin::deprecated.deprecatedParticles.fx.fx_shaping"
```
Pure math — no bindings. A Surface-domain shader and a `.computeShader` see
different generated frameworks and can share a function only when it touches
neither, so an explosion's material and the pass that drives its lifetime read
one curve.
## Remap
`fx_remap(v, in_lo, in_hi, out_lo, out_hi)` extends past both ends,
`fx_remap_clamped` holds at them, and `fx_remap01(v, lo, hi)` reports where `v`
sits in a range as `[0, 1]`. All three divide through `fx_nonzero`, so a
degenerate range gives a finite answer rather than an infinity that spreads
through everything downstream of it.
## Easing
Each curve takes `x` in `[0, 1]` and returns `[0, 1]`, holding 0 at 0 and 1
at 1.
| Function | Shape |
|----------|-------|
| `fx_smoothstep01(x)` | cubic Hermite |
| `fx_smootherstep(edge0, edge1, x)` | quintic Hermite — second derivative vanishes at both ends |
| `fx_pulse(edge0, edge1, softness, x)` | 1 inside the band, with a shoulder of width `softness` |
| `fx_ease_in_expo` / `fx_ease_out_expo` / `fx_ease_in_out_expo` | exponential |
| `fx_ease_in_pow(x, k)` / `fx_ease_out_pow(x, k)` | a knee whose sharpness is a parameter |
| `fx_gain(x, k)` | contrast about (0.5, 0.5); `k` of 1 returns `x` |
## Gradient ramps
`fx_ramp4(t, positions, values)` and `fx_ramp4_color(t, positions, c0, c1, c2,
c3)` evaluate four keypoints whose positions ascend in `positions`. `t` at a
keypoint returns that keypoint's value exactly; between two neighbours it
interpolates linearly; past either end it holds.
## Polar and radial UV
`fx_to_polar(uv, center)` gives `(radius, turns)` with the angle over `[0, 1)`
anticlockwise from +X, and `fx_from_polar` inverts it. `fx_radial_uv(uv, center,
repeat, spin)` rewrites a UV so `x` runs around the centre `repeat` times and
`y` runs out from it — the coordinates a shockwave ring or an arcane circle is
drawn in. `fx_rotate_uv(uv, center, turns)` spins one about a point.
## Flow-map distortion
`fx_flow(uv, flow, time, strength)` returns the two UVs to sample and the weight
of the first:
```wgsl
let f = fx_flow(uv, flow_vector, time, 0.25);
let color = mix(textureSample(tex, samp, f.uv_b), textureSample(tex, samp, f.uv_a), f.blend);
```
The two samples are half a cycle out of phase, and each one's weight falls to 0
at the moment it resets, which is what hides the reset. `time` is in cycles.
# look_droplet
A soft ellipse with a highlight sitting up and to the left — rain, splashes, a bead of liquid.
`energy` scales the final colour; `detail` is unused by this look's shape.
The material `look = "droplet"` on an emitter draws with.
# look_ember
A mote that flickers, out of unison with its neighbours.
`energy` scales the final colour; `detail` is unused by this look's shape.
The material `look = "ember"` on an emitter draws with.
# look_flame
A tongue of fire, narrow at the tip and licked by noise that runs upward, hot at the base and cooling as the particle ages.
`energy` scales the final colour; `detail` is unused by this look's shape.
The material `look = "flame"` on an emitter draws with.
# look_glow
A wide, low body and a small hot core, so many of them add up to light rather than to white.
`energy` scales the final colour; `detail` is unused by this look's shape.
The material `look = "glow"` on an emitter draws with.
# look_mote
A soft gaussian dot that reaches zero at the edge — the default look, and what dust, snow and every generic particle is.
`energy` scales the final colour; `detail` is unused by this look's shape.
The material `look = "mote"` on an emitter draws with.
# look_puff
A puff of smoke, steam or dust: a noise body eaten away as the particle ages, lit as a volume from the gradient of the same field that shapes it.
`energy` scales the final colour; `detail` scales the noise domain the puff is carved from, so a higher value packs more turbulence into the same quad.
The material `look = "puff"` on an emitter draws with.
# look_ring
A band that expands over the particle's life and thins as it goes.
`energy` scales the final colour; `detail` is unused by this look's shape.
The material `look = "ring"` on an emitter draws with.
# look_spark
A hot core along the quad's long axis, tapered at both ends. Pair with `stretch` so the quad lies along the velocity.
`energy` scales the final colour; `detail` is unused by this look's shape.
The material `look = "spark"` on an emitter draws with.
# look_droplet
A sprite particle drawn as a droplet: a soft ellipse with a highlight sitting up and to the left.
`detail` is unused by this look's shape but still declared for a uniform property set; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_droplet` draws with `look = "droplet"` on an emitter.
# look_ember
A sprite particle drawn as an ember: a mote that flickers, out of unison with its neighbours.
`detail` is unused by this look's shape but still declared for a uniform property set; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_ember` draws with `look = "ember"` on an emitter.
# look_flame
A sprite particle drawn as a flame: a tongue of fire, narrow at the tip and licked by noise that runs upward, hot at the base and cooling as the particle ages.
`detail` is unused by this look's shape but still declared for a uniform property set; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_flame` draws with `look = "flame"` on an emitter.
# look_glow
A sprite particle drawn as a glow: a wide, low body and a small hot core, so many of them add up to light rather than to white.
`detail` is unused by this look's shape but still declared for a uniform property set; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_glow` draws with `look = "glow"` on an emitter.
# look_mote
A sprite particle drawn as a mote: a soft gaussian dot that reaches zero at the edge — the default look, and what dust, snow and every generic particle is.
`detail` is unused by this look's shape but still declared for a uniform property set; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_mote` draws with `look = "mote"` on an emitter.
# look_puff
A sprite particle drawn as a puff of smoke, steam or dust: a noise body eaten away as the particle ages, so a plume dissolves rather than fades, lit as a volume from the gradient of the same noise field.
`detail` scales the noise domain the puff is carved from; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_puff` draws with `look = "puff"` on an emitter.
# look_ring
A sprite particle drawn as a ring: a band that expands over the particle's life and thins as it goes.
`detail` is unused by this look's shape but still declared for a uniform property set; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_ring` draws with `look = "ring"` on an emitter.
# look_spark
A sprite particle drawn as a spark: a hot core along the quad's long axis, tapered at both ends. Pair with `stretch` so the quad lies along the velocity.
`detail` is unused by this look's shape but still declared for a uniform property set; `energy` scales the final colour.
The material `@builtin::deprecated.deprecatedParticles.fx.looks.materials.look_spark` draws with `look = "spark"` on an emitter.
# particle_looks
The eight looks a sprite particle can be drawn as — mote, glow, puff, flame, spark, ember, droplet, ring — as pure WGSL functions of the quad's uv and the particle's own life, seed and size. Each answers a `LookSample { alpha, heat }`; `look_heat` runs the particle's colour toward white by its heat, `look_puff_normal` is the normal a puff shades under, and `look_weighted` hands the blend equation the fragment it expects.
Included by every `looks/shaders/look_*.shader`, after `particle_data`, `fx_noise` and `fx_shaping`.
## Authoring colour stops
A colour a look returns is linear light, and the eye reads it after the display encode. That encode lifts the middle of the range hard: a linear 0.5 arrives near 0.74, a linear 0.12 near 0.38. A stop written down as the colour it is meant to LOOK therefore arrives washed out — the vivid orange `(1, 0.5, 0.12)` is delivered as a dusty tan.
So a stop meant to read as a saturated colour keeps its minor channels far lower than the on-screen target: to read as `(1, 0.4, 0.02)` a stop holds about `(1, 0.13, 0.0003)`. The further a colour is meant to be from grey, the wider the gap between the number and the target.
`look_flame_color` is the worked form. It raises the emitter's hue to a power for each stop — the cube for the tint's own colour, the sixth for the cool end — and lifts the hot end per channel rather than toward white as a colour, so the range runs red → orange → yellow → white-yellow instead of through pink.
·computeshader · born here
❒asset # particle_census
Counts a particle emitter's live slots on the device. One invocation per slot
over the state buffer the update pass writes, applying the same test that pass
applies — a slot is alive while `age < lifetime` — and accumulating into a
two-slot `u32` counter.
| Slot | Counts |
|---|---|
| 0 | live particles |
| 1 | live particles a dispatch has advanced (`age > 0`) |
The gap between the two is what a state buffer the simulation has not run over
looks like: the emitter's spawns wrote slots at age 0, and nothing moved them.
Bindings (see `bindings.yaml`): `particles` (read `array<f32>`), `census`
(read_write `array<atomic<u32>>`), `params` (read `array<f32>`, whose
`P_MAX_COUNT` bounds the pass).
The particle module dispatches it for an emitter that has been asked to confirm
its population — `sys:requestCensus()`, or any `sys:observe()` — and reads the
counter back over the following frames. The answer reaches content through
`observe().confirmation`, carrying the simulated time it was taken at.
# particle_data
The per-particle channel, read from a material.
A particle carries four numbers into the material that draws it — `life` (its
normalised age, 0 → 1), `seed` (its own random in [0, 1], fixed for its whole
life), `size` (the world-space size it is drawn at this frame), and `alive`.
`particle_layout` declares the four as `ParticleData`; this module is how a
shader reads them back.
```wgsl
#include "@builtin::deprecated.deprecatedParticles.particle_data"
fn fragment(input: FragmentData) -> vec4<f32> {
let p = particle_sprite_data(input); // particle_mesh_data for a mesh emitter
let flicker = 0.6 + 0.4 * sin(input.time * 8.0 + p.seed * 6.2831);
return vec4<f32>(input.vertex_color.rgb * flicker, input.vertex_color.a * (1.0 - p.life));
}
```
The two emitter paths carry the channel in different places — a sprite in the
four tangent words of each vertex of its billboard quad, a mesh in an instance
shader-data lane — so there is one accessor for each, and both hand back the
same `ParticleData`.
`seed` is what makes a population vary out of unison: it differs between the
particles of one emitter and reproduces for the same particle at any age, so a
noise phase or an atlas frame chosen from it is that particle's own and holds
still while it lives. `@builtin::deprecated.deprecatedParticles.fx.fx_noise` takes it directly as
a phase or an offset.
This is the per-PARTICLE channel. `renderer.instanceData` is the per-ENTITY one:
a sprite emitter is a single entity, so the lanes it sets are shared by every
particle the emitter draws.
# particle_layout
Where everything lives in the particle system's two buffers: the 16 f32 of one
particle's state, and the offsets of every field in an emitter's parameter
block — frame data, physics, the packed curves, the collider records, and the
grid a bound world distance field covers.
The Luau module packs those buffers and the update shaders read them, so an
offset written down twice is an offset that can disagree. Every shader that
touches either buffer includes this.
# particle_lighting
The light a particle takes from the scene it is drawn in, shared by the sprite
and mesh particle shaders.
```wgsl
#include "@builtin::deprecated.deprecatedParticles.particle_lighting"
```
| Function | Answers |
|---|---|
| `zero_particle_point_light(input)` | The multiplier the point lights near this fragment add — 1 outside every light's radius. |
| `zero_particle_scene_light(input)` | The scene's own light at this fragment — the ambient term plus the sun through a wrapped diffuse. |
| `zero_particle_lit(input, rgb, light_influence, light_emission)` | `rgb` with an emitter's two light declarations honoured. Both at 0 returns `rgb` unchanged. |
`light_influence` is how much of the scene's light the particle takes;
`light_emission` is how much of itself it emits regardless. A `ParticleEmitter`
carries them as `lightInfluence` and `lightEmission`, and the particle
materials this package ships read them from material properties of the same
names.
# Particle Mesh Default
The default surface for mesh particles — the one material every copy in a
mesh-particle population draws with, while each copy still carries its own
colour and opacity in its per-instance shader-data lanes. A neutral white base
colour (`1.0, 1.0, 1.0`) with no emissive, so the per-particle colour and any
bound texture fully drive the look. Transparent, double-sided (`cull: none`), in
the transparent queue (`3000`). Built on
`@builtin::deprecated.deprecatedParticles.particle_mesh`.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — neutral tint that lets per-particle colour show through.
- `colors.emissive` (`0.0, 0.0, 0.0`) — no self-illumination by default.
- `textures.base_color_texture` — the image mapped over the source mesh (`default:white` placeholder).
- `float2.uv_scale` (`1, 1`) / `float2.uv_offset` (`0, 0`) — how the texture is mapped over the source mesh's own UVs.
·computeshader · born here
❒asset # particle_mesh_instance
Mesh-particle path of the generic GPU particle system. One invocation per
particle: it integrates the particle, samples the size/transparency/colour
sequences, and writes the particle's world matrix and its shader-data block.
The emitter's source mesh is uploaded once and drawn `maxCount` times from those
matrices, so both the memory this path holds and the work it does each frame are
proportional to the particle count and independent of how many vertices the
source mesh has.
Bindings (see bindings.yaml): `particles` (read_write `array<f32>`, 16 f32 per
particle), `transforms` (read_write `array<f32>`, 16 f32 per particle — one
column-major 4x4), `instance_data` (read_write `array<f32>`, 16 f32 per particle
— four `vec4` lanes), `params` (read_write `array<f32>`).
Shader-data lanes, as `particle_mesh.shader` reads them:
| Lane | Contents |
|------|----------|
| 0 | `rgb` the particle's colour, tinted and brightened; `a` its opacity |
| 1 | `(life_t, seed, world size, 1 while alive)` |
Usage: dispatch by identity with
`compute.dispatch("@builtin::deprecated.deprecatedParticles.particle_mesh_instance", ...)`
(buffers in bindings order) — it resolves to the shader's stable guid and
auto-compiles on first use.
# particle_sim
The sprite particle simulation itself: integrate one particle, resolve it
against the emitter's colliders, sample its curves, and write the billboard quad
it draws as.
A shader that includes it binds `particles`, `vertices` and `params`, includes
`particle_layout` ahead of it, and defines `world_field(p)` — the distance from
a point to the scene's own geometry. That one function is the difference between
the update shaders: one answers from a distance field it binds, the other
answers that nothing is near.
# particle_sort_depth
The depth key a sprite emitter's back-to-front sort orders its particles by:
`particle_depth_key(pos, cam, near, far, bucket_count)` files a particle into
one of `bucket_count` depth buckets, numbered far to near, so ascending keys
walk the population back to front.
The distance is radial, from the camera position, because a particle draws as
a quad turned to face the camera. Buckets are spaced logarithmically between
`near` and `far`, so each spans a constant ratio of depth: resolution is finest
close to the camera, and one key space covers a scene of any size.
`particle_sort_key` (the radix path's key pass) and `particle_sort_local` (the
one-dispatch path) both include it, so the two paths order a population by the
same keys.
·computeshader · born here
❒asset # particle_sort_indices
The last stage of a sprite emitter's per-frame back-to-front sort. One thread
per draw slot, once per frame the emitter sorts.
Thread n reads which particle the sort put n-th and writes that particle's two
triangles into the n-th six-index run of the emitter's index buffer. The
vertices stay where the update pass wrote them, so the whole sort costs one u32
per slot of traffic and nothing per vertex.
A slot the sort resolved to the sentinel holds no live particle. It takes six
copies of index 0 — three zero-area triangles the rasterizer drops.
## Bindings
| Slot | Access | Contents |
|------|--------|----------|
| `indices` | read | The final permutation: entry n names the slot that draws n-th. |
| `out_indices` | read_write | The emitter's index buffer, six indices per slot. |
| `sortview` | read | `[0]` slot count. |
Dispatch one workgroup of 64 per 64 slots.
·computeshader · born here
❒asset # particle_sort_key
Stage 1 of a sprite emitter's per-frame back-to-front sort. One thread per
particle slot, once per frame the emitter sorts.
Each thread measures how far its particle stands from the camera and files it
into one of `bucket_count` depth buckets ordered far to near, so sorting the
keys ascending walks the population back to front. It also seeds the sort's
input permutation to the identity, which keeps a four-byte-per-slot fill off the
upload path.
The distance is radial rather than along the view axis: a particle draws as a
quad turned to face the camera, so which of two quads is in front is decided by
which centre the camera is nearer to.
Buckets are spaced logarithmically between `near` and `far`, so each bucket
spans a constant ratio of depth. Resolution is finest close to the camera, where
overlapping particles are largest on screen, and one key space covers a scene of
any size.
A dead slot takes `bucket_count`, one past the last real bucket. That parks it
in the tail of the permutation, where `radix_scatter` resolves it to the
sentinel and `particle_sort_indices` writes it a degenerate quad.
## Bindings
| Slot | Access | Contents |
|------|--------|----------|
| `particles` | read | The emitter's particle state, 16 f32 per slot. |
| `params` | read | The emitter's parameter block — camera position, slot count. |
| `keys` | read_write | Per-slot depth bucket. |
| `indices` | read_write | The identity permutation the radix passes start from. |
| `sortview` | read | `[0]` slot count, `[1]` bucket count, `[2]` near depth, `[3]` far depth. |
Dispatch one workgroup of 64 per 64 slots.
·computeshader · born here
❒asset # particle_sort_local
A sprite emitter's whole back-to-front sort in one dispatch, for a population
of up to 2048 live particles. One workgroup of 256 threads, once per frame the
emitter sorts and its live particles fit.
The threads walk every slot, give each live particle its depth key
(`particle_sort_depth`) and gather it into workgroup memory as one word: the key
in the high bits and the slot in the low `sortlocal[0]` bits. A bitonic network
sorts those words, sized to the next power of two at or above the live count, so
the population comes out ordered by key and, inside one key, by slot: the same
total order the radix path (`particle_sort_key`, three `gpuSort` passes per
eight bits of key, `particle_sort_indices`) produces.
The sorted words are written out as the emitter's index buffer. Run n takes the
two triangles of the n-th particle, and every run past the live count is six
copies of index 0, so the buffer holds exactly what the radix path leaves. Only
the runs between this write's live count and `sortlocal[1]` (the runs the
previous write may have left holding triangles) are cleared, so the write costs
the live population rather than the emitter's capacity.
An emitter takes this path when the slot and the key fit one 32-bit word
together and its live count is at most 2048; past that, the radix path orders it.
## Bindings
| Slot | Access | Contents |
|------|--------|----------|
| `particles` | read | The emitter's particle state, 16 f32 per slot. |
| `params` | read | The emitter's parameter block: the camera position. |
| `out_indices` | read_write | The emitter's index buffer, six indices per slot. |
| `sortview` | read | `[0]` slot count, `[1]` bucket count, `[2]` near, `[3]` far. |
| `sortlocal` | read_write | `[0]` slot bits, `[1]` runs that may hold triangles, `[2]` live particles found. |
Dispatch exactly one workgroup.
# Particle Sprite Default
The default sprite surface for the particle system — a neutral white base colour (`1.0, 1.0, 1.0`) with no emissive, so per-particle tint and the bound sprite texture fully drive the look. Transparent, double-sided (`cull: none`), non-instanced, in the transparent queue (`3000`). Built on `@builtin::deprecated.deprecatedParticles.particle_sprite`.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — neutral tint that lets per-particle colour show through.
- `colors.emissive` (`0.0, 0.0, 0.0`) — no self-illumination by default.
- `textures.base_color_texture` — the sprite image (`default:white` placeholder).
- `floats.roughness` (`1.0`) / `floats.metallic` (`0.0`) — flat, dielectric sprite.
·computeshader · born here
❒asset # particle_update
Default update shader for the generic GPU-driven particle system. Runs once per
frame over the full particle buffer: integrates physics (gravity, drag, wind,
accel), samples the size/transparency/squash/rotation NumberSequences and the
ColorSequence on the GPU, and writes a billboard quad (4 vertices) per particle in
the engine's standard 92-byte vertex layout.
Bindings (see bindings.yaml): `particles` (read_write `array<f32>`, 16 f32/particle),
`vertices` (read_write `array<u32>`), `params` (read_write `array<f32>`).
Usage: dispatch by identity with `compute.dispatch("@builtin::deprecated.deprecatedParticles.particle_update", ...)` (buffers in bindings order) —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
·computeshader · born here
❒asset # particle_update_world
The sprite update shader with the scene's geometry as a collider. Same
simulation as `particle_update` — it shares `particle_sim` — plus a fourth
binding: a distance field covering the scene, which is what a `world` collider
in the emitter's collider list consults.
Bindings (see bindings.yaml): `particles` (read_write `array<f32>`, 16 f32 per
particle), `vertices` (read_write `array<u32>`), `params` (read_write
`array<f32>`), `pw_field` (`texture_3d<f32>`, r32f — world-space distance to the
nearest surface per voxel).
The grid the field covers is described by the params buffer's world block, which
the particles module writes from the field's own settings. With the block's flag
clear the world collider reports no contact, so an emitter whose field has gone
away keeps simulating against its analytic colliders.
Contact is resolved where the field reads the collider record's radius, so
accuracy follows the field's voxel size — a coarser grid rests particles further
from the surface.
# 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.install`, `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).
**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 })
```
## 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` from the shared library, or
`tools.use("zeromind", "installAsset", <guid>)` inside the engine. The
install writes the package's files (and the deps its `.refs`
record) 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.
- Version conservatively — breaking a package means breaking every
world that installed it. Use semantic version bumps.
## Common pitfalls
- **Missing `package.yaml`.** Without it the folder isn't recognized
as a package even if it has a `.package/` suffix.
- **Dependency installs.** A package that depends on another package
must declare it (in `package.yaml::dependencies` once supported)
and the parent world must install dependencies in order.
- **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.otherPkg.modules.x")` |
| A **different library's** public API (a deliberate external dependency) | `@otherlib::…` | `require("@physics::modules.rigidbody")` |
**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 a reusable behavior + data unit attached to an entity.
The component file declares public fields, methods, and lifecycle
callbacks; the engine instantiates one per attachment and drives its
hooks every frame. Components are the primary unit of 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`, `destroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If you need a global service that outlives any entity, use a `.service`
instead. If you need a stateless pure-function library, use a `.module`.
## 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 beside it on the fixed timestep; `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`, `destroy`) 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 service, 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. Update
every `component.add(<oldname>, ...)` call and the scene JSON
entries that reference it.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service` — globally-scoped behavior, 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`.
# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## 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 logic is bound to one entity, 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**.
# 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; 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` | — | `var NAME: sampler;` |
| `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 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` 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`, `rgba8`, `rgba16f`,
`rgba32f`. Storage textures only allow storage-compatible formats
(`r32f` / `rgba8` / `rgba16f` / `rgba32f`).
- 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, for shadow/occlusion rays), and
`zeroHitSurface(hit) -> ZeroSurface` (`normal, uv, material`) +
`zeroMaterial(index) -> ZeroMaterial` (`base_color, emissive, metallic,
roughness`) to shade what a hit landed on. The same surface works on both backends — hardware
ray query and the software/compute path — so the shader doesn't branch on
`renderer.raytraceCapability()`. 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 }` — for shaders mixing textures, samplers and storage textures: one `{ kind, name }` per declared binding, in order |
| `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 |
| `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, or a texture asset's guid once `texRef:handle()` has made it GPU-resident |
| `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` |
`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.
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.
`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 },
},
})
```
## Registration & hot reload
Writing `shader.wgsl` or `bindings.yaml` fires the `.computeShader` assetType's
`onChange`, which calls `__compute.compile` — that generates the binding
declarations, expands `#include`s, naga-validates, and registers. 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"`, and a dispatch issued before that is dropped.
- **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` / `rgba8` /
`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) and the
legacy `@domain: compute` fallback.
## 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`.
# Scene (asset type)
A scene is a saved, loadable snapshot of an entity scenegraph inside a
world: the entity hierarchy, transforms, components, lighting, and a
declared `player` intent, plus an auto-discovered startup script. A scene
is the unit of "level" or "screen" — a title screen, a lobby, a gameplay
area, and an end-of-game summary each get their own scene.
Scenes load as **layers**. One root scene is active at a time; additional
scenes can load additively as overlays on top of it. Each scene owns its
own multiplayer relay room. Switching scenes is a local call: the client
that makes it leaves the old scene's room and joins the new scene's room.
## When to use one
- You want a savable, re-loadable snapshot of an entity scenegraph plus
its lighting and player setup.
- You want a runnable starting state for a level or screen.
- You want a scenes-as-data flow: `layers.load("lobby")`, edit live, then
`layers.active:save()` to publish the edits back to the scene.
For a reusable entity assembly (a prop, a vehicle, a UI panel) that many
scenes spawn into themselves, use a `.bundle`. A scene is a whole-world
snapshot; a bundle is one prefab that lives inside scenes.
## Folder shape
A scene asset is a folder ending in `.scene`. Its identity is the folder
name with the suffix stripped (`Lobby.scene` → `Lobby`).
- `scene.json` — the scenegraph: `entities[]`, lighting, and the
top-level `player` intent. **Required.** Written by the engine — a build,
a save, a human dragging something in. Not hand-edited.
- `build.luau` — what the scene is made of, written as code. Runs while you
author; saving bakes its result into `scene.json` (see Building a scene).
- `entrypoint.luau` — the startup script. Auto-discovered as a sibling of
`scene.json`; define lifecycle callbacks here (see The entrypoint).
- `<name>.<type>/` — an asset the build makes, authored here by `build.asset`
(see The assets a build makes), alongside `.build.assets`, which records
which `build.luau` produced each of them.
- `prefabs/` — optional subfolder for scene-local bundles.
- `scripts/` — optional subfolder for scene-local Luau helpers, required
from `entrypoint.luau`.
- `README.md` — optional per-scene notes about THIS scene. Author one only
when there is scene-specific detail worth recording; the general scene
model lives here, in `guides { path: "types/scene" }`.
`scene.json` is version 7. It carries `"format": "scene"`,
`"version": 7`, an `entities[]` array, and a top-level `"player"` string
intent.
## The `player` intent
Every scene declares how it handles players with a top-level `player`
field in `scene.json`:
- `"spawns"` — the scene carries an authored player setup, and the engine
spawns a player for each connecting user from it. This is the default
for a freshly created scene.
- `"none"` — the scene spawns no player and authors no camera. Author your
own Camera entity for the view (menus, UI-only screens, cinematics).
### How `"spawns"` works
A `"spawns"` scene authors two things in `scene.json`:
1. A **PlayerPrototype** — an entity carrying the `PlayerPrototype`
component, whose `body` field names a child entity (the body). The
body carries an avatar (an `Asset` pointing at an avatar, e.g.
`@builtin::avatars.humanoid`). A `CameraRig` child carries a `Camera`
with a camera behavior (e.g. `orbital_follow`). The prototype root is
authored `PrototypeOnly` so it exists as a clonable template.
2. A **PlayerSpawn** — an entity carrying the `PlayerSpawn` component,
whose `prototype` field names the PlayerPrototype to instantiate and
whose transform is where players appear.
The scaffolded scene groups these under two organizing entities,
`PlayerSetups` (holding the prototype) and `Spawns` (holding the spawn),
so the authoring tree stays legible.
On each user join — entering play, and each subsequent connect — the
engine runs the spawn for that user:
- It clones the PlayerPrototype subtree.
- The clone root becomes the user's **internal identity** — a registry-only
entity named `user` carrying the `UserIdentity` component. The identity
is the anchor for who the player is; it has no world presence.
- The body named by `PlayerPrototype.body` is adopted as the user's
**avatar** — their visible presence in the world — and placed at the
PlayerSpawn's world transform. Move the PlayerSpawn (or drag it in the
editor) to set where players appear.
- The `CameraRig`'s Camera follows the bound avatar.
The player prototype is live in edit mode so you can see and adjust it. In
play mode it is deactivated and marked internal — it stays a clonable source while
each user gets their own clone.
### Reaching the live player
The player surface lives on the root scene's registry,
`layers.active.players`:
- `players.localPlayer` — this client's player, a curated handle.
- `players.localReady` — `true` once the local player's avatar is bound
(or the scene opted its avatar out).
- `players:list()` / `players:count()` — the players connected in this
scene's room.
- `players:get(userId)` — a connected player by account id.
- `players:ownerOf(avatar)` — the player whose body is a given avatar.
A player handle is a data record about who the player is, plus a link to
their body:
- `player.avatar` — the body's entity ref. Act on the body through it
(`player.avatar.position`, raycasts, rig access).
- `player.isLocal` — whether this client owns the player.
- `player.ready` — whether a live avatar is bound.
- `player.userId` / `player.identity` / `player.displayName` — the
player's account identity.
- `player.avatar = ref` — bind a live body entity as the player's body
(assign nil to clear). To use a `.bundle` / `.avatar` asset, spawn it
into the world first, then bind the resulting entity.
The player's identity entity is the internal anchor; the handle exposes the
body (`player.avatar`) and the player's data, and reaching for
`.entity` / `.id` / `.component` raises with a redirect to `player.avatar`.
## Building a scene
`build.luau` declares what the scene holds. It is ordinary engine code —
`entity.spawn`, `component.add`, transform writes, `for` loops, a `require`
of a module that computes a layout — and what it creates is what ends up in
the scene.
```lua
function content()
for i = 0, 4 do
local crate = entity.spawn("crate")
crate.localPosition = { i * 2, 0.5, 0 }
crate.component.add("Model", { model = asset.resolve("cube", "mesh") })
end
end
```
The build runs while you author, in **edit** mode, and what it created lands in
the live scene. Saving the scene bakes it into `scene.json`, which is what makes
the entities durable content: a human can select and inspect them, they
replicate, and they are there when the world opens without `build.luau` running
at all. Play mode never runs it — in play the entities load from `scene.json`
like anything else the scene holds.
**Editing the file rebuilds the scene in place.** Writing `build.luau` is the
signal; there is nothing to reload, and the rebuild saves. An entity keeps the
id it had, so a reference to it — a spawn naming a prototype, another entity's
component naming this one — survives every rebuild. Add a crate to the loop and
the other four do not move.
The write returns as soon as the file is on disk and the rebuild finishes behind
it, so what it landed comes back as a notice:
```
[info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main",
editorOnly="1" }
```
An edit saved while a rebuild is still running is an edit to code that rebuild
has already read, so it gets a rebuild of its own once that one finishes, and
says which it was:
```
[info] a write to build.luau arrived during a rebuild and was rebuilt after it
{ content="7", scene="scenes.main", editorOnly="1" }
```
Several edits saved during the same rebuild get the one run after it, which
reads the file as it stands then.
A scene that declares a build also runs it when it **loads** in edit, so the
scene shows what the code says now, including an edit made while the world was
closed. A load whose `.build.state` records the current script reads
`scene.json` as the build and runs nothing. When the load does run it, a
world's own scene saves the result, unless the scene holds unsaved edits: those
stay the author's to keep or discard, and the file write waits for their save.
A library scene (one under `/libs/`, the `@builtin` library included) is read
by its load: the build lands in the live scene and its files stay as the
library states them. Play reads `scene.json`, so it comes up without that build
until `:build()` saves it.
### The two surfaces
- `content()` — the scene's own entities. Present in play.
- `editorOnly()` — entities present while authoring and absent in play. They
carry the `EditorOnly` participation the runtime deactivates and hides when
play begins, and they are baked too, so a collaborator opening the world sees
the same ones. Anything an author needs to see and a player does not goes here
— an alignment guide, a spacing marker, a debug volume.
Both are optional. A scene with neither has no build.
### What a rebuild touches
Only the entities the build itself placed. Anything a human dragged in, or a
tool placed directly, is invisible to a rebuild and never moved or removed.
Within what it owns, the build is authoritative: an entity the code stopped
emitting is despawned, a component it stopped adding is removed.
The build writes its own name and each entity's place in the hierarchy onto the
entity, and `scene.json` records that pair beside the entity's name and
transform — which is why a rebuild after a reload, in a later session, lands on
exactly the entities it placed the first time without anything having been
remembered.
### When the file did not change
`:build()` runs the build against what it resolves right now — for the case
where something the builder *reads* changed and the file did not: a module it
requires, an asset it resolves. After a write it is unnecessary; the write has
already run it.
```lua
layers.active.asset:build() -- rebuild and save
layers.active.asset:build({ save = false })
```
It answers with how many entities each surface placed —
`{ content = 6, editorOnly = 1 }` — and with nil for a scene that has no
`build.luau`. Called while a build for that scene is already running, it returns
at once with `{ inFlight = true, scene, trigger, startedBy, message }` naming
that build instead of starting a second one; `inFlight` is what tells the two
answers apart.
An operation the bake cannot hold is **refused** rather than applied. A build
accepts what its records carry: entity lifecycle, transforms, hierarchy, names,
visibility, active state, participation mode, network scope, attributes, and
components with their public data. Anything else raises while the build runs,
naming the operation and the build it answered to, instead of leaving the scene
depending on something no reload brings back. When that happens the previous
build stays exactly as it was. A runtime resource a build needs — a mesh it
generates, a texture it writes — is made as an asset instead, below. Everything
else a refusal names goes outside the builder, or into a component the builder
attaches, which runs at play.
### The assets a build makes
`build.asset(type, name, produce)` makes an asset the build's content names — a
mesh a lathe produces, a texture a pattern writes. `produce` takes nothing and
returns the creation parameters `asset.create` takes for that type; the call
returns the asset's `AssetRef`, which is what a component field holds.
```lua
function content()
local tower = build.asset("mesh", "tower", function()
local positions, indices = lathe(profile, 16)
return { positions = positions, indices = indices }
end)
entity.spawn("tower").component.add("Model", { model = tower })
end
```
The asset is authored inside the scene's own folder — `Lobby.scene/tower.mesh`
— and the scene records which `build.luau` produced it in `.build.assets`. So
`produce` runs when the build script changed and never otherwise: a reload
re-runs the build and reuses the asset, while editing the profile re-authors
`tower.mesh` **in place**, keeping its path and its guid. That is what holds the
reference — `scene.json` names assets by guid.
For a part of a scene that several scenes place — or that one scene places many
times with different settings — see `guides { path: "types/sceneModule" }`,
which is the same idea with declared `inputs` a placement sets.
`guides { path: "core/scenes-as-code" }` covers both.
## The entrypoint
`entrypoint.luau` is the scene's **runtime** — what happens while the game is
being played. What the scene *is* comes from `build.luau` above; nothing here
has to construct it.
`entrypoint.luau` is auto-discovered as a sibling of `scene.json`. The
loader runs it in a fresh environment and folds its top-level
`function name(...)` declarations into the matching scene lifecycle event.
Define the callbacks the scene needs — the recognised set:
- `onLoad()` — the scene loaded in **play** mode. Gameplay-start hook,
runs on every connected client.
- `onHostLoad()` — the scene loaded in **play** mode, on the client that
owns the scene's synced content (the relay room creator; offline and
single-player count as host). Fires once. Entities spawned here — and
anywhere downstream — become synced automatically, so this is where
shared world content is spawned: it runs on exactly one peer, and every
other peer receives the entities from the relay snapshot.
- `onEditLoad()` — the scene loaded in **edit** mode. Custom per-scene
authoring tools. Writing this file while the scene is loaded in edit mode
reloads its layer, so the new `onEditLoad` runs after the previous load's
`onUnload`.
- `onUnload()` — before the scene's entities are torn down. Extra cleanup;
engine-managed teardown (entity despawn, resource release) runs
separately.
- `update(dt)` — per frame in play mode, while the gameplay clock
runs.
- `editorUpdate(dt)` — per frame in edit mode, running or paused.
Play-paused ticks neither hook. The scene loader partitions these
strictly on mode; a component's hooks of the same name read
`engine.paused` instead, so the two rules differ — `man components`
has that table.
- `localPlayerReady(player)` — once the local player's avatar is ready.
Gameplay wiring for the local player: attach state, bind UI, swap the
avatar. The avatar is already placed at the PlayerSpawn, so this is for
behavior, not positioning.
- `playerJoined(player)` — a remote player joined this scene's room. Use
for per-player UI (nameplates, greetings). The local player arrives
through `localPlayerReady`.
- `playerLeft(eid)` — a remote player left this scene's room. Receives the
departed entity's id (the entity is already despawned).
Each scene's entrypoint runs in its own environment, so two scenes can
declare the same top-level names without clashing. Keep each callback
short; push per-scene logic into `scripts/` modules and `require` them.
## Layers
Scenes load through the `layers` namespace.
- `layers.load(ref, opts?)` — load a scene. `ref` is a scene AssetRef or
identity string. Without `opts.additive`, this is a **root** load: it
replaces the current root scene. `opts`:
- `additive` — load as an overlay alongside the current root instead of
replacing it.
- `persistent` — keep an additive overlay mounted across mode flips and
root swaps.
- `origin` — a `{x, y, z}` world offset for the overlay's entities.
- `deferred` — spread the entity spawn across frames (for
thousand-entity scenes); the load signals complete only once the
scene has settled.
- `layers.active` — the current root scene proxy (nil before any load).
- `layers.list()` — every loaded layer (root + additive overlays).
- `layers.find(ref)` / `layers.is_loaded(ref)` — look up a loaded layer by
ref.
- `layers.onLoad(cb)` / `layers.onUnload(cb)` / `layers.onBeforeLoad(cb)` —
subscribe to every scene load / unload (distinct from a scene proxy's
own `:on_load` / `:on_unload`, which fire only for that scene).
A root scene carries the `players`, `camera`, and `settings` surfaces;
additive overlays inherit the root's players and lighting and do not carry
their own.
### The scene proxy
`layers.active` (and `layers.find` / `layers.list` entries) returns a
scene proxy:
- Fields: `.guid` (canonical identity), `.name`, `.path`, `.asset`,
`.additive`, `.visible`, `.state` (`"loading"` → `"loaded"` → `"ready"`
→ `"unloading"`), `.ready`, `.players`, `.camera`, `.settings`,
`.entrypoint`.
- `.camera` — a proxy over the scene's primary camera entity; read and
write the live Camera component through it, and
`.camera.behaviors._list()` enumerates the available camera behaviors.
- `:save(opts?)` — publish the live scenegraph to canonical `scene.json`
(see Saving). A convenience that forwards to the scene ASSET's `save`
(`self.asset:save(opts)`): the proxy is the runtime view and owns nothing
on disk, so persistence lives on the asset.
- `:reload()`: unload and reload the same scene (a runtime respawn). A scene
with a `build.luau` runs its build again and saves the scene, so `scene.json`
holds what the reload built and the next play loads it; a library scene's
rebuild lands in the live scene alone.
- `:clearDirty()` — discard unsaved edits and respawn from canonical.
Forwards to the scene asset's `discard` (`self.asset:discard(opts)`).
- `:sceneAsset()` — the durable `AssetRef<scene>` this live layer maps to.
- `:promoteDirty()` / `:writeDirty()` / `:hasDirty()` — manage the dirty
overlay directly.
- `:unload()` — despawn the layer and free its slot.
- `:onReady(cb)` — fire once the scene reaches `ready` (latched: a late
subscriber fires immediately).
## Multiplayer & relay rooms
Every scene has its own relay room, keyed by the world guid, the boot
profile, the mode, and the scene guid. Switching scenes with
`layers.load` runs a room transition — leave the old room, tear down,
join the destination scene's room — all on the client that made the call.
Teardown of the old scene never leaks to peers in the new one.
In play mode connected to a relay, the scene's entities are
host-authoritative: only the room creator instantiates them (marked
synced), and every joiner receives them from the relay snapshot rather
than spawning their own. This is why shared world content belongs in
`onHostLoad` — spawning it in `onLoad` would run on every peer and
duplicate it. Each player's own avatar spawns per-user from the
PlayerSpawn on every client.
Edit mode and offline boots spawn locally and never auto-sync.
## Loading and saving
**Loading** — `layers.load(ref)` for a root scene:
1. Despawns the current root scene's non-persistent entities.
2. Instantiates the entities from `scene.json` (including the player
prototype and spawn for a `"spawns"` scene).
3. Applies lighting and sky.
4. Runs `entrypoint.luau` and fires lifecycle callbacks as their events
occur.
**Saving** — persistence lives on the scene ASSET. `sceneRef:save()`
writes the scene's current state back to canonical `scene.json`; when the
scene is loaded it captures the live scenegraph, and when it is not loaded
it promotes the pending dirty overlay. `layers.active:save()` is the
convenience form — it forwards to the active layer's mapped asset
(`layers.active.asset:save()`). Writing canonical is the only path that
does so: edit ↔ play cycles never save, so hitting play to test never
overwrites the scene. Between saves, live edits accumulate in a per-scene
dirty overlay that the loader merges on top of canonical.
`sceneRef:discard()` throws the overlay away and restores the saved state
— deleting the overlay, and respawning the live layer when the scene is
loaded. It works whether or not the scene is loaded, because the overlay
belongs to the asset, not the runtime layer. `layers.active:clearDirty()`
forwards here. Saves capture entity data, not the entrypoint script —
edits to `entrypoint.luau` and `scripts/` are always preserved.
`opts.to` on `save`/`discard` targets a different scene ("save as"),
taking either a bare name (`"level_2"`) or a full VFS path.
**What a record states.** A component's record in `scene.json` holds the
fields that instance's configuration states: the keys of the table it was
added with (a `build.luau` call's own init table, or the record it was
loaded from) and every field written since, through code, a tool or the
inspector. A field nothing set stays out of the record and takes the
component's declared default each time the scene loads, so changing that
default reaches every entity that left the field to it. To have an entity
follow the default again, remove the field from its record. A field set on a
live entity after its record was made is a change the scene review names
(`sceneAuthoring.changes` lists it as `+ Type.field = value`), and accepting it
writes the field into the record. A scene saved
before records were stated this way holds every field; those values load
and save as they are, since a stored value cannot be told apart from one an
author chose, and a hot reload that changes a default one of them shadows
names it. A stored field the component no longer declares is named by a
`[component.add]` warning when the record loads and left out of the next
save.
## Lighting
Lights are ordinary entities: a directional light, an ambient light, and
a sky are entities carrying `Light` / `ProceduralSky` components in
`scene.json`. Author, move, and tune them like any other entity. If a
scene is missing any of {directional light, ambient light, sky}, the
loader adds a temporary default for the absent one so a scene never loads
dark or skyless; the defaults are never saved into the scene.
Scene-level lighting state that is not an entity — clear color and sky
descriptor — lives under `layers.active.settings.lighting` (`clear_color`,
`sky`); writing those fields updates the engine live.
## Modes
Scenes load in both edit and play mode (see `man modes`). The mode
governs behavior:
- An entrypoint's `update(dt)` runs in play while the gameplay clock
runs, and its `editorUpdate(dt)` runs in edit. A component's hooks of
the same name follow the clock rather than the mode — `man
components` has the four states that produces.
- Player prototypes are live in edit and deactivated + internal in play,
where each user instead gets a clone. `EditorOnly` entities follow the
same edit-live / play-internal toggle.
- `onLoad` / `onHostLoad` fire on a play-mode load; `onEditLoad` fires on
an edit-mode load.
## How to create one
```luau
asset.create("scene", "<Name>")
-- Creates /zero/source/<Name>.scene/ with:
-- build.luau where this scene's content is written. A new one starts
-- with the sun / ambient / sky lighting and the "spawns"
-- player setup, commented for editing — everything else the
-- scene comes to hold is written here too.
-- scene.json what that code produces, baked.
-- entrypoint.luau commented lifecycle-callback stubs.
```
A freshly created scene has a player with a following camera on the first press
of play. It carries no ground, so the first thing to author is what the player
stands on — a `content()` line away in `build.luau`.
## Discovery
- `asset.list("scene")` — every registered scene.
- `asset.inspect("<name>")` — entity count, lighting summary, source path,
and this type README.
## Authoring conventions
- Keep static layout in `scene.json` — geometry, lights, props, the player
prototype and spawn.
- Keep dynamic setup in `entrypoint.luau` lifecycle callbacks — event
listeners, gameplay state, services attached to spawned entities.
- Spawn shared, synced world content from `onHostLoad`; spawn each
player's own gameplay wiring from `localPlayerReady`.
- Set the world's startup scene in `/.world_settings` — that is the scene
the world boots into.
- Y is up; +Z is forward.
- Renaming the folder changes the scene's identity — update every
`layers.load` callsite and the world's startup-scene field.
## Related types
- `.bundle` — reusable entity hierarchies that scenes spawn into
themselves.
- `.service` — cross-scene background work that outlives a scene load.
- `.world_settings` — picks the startup scene and world-level renderer /
physics options.
## In the Inspector
Selecting a scene opens its **Scene** section, read from `scene.json` without loading the scene: how many entities it holds, how many of them are roots (and their names), how players join and the file's format version when it states them, and whether the scene has edits not yet saved.
# Particles.spawnBatches
The spawn batches a particle emitter keeps, as a min-heap on the clock each batch leaves the live bound at, and the count of particles they can still hold alive. An entry whose slots a whole capacity of later placements has overwritten holds no particle, and a sweep drops it, so the heap stays within twice the emitter's capacity whatever the particles' lifetime.
- `newSpawnBatches()` answers an empty heap.
- `pushBatch(b, leavesAt, count, capacity)` files a batch of `count` particles, the last of which leaves the bound at `leavesAt`, into an emitter of `capacity` slots.
- `batchesHeldAt(b, now)` drops every entry whose clock is at or behind `now` and answers how many particles the rest placed.
- `forgetBatches(b)` forgets every batch.
```luau
local Batches = require("@builtin::deprecated.deprecatedParticles.engine.spawnBatches")
local b = Batches.newSpawnBatches()
Batches.pushBatch(b, 2.0, 10, 100)
print(Batches.batchesHeldAt(b, 1.0)) -- 10
print(Batches.batchesHeldAt(b, 3.0)) -- 0
```
# Particles.spec
How the particle system reads an emitter spec. Each reader checks one field against the shapes it takes and raises a refusal naming the field and those shapes; `level` is how far out the refusal is reported, counted from the reader, so it lands on the call that wrote the value.
- `readRange(value, field, lo, hi, level)` reads a number or `{min, max}`, and `rangeArgs(min, max)` packs the two arguments a range setter takes.
- `readSize(value, fallbackSeq, level)` reads a number, `{min, max}`, a NumberSequence or a keypoint list.
- `asNumberSequence(value, fallback, field, level)` and `asColorSequence(value, fallback)` read a curve.
- `readBursts(bursts)` normalizes a burst schedule; `readDirection(dir)` a direction.
- `readNumber`, `readBoolean`, `readEnum`, `readVector` and `readTable` read one value of their kind, and `nameSet(names)` builds the set `readEnum` checks against.
```luau
local Spec = require("@builtin::deprecated.deprecatedParticles.engine.spec")
local lo, hi = Spec.readRange({ 1, 3 }, "lifetime", 1, 1, 2)
print(lo, hi) -- 1 3
```
# 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)
```
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 in the same package
#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. That is what
lets a module be renamed without breaking the shaders already written against
its old name: content persists the source it was authored with, so a name that
stops resolving is a world that stops publishing.
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.
## 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`.
# Material (asset type)
A material is a named, configured instance of a `.shader`. The shader
defines the surface look (lighting model, available property fields,
texture slots); the material picks values for those fields and a
shader to bind to. Renderable entities reference materials, not
shaders, so the same geometry can wear different materials and the
same material can be reused across many entities.
Entities sharing one material can still differ in a value: every drawn
object carries four `vec4` lanes of its own that a surface shader reads
as `input.shader_data[lane]` and `renderer.instanceData.set` writes. Use
that for a dissolve at its own progress per subject, a hit flash at its
own age, a fill level per instance — a material per entity is for when
the LOOK differs, not when a number does.
> New to how a material relates to its shader, its textures, and the live GPU
> material behind it? Read `core/resource-model` first. It also covers the
> difference between an authored `.material` asset (this type) and a runtime GPU
> material made with `renderer.material.create`.
## When to use one
- You want a named surface configuration an entity wears by referencing it
from its `Model` component (`material = "@.../<Name>"`).
- You want runtime property tweaks (`asset.resolve(ref):setProperty(...)`) to
affect every entity using the material at once.
- You want to publish a curated look (`Gold`, `RedGlow`,
`BrickWall`) other authors can reuse without re-typing shader
bindings.
If you need a brand-new lighting model or a custom visual effect, you
need a `.shader` first; the material wraps it.
## Where it lives
- Source: `/zero/source/.../<Name>.material/`
- Identity: `<Name>` (the `.material` suffix strips).
- Folder shape:
- `mat.yaml` — canonical material spec (shader + property values).
**Required.**
- `preview.png` — the material's rendered shader-ball still, its
persisted visual description. **Required.** Rendered when the
material is staged (`zm add`) with its preview missing or stale, and
by `generatePreviews`; it syncs, publishes, feeds image-based search,
and gives browsers a thumbnail.
- `README.md` / `.metadata` — optional prose + tags, indexed when an
author writes real ones.
- `textures/` — optional folder for embedded textures. Validator
allows the folder; its interior is unrestricted.
- `shaders/` — optional folder for a co-located custom shader.
Same rule.
## How to create one
```luau
asset.create("material", "<Name>")
-- Creates: /zero/source/<Name>.material/
-- mat.yaml (shader binding + property scaffold)
-- preview.png (rendered when the material is staged with `zm add`; the
-- picture lands as a change the next `zm add` stages)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("material", "<Name>", { folder = "materials" })
```
Pass the shader and initial values through `asset.create`, then tune with
`setProperty` and keep what you tuned with `saveDefinition`:
```luau
local mat = asset.create("material", "<Name>", { shader = "@builtin::shaders.pbr" })
mat:setProperty("base_color", { 0.8, 0.6, 0.1, 1 })
mat:setProperty("roughness", 0.3)
mat:saveDefinition() -- writes the tuned values into mat.yaml
```
This mints the `.material` asset and returns a handle you tune with
`setProperty`. A set is a runtime change: it reaches the GPU material and every
entity wearing it, and `saveDefinition` is the call that writes it into
`mat.yaml`, so a property driven every frame costs no file write and leaves the
authored file as its author wrote it. A purely runtime `asset.create` lives only
for the session.
For an ephemeral, runtime-only GPU material that is not an asset at all, use
`renderer.material.create` instead (see `core/resource-model`).
## How it operates
1. **Property reflection.** The bound shader's uniform struct fields
become the material's configurable properties — no manual property
declarations needed. `naga` introspects the shader at load.
2. **Property values.** `mat.yaml` groups values by type, each block
keyed by the shader's field names: `properties:` holds scalars and
colors/vectors, `ints:` holds integer-typed fields, `bools:` holds
boolean-typed fields, and `textures:` holds texture slots. Omitted
fields take the shader's default. A scalar is a bare number
(`roughness: 0.5`); a color or vector is an array
(`base_color: [1, 1, 1, 1]`). `shader:` is the shader's identity
string. This is the shape every material the engine writes uses. A
`saveDefinition` writes the changed values into the file where they
already stand and leaves the rest of it — its comments, the order of
its keys and blocks, the spelling of its literals — untouched. The older
`floats:` / `colors:` blocks (with `{ r, g, b, a }` map colors) still
load for materials hand-authored that way.
3. **Render state.** `render:` holds how the mesh is drawn rather than
what the shader reads: `blend` (the equation the fragment composites
with, also spelled `type`), `cull`, `depth_write`, `depth_compare`,
`topology` and `queue` (the draw order, a whole number: `2000` opaque,
`3000` transparent, `4000` overlay). The `.shader` type README's "The
render block" section lists every value each key takes, and
`asset.create`'s `render` argument takes the same keys and values.
4. **Application.** An entity wears a material by referencing it from its
`Model` component (`material = "@.../<Name>"`). Materials affect every entity
that references them; runtime `asset.resolve(ref):setProperty(...)` changes
propagate to all of them immediately, and last until the next mode change
unless `saveDefinition` writes them into `mat.yaml`.
5. **Texture binding.** Texture slots accept `color:r,g,b,a` for
solid colors, `default:white` / `default:black` / `default:normal` for the
engine's own fallback texels, `@builtin::textures.<name>` for builtins,
`path/to/image.png` for file textures, or a render-target handle
for camera renders. The GPU texture cache reads the `color:` and
`default:` forms from the string itself, so a slot written in one names no
asset and carries nothing with the material when it travels; every other
form names a texture asset the slot depends on.
A texture in `base_color_texture` is multiplied by `base_color`: every
built-in surface shader declaring both draws the texture's colour times
`base_color`, channel by channel. Under the default white `base_color` the
texture shows as itself, and a coloured `base_color` tints it. The two
read a colour differently: `base_color` is linear, and the slot reads its
texels as sRGB-encoded, a `color:` value's included, the way it reads an
image. A colour stated in both places is therefore multiplied by a darker
copy of itself: `color:0.62,0.14,0.05,1` in the slot decodes to
`0.34, 0.017, 0.0039`, so beside `base_color` `0.62, 0.14, 0.05` the
surface draws `0.21, 0.0024, 0.0002`, far darker than either. State a
solid colour once, as `base_color`, and leave the slot at its default
white.
6. **Hot reload.** Editing `mat.yaml` repacks the GPU uniform buffer
on the next frame; visible immediately.
7. **Inspector.** `type.yaml` names `inspector: { type: "inspector.luau" }`,
and `inspector.luau` declares the material's sections beside the generic
ones: `shader` (the bound shader, swappable), `properties` (each shader
field as its typed control) and `textures` (each texture slot as an asset
chip). They read the material through `mat:getShaderRef()` (the bound
shader's ref, `~` expanded) and `mat:getTextures()` (slot name →
`{ ref, name }`: the bound texture's guid and the id the material names
it by). An edit there is an authoring write: `mat:writeProperty(name,
value)` and `mat:writeTexture(slot, texture)` write the value into
`mat.yaml` (and drop the session's own value for it, so the material
reads what the file holds), and `setShader` rewrites the file; inside an
undo operation each file write is recorded, so undo puts `mat.yaml` back.
`setProperty` / `setTexture` stay runtime writes that last until the next
mode change.
## Discovery
- `asset.list("material")` — every registered material.
- `asset.inspect("<name>")` — shader binding, property values,
source path, this type README.
- `ls /zero/source/<Name>.material` lists the files the folder holds.
- `asset.resolve("<name>"):getProperties()` — the property fields exposed by
the bound shader, each at the value it currently holds: what `mat.yaml`
authored until something writes to the material, and the written value from
then on, whichever call wrote it. That is the value the surface is drawn
with. Read them back rather than guessing names; which fields exist comes
from the shader.
- `asset.resolve("<name>"):getDefinition()` — the authored `mat.yaml` bytes,
the value the material rests at.
- `asset.resolve("<name>"):getShader()` — the shader the material binds.
## Authoring conventions
- Use lowercase, descriptive names (`brushed_steel`, `red_glow`,
`tarmac_wet`). Avoid shader-name suffixes in the material name —
the binding lives in `mat.yaml::shader`.
- Drive every property the shader exposes; defaults are a fallback,
not a contract for which fields exist.
- Embed textures alongside the material (`textures/` subfolder) when
they're used only by this material; reference shared textures from
`@builtin::textures.*` or a library.
## Common pitfalls
- **Property names must match the shader's uniform struct exactly**
(case-sensitive). Misnamed properties silently get the shader's
default.
- **`base_color_texture` multiplies `base_color`.** A `color:` texture holding
the same value as `base_color` multiplies the colour by its own
sRGB-decoded value, so the surface renders far darker than the value
written. Write a solid colour as `base_color` alone.
- **Broken shaders break the material.** A material whose shader has a
parse error renders as the magenta checkerboard. Inspect the shader
first if the material looks wrong.
- **`setProperty` targets the material, not the entity.** Changes affect
every entity that references the material.
- **`setProperty` is a runtime change.** It reaches the GPU, not the file:
call `saveDefinition` to write the current values into `mat.yaml`. For a
per-entity override that no other entity sees, give the entity its own copy
with `Model:applySessionMaterial(renderer.material.create(...))`.
- **Renaming the folder changes the identity.** Update every `Model`
component and `asset.create` callsite that references it.
## Related types
- `.shader` — defines what properties exist; required before a
material can bind to it.
- `.preset` — captures a component configuration; conceptually
similar to a material, but for components instead of shaders.
# 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. | *(legacy)* An `@compute @workgroup_size(...)` entry over storage buffers — you write the `@group/@binding` lines yourself. **The canonical path is now the separate `.computeShader` assetType** (see below); `.shader` + `// @domain: compute` still compiles for back-compat. |
`// @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 are now 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`. The `.shader` compute domain above remains only for back-compat.
**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 legacy `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. `uniforms.*` (sun direction/colour,
ambient, `camera_pos`, `time`) and the punctual lights (`zero_point_light(i)`)
are always in scope; the shadow functions come from `#include "@builtin::shaderModules.shadows"`. 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 now `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 read |
|---|---|---|
| `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the `PbrSurface` too when the body hands one to `zero_pbr_shade` | the real channel where a surface was handed over; magenta, the "no data here" marker, where the body shades by its own math |
| `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the real channel |
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. A body that lights itself by its own math draws those
channels magenta. `pbr.shader` exposes `surface()`.
`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()`.
### 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;
}
```
#### 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; its geometry is culled against its undisplaced bounds.
### 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 to the camera |
| `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>` | ambient colour |
| `ambient_intensity` | `f32` | ambient intensity |
| `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 |
| `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), `normal`, `uv`, `color`, `time`.
`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
The common lighting state — the sun (`input.light_direction` / `light_color` /
`light_intensity`), the ambient (`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 one thing not
on `FragmentData` is the punctual-light array (its length varies), which is always
in scope:
| Expression | Type | Meaning |
|---|---|---|
| `uniforms.point_light_count` | `u32` | number of active point/spot lights |
| `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 with no PBR:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.shadows" // exposes compute_directional_shadow_factor
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 lit = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow;
// Point + spot lights (the punctual-light array, varying length).
for (var i = 0u; i < uniforms.point_light_count; i = i + 1u) {
let pl = zero_point_light(i);
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);
lit += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten;
}
// Ambient fill.
lit += input.ambient_color * input.ambient_intensity;
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
- **Unlit:** skip the lights and return your colour directly.
- **Toon / PS1 / custom:** start from the loop above and band, quantize, or warp
it however you like.
- **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes")
instead of writing the BRDF by hand.
## 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>` | sRGB colour, default is `[r,g,b,a]` |
| `int` | `i32` | |
| `bool` | `u32` | |
| `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) |
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 |
```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.
## 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 `all`, the picture after `__display__` with the UI 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. `opts.layer` names one
explicitly — `"all"` is what an effect that must grade the interface says.
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. `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, view-sized times its own `scale` — allocated on the
first draw and replaced whenever the size changes. `engine.params`, below,
carries the drawing pass's own index, its scale, 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
twelve passes — a threshold pass, five downsamples, five tent upsamples and a
composite — out of four entries, since the five downsamples share one and the
five upsamples share another, each level reading the one below it through
`zero_pass_input` and telling itself apart by `engine.params`. 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` declared on the last pass;
a `buffer` property (group(2) carries the pass inputs now); 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(d, near, far)` | `f32` | that sample as a distance in metres — the one inversion of the reversed range |
| `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 |
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. |
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.)
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) |
| `@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(...)` |
| `@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.depth` | `zero_linear_depth(depth, near, far)` — the one reading of a stored depth |
| `@builtin::shaderModules.gbuffer_material` (`zero::gbuffer_material`) | `struct ZeroGbufferMaterial { base_color, metallic, perceptual_roughness }`; `zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial`; `zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial`, `zero_gbuffer_base_color`/`zero_gbuffer_metallic`/`zero_gbuffer_roughness(t, coord)` — the one unpacking of `@scene.material`'s `Rgba8Uint` texel into what a surface reflects |
| `zero::scene_depth` | `zero_scene_depth(px: vec2<f32>)`, `zero_scene_depth_uv(uv: vec2<f32>)`, `zero_scene_depth_texel(px: vec2<i32>)`, `zero_scene_depth_size()`, `zero_scene_depth_is_sky(d: f32)`, `zero_scene_world_position(px: vec2<f32>)`, `zero_scene_world_normal(px: vec2<f32>)`, `zero_scene_depth_fade(px: vec2<f32>, world_position: vec3<f32>, fade_distance: f32)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The depth already drawn UNDER a surface fragment, and the world position and geometric normal of the surface standing there. What a decal projector box, a soft particle, a forcefield or water intersection foam shades against. Surface domain; the depth belongs to the view being drawn |
| `zero::scene_color` | `zero_scene_color(px: vec2<f32>)`, `zero_scene_color_uv(uv: vec2<f32>)`, `zero_scene_color_texel(px: vec2<i32>)`, `zero_scene_color_size()`, `zero_scene_color_refract(px: vec2<f32>, offset_px: vec2<f32>)`, `zero_scene_color_refract_uv(px: vec2<f32>, offset_fraction: vec2<f32>)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The scene colour already composed BEHIND a surface fragment, and the displaced read that bends it. What heat haze, a refraction shockwave, a cloaking or shield warp, glass and ice shade with. Surface domain; the colour belongs to the view being drawn, and is the lit opaque scene as it stood immediately before the transparent pass — so a `blend`-queue surface reads this frame's, an opaque one reads the previous frame's, and two overlapping blended surfaces both read the same picture and do not bend each other |
`asset.list("shaderModule")` enumerates the `.shaderModule` assets in this
engine, builtin and world-authored alike, and each one's README says what it
exposes. Those are the `@builtin::shaderModules.*` rows above; a module you
write is included exactly the same way, by its own identity or by the
package-relative `~.name` form.
The `zero::`-named rows come from the renderer itself. Their WGSL is baked into
the engine binary and registered under those names before any asset exists, so
they answer an `#include` in every engine and appear in no asset index. A shader
that includes one records no dependency on it: the engine reading the shader is
the engine that already holds the module.
Two spellings reach the same `.shaderModule`: an earlier name is kept working
through the module's declared alias, so a shader written against `zero::pbr`
still compiles and still pins the asset that name resolves to. Newly written
shaders should use the identity — it says which asset travels with the content.
Whichever punctuation an include is written with — `#include "name"`,
`#include 'name'` or `#include <name>` — names the same module and records the
same dependency.
The engine's own scaffolding — `zero::surface`, `zero::sky`, `zero::post`,
`zero::screen` — is injected by the compiler around the matching domain and is
never written by hand. The surface framework puts `safe_normalize`,
`mat3_from_mat4` and `apply_normal_map(FragmentData, tangent_normal)` in scope
for every surface shader.
## Shader features — compile-time variants
A **property** is runtime uniform data (a colour, a float, a texture): set per
material, read as `material.<name>`, no recompile. A **feature** decides which
code is in the program at all. Use a property when the value changes at runtime,
a feature when it changes what the shader is.
Declare features in `properties.yaml`, alongside the properties:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
features:
- { name: PARALLAX, default: false, description: silhouette parallax march }
- { name: DETAIL, default: true, description: detail-normal overlay }
```
Guard the code each feature owns with `#ifdef`:
```wgsl
fn surface(input: FragmentData) -> PbrSurface {
var s = zero_pbr_default_surface(input);
#ifdef PARALLAX
s.normal = parallax_normal(input); // absent when PARALLAX is off
#else
s.normal = input.world_normal;
#endif
return s;
}
```
`#ifdef` / `#ifndef` / `#else` / `#endif`, one per line, and they nest. The
directives resolve before the WGSL reaches the compiler, so the program holds
exactly the lines its feature set selected and every other line is an empty one,
which keeps a compiler message on the line number the file shows. An unbalanced
block is a compile error naming its line.
A material is what chooses a feature set, so `features:` shapes the shaders a
material draws with — the surface, sky and screen-space domains.
A material names the features it wants in its `mat.yaml`:
```yaml
name: worn_rock
shader: "@builtin::shaders.pbr_layered"
features:
PARALLAX: true # on, over the shader's default
DETAIL: false # off, against the shader's default
```
or through `asset.create`:
```lua
asset.create("material", "worn_rock", {
shader = "@builtin::shaders.pbr_layered",
features = { PARALLAX = true, DETAIL = false },
})
```
### A property that switches a feature on
A feature can also be switched on by a material's property values. List the
properties under the feature's `properties:`, and the feature is on for every
material whose value for one of them stands away from that property's declared
default:
```yaml
properties:
- { name: clearcoat, type: range, default: 0.0, min: 0, max: 1 }
features:
- { name: CLEARCOAT, properties: [clearcoat], description: the coat lobe }
```
```wgsl
#ifdef CLEARCOAT
s.clearcoat = material.clearcoat;
#endif
```
A material at `clearcoat: 0` draws a program holding none of the coat's code; one
that sets `clearcoat: 0.6`, in its `mat.yaml`, through `asset.create` or with
`renderer.material.setProperty`, draws the `CLEARCOAT` variant, and setting it
back to 0 returns it to the base program. The property stays a runtime value the
program reads; the feature decides only whether the code reading it is there.
This is how a shader with costly optional parts keeps every material that leaves
them at rest on the cheap program without each material having to name a
feature. A material naming the feature off under `features:` keeps it off
whatever the property holds. Write the guarded code so that, with the feature
off, the shader computes what it would with the property at its default: the
material sees one look either way, and pays for the part only where it shows.
Each distinct set of switched-on features is a program to compile the first time
a material reaches it. A material keeps the programs its values switched it onto
compiled while it lives, so a property crossing back and forth reuses them; when
the shader's variant budget is spent, the ones no material draws with are given
back first. A `properties:` entry is a value property (`float`, `range`, `int`,
`bool`, `color`, `float2` to `float4`) the shader declares; one naming no declared
property, or a texture or buffer, is refused by name.
The engine compiles one program per feature set its materials ask for, named
`<shader>#<features>`. Materials sharing a set share that program. A feature the
shader does not declare selects nothing, so a stray name cannot make the engine
compile anything, and the compile names both halves of a mismatch: a guard on a
name `features:` does not declare, and a declared name no guard tests.
**Permutations are the cost.** A shader with n features can express 2^n
programs, each its own compile and pipeline. One shader holds at most 32
variants; a material asking for a set past that draws with the shader's default
features and the engine logs which shader ran out. Read what a scene is
spending:
```lua
for _, s in renderer.shaderVariants() do
print(s.shader, #s.variants, "of", s.budget)
print(renderer.variantSource(s.base.program)) -- what it ships as
for _, v in s.variants do
print(v.program, renderer.variantSource(v.program)) -- what one asked for
end
end
```
A shader registers under every key it answers to — its identity, its guid, each
alias — and each key is a row. A variant lands on the row for the key the
material named, which for authored content is the guid, so take a program name
from the report rather than composing one.
## Materials reference shaders
A `.material` applies a shader to entities. Its `mat.yaml` references the shader by
its identity string and supplies property values:
```yaml
name: my_material
shader: "@builtin::shaders.pbr"
render:
blend: alphaBlend
cull: back
depth_write: false
floats:
roughness: 0.5
colors:
base_color: { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
textures:
base_color_texture: { ref: "default:white" }
```
`shader:` is a plain identity string, and each `colors:` entry is an
`{ r, g, b, a }` map — the two forms `mat.yaml` accepts for those keys. A key's
value is the rest of its line, so every value above stands alone on one.
### The render block
Render behaviour that used to be material "flags" — the blend equation, alpha
cutout, which faces are drawn — lives in the `render:` block and drives the
pipeline, not the fragment. These are the keys that reach the pipeline from both
authoring routes, and the values each one takes:
| Key | Values | Sets |
|-----|--------|------|
| `blend` | `opaque` `transparent` `alpha` `alphaBlend` `additive` `add` `cutout` `alphaCutout` `premultiplied` `premultipliedAlpha` `multiply` | the equation the fragment composites with |
| `cull` | `back` `front` `none` `off` `disabled` | which faces the rasterizer keeps |
| `depth_write` | `true` `false` | whether the draw writes depth |
| `depth_compare` | `less` `lessEqual` `lequal` `equal` `greater` `greaterEqual` `gequal` `always` `never` | the test a fragment's depth passes |
| `topology` | `triangleList` `lineList` `lines` `line` | what consecutive vertices assemble into |
| `queue` | a whole number: `2000` opaque, `3000` transparent, `4000` overlay | the draw order of the material; a number inside a queue orders within it |
`blend` is also spelled `type`, and the two name one key. Its equations, over
the fragment the shader returned (`src`) and the value already in the target
(`dst`): `opaque` is `src`; `transparent`, `alpha` and `alphaBlend` are
`src * src.a + dst * (1 - src.a)`; `additive` and `add` are `src + dst`, the
mode a glow, a light shaft or a spark card is written for; `premultiplied` and
`premultipliedAlpha` are `src + dst * (1 - src.a)`, taking a source that already
carries its own coverage; `multiply` is `src * dst`, which is how a soot, grime
or shadow card darkens what stands behind it. `cutout` and `alphaCutout` keep
the fragment or discard it on its alpha and go on writing depth.
The same block is what `asset.create`'s `render` argument takes, key for key and
value for value, so one material named in Luau and the same material standing on
disk ask for their pipeline with the same words. `depth_write` is the one key
whose value takes the shape of its route: the word `false` on a `mat.yaml` line,
the boolean `false` in the Luau table.
```lua
asset.create("material", "heat_plume", {
shader = "@builtin::shaders.pbr",
render = { blend = "alphaBlend", cull = "none", depth_write = false },
})
```
Where a value outside a key's set is reported is what the two routes differ on.
`asset.create` refuses the call on any of these keys and names the set it
measured the value against, or for `queue`, that it takes a number. A
`mat.yaml` standing on disk registers either way, each key falling back to a
value of its own: `blend` to `opaque`, `cull` to `back`, `depth_write` to
`true`, `depth_compare` to `less`, `topology` to `triangleList` and `queue` to
`2000`. The engine log carries the blend fallback, naming the value and
the set it was measured against, so a `mat.yaml` value is worth putting through
`asset.create` once — that is where every key answers with its set.
## Registration & hot reload
A `.shader` is compiled by the asset system, not by the renderer: writing
`shader.wgsl` or `properties.yaml` fires the `.shader` assetType's `onChange`,
which calls `shader.compile` — that reads the body + the property schema, generates
the group(1) interface and (for surface) every render-mode entry point, expands
`#include`s, **validates the result with naga**, and registers it. Validation
happens at this compile step — the whole point of "compile". A shader with invalid
WGSL (an unknown field, a type mismatch, an undefined function) **fails to compile**
with the real reason — readable directly from Luau via
`shaderRef:compileStatus()` (`{ status = "compiled" | "failed" | "pending",
error?, pending? }`), and also in the author log and `asset.inspect`; it is **not**
registered. This fires on create and on every edit, so saving a `.wgsl` recompiles
with no world reload; the change is visible on the next frame. Compilation is
async, so a `compileStatus()` of `"pending"` immediately after a write means check
again next frame.
A surface shader is also checked for the material resolve, the pass that
shades each pixel of the visibility buffer through the shader's own code. That
check reaches its verdict a few frames after the raster compile. Until it
does, `compileStatus()` reads `"pending"` with `pending` saying so, and the
shader already draws. A shader the check refuses reads `"failed"`, and `error`
names the construct the resolve cannot evaluate and where it sits; its pixels
resolve through the error shader until it changes.
The stage the compile checks comes from one of two places: the hook the engine
scaffolds entry points around (`fragment()`, or `surface()` for an engine-lit
surface), or the `vs_main` / `fs_main` pair the body writes itself. The pair is
a pair: a body that writes its own entry points owes both stages. A body
carrying neither route — a hook whose name is a letter off, say, or half a pair
— holds no stage the rasterizer can enter, so the compile **refuses it** and
names both the entry point it looked for and what the body carries, in the same
`compileStatus()` error every other compile failure reads back through.
### Reading a compile error against the text it is about
What the compiler reads is not the file you wrote. The engine generates the
group(1) material interface from `properties.yaml`, wraps the body in its
domain's framework and every entry point that domain needs, expands every
`#include`, and resolves every `#ifdef` — so a 100-line body reaches naga as
tens of thousands of lines. **Every line number in a compile error, and every
`[N]` handle index naga prints where it has no name to print, is a position in
that composed module.** A fault at module scope (`no definition in scope for
identifier: 'zero_scene_depth'`) reads fine without it; a fault inside a
function body does not.
`renderer.compiledSource(name)` returns that composed module, and
`shaderRef:compiledWgsl()` returns it for a ref you already hold. Both answer
for a shader that declares no features, needs no material, entity or draw, and —
the case they exist for — **answer for a shader whose compile failed**, holding
the text the compiler was refused over for as long as `compileStatus()` reports
that failure. `renderer.compiledShaders()` lists every name they answer for.
```lua
local ref = asset.resolve("myShader", "shader")
local status = ref:compileStatus()
if status.status == "failed" then
print(status.error) -- the line, the caret, and the cause
local wgsl = ref:compiledWgsl() -- the text those positions are in
local line = tonumber(string.match(status.error, "wgsl:(%d+):"))
print(string.split(wgsl, "\n")[line])
end
```
The composed text carries every `zero::*` module the shader included, so the
signature a call was rejected against is in the same text as the rejection —
which is the whole of what a "wrong argument type" error needs to be actionable.
A material bound to a broken (or missing) shader renders with the **magenta error
shader** — never invisibly — so a shader problem is impossible to miss on screen as
well as in the log. **Fixing the shader and re-saving recovers it live**, with no
engine restart: the recompile clears the failed-shader state and the object returns
to normal on the next frame.
## Discovery
- `asset.list("shader")` — every registered shader.
- `asset.inspect("<name>")` — domain, status, source, parse errors, this README.
- `shaderRef:compileStatus()` — did it compile? `{ status, error?, pending? }`, no
log needed. `"pending"` with `pending` set means the material resolve check
is still reaching its verdict; a resolve refusal reads as `"failed"`.
- `shaderRef:compiledWgsl()` / `renderer.compiledSource("<name>")` — the WGSL the
compiler received, which is what a compile error's positions index into.
Answers for a failed compile too.
- `renderer.compiledShaders()` — every name that call answers for.
- `shaderRef:getProperties()` — the parsed `properties.yaml` schema.
- `shaderRef:listMaterialsUsing()` — materials bound to this shader.
## Common pitfalls
- **A compile error shows up in one of three ways at the draw.** A shader that
never compiled has no pipeline, so the renderer binds the magenta placeholder.
A shader that compiled once and was then edited into brokenness KEEPS the
pipeline that build produced — the surface goes on drawing the last good
program, pixel for pixel, and looks entirely intact while the source is broken.
A geometry-pass-only shader has no magenta tell either, since it is not on a
forward mesh. `shaderRef:compileStatus()` gives the status + error text (as
does `asset.inspect("<name>")`), and `renderer.drawDiagnostics()` names which
renderables are in which of the three states — a row carries `substituted` for
the placeholder, `stale` for a program that no longer compiles, and the cause
either way.
- **A compile error's line numbers are lines of the composed module, not of your
file.** `renderer.compiledSource("<name>")` / `shaderRef:compiledWgsl()` is
that module; resolve the position against it rather than counting lines in
`shader.wgsl`. The `[N]` a message prints in place of a name is a naga handle
index — it moves with the size of the body and is the same value for two
unrelated faults in one file, so it is neither a line number nor a way to tell
two failures apart.
- **Don't declare group(0) or group(1) in a surface shader.** The engine owns
group(0) and generates group(1) from `properties.yaml`. Re-declaring them is the
fastest way to a layout mismatch.
- **`#include` does nothing by itself** — it only exposes functions; you must call
them.
- **Renaming a property** changes the generated uniform field; materials setting the
old name silently fall back to its default.
- **Compute shaders don't render** — verify output via a buffer readback or a
debug pass. Author them as a `.computeShader` (its own assetType), not a
`.shader` — see `man compute`.
## Related types
- `.material` — the required wrapper that applies a shader to entities.
- `.style` — UI cascade, not GPU shaders.
## In the Inspector
Selecting a shader opens its **Shader** section: its domain and shading model (and, for a post-process shader, the space its `fragment()` reads and returns), whether it compiled (and the compiler's error when it did not), a table of its declared properties (type, default, range), its post-process passes when it has any, the bindings it declares, and openers for its source. The **Materials** section (collapsed at first) has a Find materials action that lists, as links, every material drawing with the shader; it scans every material, so it runs only when asked.