# renderFeature
A **render feature** inserts custom GPU passes into the frame pipeline. The engine
provides one generic capability — a per-frame render-pass queue and a set of
pipeline-phase insertion points — and a feature is the authored Luau that decides
what passes to enqueue, and where, every frame.
## Authoring contract
A `.renderFeature` folder holds an `init.luau` that returns a feature module:
```luau
return {
setup = function(ctx) -- optional; runs once when the feature goes live
-- A "fragment" pass's `shader` names a POST EFFECT, not a `.shader`
-- guid directly — postprocess.add compiles the shader asset under
-- that name once, here. Enqueueing a name never passed to
-- postprocess.add runs the pass as a no-op every frame (the log
-- reads "effect '<name>' not compiled — pass skipped").
postprocess.add("my_effect", asset.resolve("my.shader.guid", "shader"), { enabled = false })
end,
render = function(ctx) -- required; runs every frame
-- enqueue one or more passes. The spec shape depends on `kind` (see
-- "Pass kinds" below): this is a "fragment" pass (full-screen shader over
-- input textures); a mesh effect (outline, x-ray) is a "geometry" pass
-- with `material` + `select` (see "Geometry passes").
ctx.enqueue {
phase = "afterTransparent",
shader = "my_effect",
inputs = { src = "@scene.color" },
output = myRenderTargetGuid,
}
end,
teardown = function(ctx) end, -- optional; runs once when the feature is destroyed
}
```
Optional `materials/` and `shaders/` subfolders hold shader source the feature
constructs GPU programs from. A feature constructs its GPU programs (it does not
reference `.material` surface assets).
## `ctx`
Built fresh each frame and passed to `setup` / `render` / `teardown`:
| Field | Meaning |
|-------|---------|
| `ctx.enqueue(spec)` | Queue one render pass for the current frame. |
| `ctx.viewport` | `{ w, h }`: the size the **main viewport's** scene rasterized at, in pixels (`renderer.rasterSize()`: the viewport taken down by the render scale). |
| `ctx.time` | The instant this frame's per-frame fields are drawn at, in seconds: the running clock, or the instant a `renderer.temporal.hold` pins. Absent in a feature that states its inputs. |
| `ctx.frame` | The frame index beside that instant: it counts every frame of the loop, drawn or not, and reads 0 while a hold stands. Absent in a feature that states its inputs. |
| `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. |
| `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". |
| `ctx.authored` | The same knobs as authored: a setting declared with `Field.scaled` reads its authored value here and the value of the quality level in force in `ctx.settings`; every other setting reads the same in both. |
### Per-frame values and a still picture
A buffer a feature's passes read is part of the picture: written with new words
between two frames, it is a change of the picture, and a renderer draws for as
long as such changes arrive. A field that animates with time (film grain, a
moving noise) seeds from `ctx.time` and draws while the clock runs. The jitter
an accumulation averages over (a ray offset, a rotated sample pattern) turns
with the renders of the view instead, so the feature's parameters hold the same
words on every frame of a still scene and the renderer stops drawing once the
accumulation settles: a history target's `state` buffer
(`renderer.texture.create { history = true }`) carries in `y` how many renders
in a row the view being drawn has carried, written as each render of the view
begins, and a pass that binds it reads its jitter frame there. While
`renderer.temporal.held()`, the passes take the frame from the held instant
`@frame.clock` carries instead (the feature states the hold among its inputs
and writes a flag into its parameters), so two renders under one hold agree.
`@builtin::systems.reflections.ssr` works this way.
## Stating what a feature depends on
A feature whose `render` gives the same passes while nothing it reads moved says
what it reads, and the engine stops running `render` on the frames where none of
it did. The module states the inputs with `dependsOn`, a list of names, with
`inputs`, a function returning a value, or with both:
```luau
return {
stage = "display",
dependsOn = { "settings", "viewport" },
render = function(ctx)
ctx.enqueue(specFor(ctx.settings, ctx.viewport)) -- a spec frozen all the way down
end,
}
```
| Input | Moves when |
|-------|-----------|
| `settings` | the feature's settings in force change: a `configure`, or a quality level that scales one. Every feature that states inputs holds this one, named or not. |
| `viewport` | the size the main viewport's scene rasterizes at changes (`ctx.viewport`). |
| `renderPath` | the active render path changes (`ctx.renderPath`). |
| `camera` | the camera drawing the viewport moves, turns or changes its projection (`ctx.camera`). |
| `camera.cell:<size>` | the camera's position crosses into another cell of `<size>` world units on a side, such as `camera.cell:2` (`ctx.camera`). |
| `assets` | an asset is created, changed or removed anywhere in the world. |
| `lights` | a light the renderer shades with changes: a field of a light component, a light entity's world transform (its own or an ancestor's), a light shown, withheld, spawned or removed, the sun or the ambient term (`lighting.revision()`). |
`inputs` is called with no arguments once a frame, and its value is compared with
the one of the frame before by `==`: a number or string that counts a revision, or
a table the owner replaces when its content changes (`debugViz` answers the batch
the debug module holds).
The first render, and a render after the feature restarts or the device rebuilds,
runs whatever the inputs say. Each later frame the engine reads the inputs: when
none moved, `render` does not run, and the passes the last render handed over
stand in the frame as they stood. A render's passes stand in the frame only while
every spec it enqueued is a table frozen all the way down (the engine reads such
a spec once and keeps it); a render that hands over any other spec runs on every
frame, whatever it states. `ctx.time` and `ctx.frame` are not there to read in a
feature that states its inputs, and `ctx.viewport`, `ctx.renderPath` and
`ctx.camera` are there only when an input names them: what changes on every frame
comes from the frame's own buffer, `@frame.clock`, which every pass binds. A
feature that states nothing runs `render` on every frame.
`renderer.feature.list()` and the profiler counts `renderFeature.renders` and
`renderFeature.replays` report how many features rendered and how many stood on
their kept passes in a frame.
## Settings
A feature declares the knobs it takes as `settings`, each a Field descriptor
with a default, the way a component declares its public fields. A feature that
declares no `settings` has nothing to tune: its schema is empty, and applying it
turns it on or off.
```luau
local Fields = require("@builtin::modules.field")
local Field, NoSync = Fields.Field, Fields.NoSync
return {
settings = {
intensity = Field.number(1.0, NoSync, "How much of the effect reaches the image."),
quality = Field.enum({ "low", "high" }, "high", NoSync, "How many samples the pass spends."),
},
render = function(ctx)
local s = ctx.settings -- { intensity = 1.0, quality = "high" }, or what a caller set
...
end,
}
```
The engine holds one settings table per live feature — every declared default,
overridden by what it was handed — and passes it as `ctx.settings` on every
`setup` / `render` / `teardown`. A feature reads its knobs there and nowhere
else, so any caller tunes any feature by name:
```luau
local h = renderer.feature.create(ref, { settings = { intensity = 0.5 } })
renderer.feature.configure(h, { quality = "low" }) -- lays over the rest
renderer.feature.settings(h) -- { intensity = 0.5, quality = "low" }
renderer.feature.find(ref) -- the live handle, or nil
renderer.feature.schema(ref) -- the declared knobs, unrun
```
A knob the feature does not declare, or a value of the wrong shape, is refused
by name. A scene authors its features on one `RenderFeatures` entity — a list
of features, each with its settings — which adopts a feature already live
rather than stacking a second, and takes every one down on disable and destroy.
Each entry is an application of its asset (`applicable`): the asset holds its
one live feature, every application joins it, the settings in force are those
of the application that last stated something new, and the last to leave stops
it. A feature already running when the first application comes is adopted, and
runs on with its own settings once the last leaves. A feature stopped from
outside the asset (`renderer.feature.destroy`, a
`render` that raised) stays stopped until an application is stated again.
`render` runs **once per frame**; the passes it enqueues run **once per render
target** drawn that frame — the live viewport, every offscreen capture, every
RTT camera — each at its own resolution. So `ctx.viewport` is the main
viewport's size, not the size of the target a pass ends up drawing into. Size a
full-screen scratch RT with `screen = true` and let the engine track the drawn
target (see "Screen-sized targets") rather than deriving it from `ctx.viewport`.
## Screen-sized targets
`renderer.texture.create { screen = true }` marks a feature RT as full-screen:
before each render target's feature passes, the engine resizes it to that
target's resolution. Create it once — the engine owns its size from then on:
```luau
myRt = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
screen = true, format = "rgba16f", name = "my_effect",
}
```
A target that holds a picture of the scene is `rgba16f`, which is what the scene
target itself carries: linear light with headroom above the display's white and
no 256-step floor under a dark gradient. Omitting `format` on a screen-sized
target asks for the same thing. `format = "rgba8"` is for a mask, a weight or an
occlusion term, where 0..1 is the whole range — hand one of those back over
`@scene.color` and the frame loses every highlight and bands every gradient, and
the engine says so in the log.
`screenScale` (default `1.0`) takes a fraction of the drawn target's resolution,
for a scratch that runs below composite resolution (a half-res blur passes `0.5`).
A screen-sized RT is what makes a full-screen effect composite correctly at any
resolution. Deriving the size from `ctx.viewport` instead pins the RT to the main
viewport, and every differently-sized render target then composites a mismatched
scratch — the scene scaled into a corner with the rest black.
`screenSpace` names WHICH image a screen-sized RT follows:
| value | what it tracks |
|---|---|
| `"scene"` (default) | the scene render target, at whatever resolution the render scale asked for. Resized before EVERY render target's feature phases — the main frame and each offscreen one — and cleared to transparent before an offscreen render, so one sink never reads what another left behind |
| `"composite"` | the image the post-scene phases draw into. The presented frame's allocation is resized and drawn by the presented frame alone; an offscreen render that runs a post-scene phase (a capture, a render-to-texture camera whose picture goes through the `display` stage) draws in an allocation of its own at its own size, cleared to transparent before it draws |
The two carry the same size until the render scale drops below 1. From there,
while the renderer presents the viewport itself, the scene reaches the display's
resolution through an upscale that runs before `afterScenePost` — so a
composite-space RT is the display's size while a scene-space one is the smaller
rasterized frame. Under a UI viewport panel the panel draws the scene target at
its own rect, nothing upscales beforehand, and both spaces carry the scene's
size.
A scene-space target is scratch: whatever a pass does not rewrite this render is
transparent black. The presented frame's allocation of a composite-space target
survives every offscreen render untouched.
## History targets
An accumulation across frames (temporal antialiasing, a temporal denoiser, any
pass that reads what it wrote last time) lives in a history target:
```luau
history = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
history = true, format = "rgba16f", name = "my_accum",
}
-- in render(ctx):
ctx.enqueue {
kind = "compute", program = myResolve,
inputs = { scene_color = "@scene.color", accum_previous = history.previous.guid },
buffers = { accum_state = history.state },
storage = { accum_out = history.guid },
phase = "afterLighting",
}
```
The passes a feature enqueues run once for every view the frame draws (the
viewport, each render-to-texture camera, each capture), so an accumulation has
to be one per view. A history target keeps one pair of images per view, sized to
that view: for the length of a view's render `history.guid` names the image the
render writes and `history.previous.guid` the image the same view's previous
render wrote. Another view never resizes, clears or overwrites them, and a
view's images are freed when it stops drawing. A capture drawing the picture
the viewport's latest render drew (its camera and lens, its size, the same of
the scene its layers admit, and its shading), while the viewport samples
where `renderer.setProjectionJitter`'s sequence places it, is the one render
that draws with another view's images: for the length of its render
`history.previous.guid` names the image the viewport's latest render wrote and
`history.guid` the viewport's other image, which the viewport's next render
writes over, and `history.state` reads as it would for that next render. A
viewport whose projection `renderer.setProjectionOffset` or a reconstructing
upscaler moves samples where no capture follows, and a capture then draws with
images of its own. It follows `screenSpace` and
`screenScale` like any screen-sized target; a composite-space one is kept for
every view that runs the post-scene phases: the viewport, a capture, and a
render-to-texture camera whose picture goes through the `display` stage.
Before each render of a view the engine writes `history.state`, one
`vec4<f32>` a pass binds through `buffers`:
| field | holds |
|---|---|
| `x` | 1 when `previous` holds this view's previous image; 0 on the view's first render, its first after a camera cut or a change of size, or after a render of the view that ran without the target, and `previous` then reads transparent black |
| `y` | how many renders in a row have carried the history |
| `zw` | this render's sub-pixel projection offset, in pixels (`renderer.setProjectionJitter`) |
`renderer.setProjectionJitter` is the matching per-view sample sequence: every
view walks it by its own count of renders, so the sequence a temporal pass
expects is the one each view's renders sampled.
## Post stages
A post effect belongs to one of the frame's named **post stages**, in frame
order, each stating what the picture holds there: the space an effect there
reads and writes (`light`, the scene's own light ahead of the display
transform's exposure and tone curve, `display`, code values, or `encoded`, the
presented surface's own values) and the size
the picture is held at (`raster`, the size the scene rasterized; `output`, the
size the frame is composed and shown at):
| Stage | Space | Resolution | Runs |
|-------|-------|------------|------|
| `lighting` | light | raster | screen-space lighting terms and what draws into the lit scene: occlusion, reflections, indirect light, contact shadows, decals, splats, outlines, diagnostic views. It spans every phase up to `afterLighting`, so a pass of a feature declaring it may name one of those phases |
| `medium` | light | raster | participating media: aerial perspective, fog, volumetric light |
| `preTemporal` | light | raster | effects reading the jittered raster before reconstruction: depth of field |
| `temporal` | light | raster | the one temporal reconstruction of the raster (TAA); the stage holds one feature at a time |
| `postTemporal` | light | raster | effects reading the reconstructed picture: motion blur |
| `meter` | light | reduced | measuring the picture: the exposure histogram, a fraction of the raster |
| `optics` | light | raster, then output | lens light: bloom, flare, streaks. Its render features run on the raster; the frame then carries the picture to the output size, and the post-process chain's `scene` layer runs there |
| `display` | display | output | the display transform, then on code values the temporal upscale, debanding, edge antialiasing and sharpening; the chain's `display` layer, the film grain last |
| `ui` | display | output | the UI, drawn over the finished picture, then what grades the picture with the UI on it: `afterUI` passes, the chain's `all` layer, then `afterPost` passes |
| `output` | encoded | output | the renderer's output stage alone: the one write of the presented surface, in the surface's encoding, rounded to its bit depth with a blue-noise dither (`renderer.output`). It takes no render feature and no chain effect |
A feature declares the stage it belongs to, and each pass it enqueues with no
`phase` runs in that stage, at the stage's phase and its band of orders plus the
pass's own local `order` (a whole number from 0 to 99):
```luau
return {
stage = "postTemporal",
render = function(ctx)
ctx.enqueue { kind = "fragment", shader = "my_effect", inputs = { src = "@scene.color" }, order = 0 }
end,
}
```
Passes sharing an order run in the order they were enqueued, so a chain of
passes over shared targets can run at one order, in sequence.
The `meter` and `optics` stages are the camera's film. A pass placed in one of
them, stating neither `postProcessing` nor `presented`, is part of the camera's
post-process chain (`postProcessing = true`): a camera running no
post-processing, such as a capture asking for the scene ungraded or an
environment cube face, skips it. A pass stating `postProcessing = false` runs on
every camera.
`render` runs once a frame, but each view the frame draws (the viewport, a
capture, a render-to-texture camera, an environment cube face) looks at the
world from its own camera, so an order that depends on where the camera stands
is stated per pass rather than chosen in `render`. A pass that composites
something standing in the world states the world point it stands at as
`sortPoint`: `{ x = .., y = .., z = .. }`, `{ x, y, z }` or a `vector`, so an
entity's `position` is one. Among the passes of one phase sharing one `order`
that run together (its fragment, compute and raster passes; its geometry
passes, which run ahead of those), the ones stating a point trade the places
they were enqueued in so that every view runs the one farthest from its own
camera first and the nearest last: composites laid over the frame by each of
them leave the nearest in front from wherever the view looks. Depth is
taken along the view (the distance in front of a perspective camera, the depth
into an orthographic one's box). Passes at the same depth keep the order they
were enqueued in, so the passes of one effect stating one point (a march into a
target and the composite reading it) stay together, and a pass stating no
point keeps its place:
```luau
for _, item in ipairs(items) do
ctx.enqueue { kind = "compute", program = march, storage = { out = scratch.guid }, order = 2, sortPoint = item.center }
ctx.enqueue { kind = "fragment", shader = composite, inputs = { src = scratch.guid }, blend = true, order = 2, sortPoint = item.center }
end
```
A draw or splat pass takes no `sortPoint`, and a value that is not three finite
numbers is refused by `ctx.enqueue`.
A pass may name a
`stage` of its own in place of the feature's, placed the same way: a feature
whose work spans two stages declares one and names the other on those passes,
the way temporal antialiasing declares `temporal` for its resolve and names
`display` on its sharpening passes. A pass naming both a `stage` and a `phase` is refused. A stage the
frame does not have is refused by `renderer.feature.create`, naming the stages
there are, and a second feature declaring the `temporal` stage while one stands
in it is refused naming both; the `temporal` stage takes the passes of the
feature declaring it alone. A pass that names a `phase` runs at that phase and
`order`, as below. `renderer.post.stages()` reports every stage and what stands
in it: a feature by the stage its passes' position falls in, marked `declared`
where that is the stage the feature declares or a pass names. Every built-in
render feature declares its stage; `postStages`'s README lists where each
built-in effect runs.
## Pass phases
`enqueue` runs a pass at a named pipeline boundary — a real seam between the
scene's discrete passes — ordered within a phase by `order`. Each phase is the
point where the scene colour holds a specific, nameable state:
| Phase | Scene colour there |
|-------|--------------------|
| `afterDepthPrepass` | the visibility raster written: `@scene.depth` holds this frame's complete opaque depth, and `@scene.motion` its opaque motion, before anything shades. Scene colour is not yet drawn; `@scene.colorHistory` holds the previous frame's lit colour, and the deferred g-buffer the previous frame's surfaces (`readsPrevious`) |
| `afterShadows` | shadow maps populated; scene colour not yet drawn. `@scene.depth` and `@scene.motion` hold what the visibility raster laid at `afterDepthPrepass` |
| `afterSky` | sky only. `@scene.depth` holds the frame's opaque depth, so a pass here tells the pixels the geometry pass draws over (depth above 0) from the ones that stay sky (depth 0) |
| `afterOpaque` | opaque drawn, before transparents. `@scene.depth` (and the deferred G-buffer) are populated. Forward: lit opaque. Deferred: lit opaque too, which the geometry pass shades straight into the scene colour, on a render no pass reads or writes `@scene.shaded` in; on one that does, the opaque surfaces are in the G-buffer's shaded channel, so the colour is still sky only until the composite (use `afterOpaqueLit`). Radiance stamped into `@scene.emissive` reaches the colour at the composite |
| `afterOpaqueLit` | the lit opaque scene, still before transparents, on **both** paths — the forward opaque draw, or the deferred geometry pass and composite. The background a refractive or transmissive surface samples: the one phase whose colour holds what is behind such a surface without holding the surface itself. A pass that lights or changes the opaque scene runs here, ahead of the air that hazes it (the aerial perspective at 98, the height fog at 100) and of the transparent phase: the built-in lighting terms (probe field, sky light, image-based environment, area lights, local contact shadows, surface weather, capsule occlusion, subsurface scattering, cached indirect, resampled direct, ray-traced shadows), the splat clouds and the outline shells stand at orders 1-96, so the haze covers their light and a see-through draw in front of a surface is not lit by that surface's light |
| `afterTransparent` | transparents drawn, before the OIT composite |
| `afterLighting` | deferred-lighting + OIT composite done — fully lit, final geometry on **both** paths. Where the air hazes the scene (aerial perspective, height fog), the opaque scene here is already hazed, so light a pass adds here lands over the fog and over every see-through draw |
| `afterScenePost` | the chain's `scene` layer and the display transform done: display code values, before the chain's `display` layer and the UI |
| `afterUI` | scene + UI composited |
| `afterPost` | the chain's `all` layer done — the finished picture in display code values, before the output stage writes it to the surface. A pass here reads that picture as `@scene.color` and draws over a copy of it |
The last three are the post-scene phases, and they work on the COMPOSITED image:
`@scene.color` there is the target the UI lands on, not the scene render target.
`@scene.depth` and `@scene.motion` still bind — they are the scene's own buffers
for the frame just drawn, which is what lets a pass at these phases reproject the
composite it is handed — and on the deferred path so do the G-buffer channels
(`@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive`), the
surfaces of that same frame, so a look drawn over the finished picture reads
what each pixel's surface is without copying the G-buffer at an earlier phase.
All of them keep the SCENE's resolution. Whenever the
render scale is below 1 on the presented frame, that is smaller than
`@scene.color`, so a pass here maps between the two by uv rather than by texel
index, and takes its own output size from the target it writes.
**A texture is a texture.** A pass's sampled input names any texture the engine
holds by the handle that made it: a render target or a texture
`renderer.texture.create` returned (its guid), or a storage texture a compute
shader created (`ref:createStorageTexture2D`, its `key`). Which one it is decides
nothing about whether the pass accepts it. A pass sees the contents a texture
holds when the pass runs: a compute shader that wrote the texture in an earlier
pass of the same frame, or in a `dispatchEx` recorded at the start of the frame,
is read by a pass at any later point of the frame, and a pass that reads a
target an earlier phase of the frame draws sees that draw once the phase has run.
The `@scene.*` inputs (`@scene.color`, `@scene.depth`, …) bind the live frame
buffers; the deferred g-buffer channels (`@scene.normal`, `@scene.shaded`, …)
resolve only on the deferred path. Before the pass that shades has drawn — at
`afterDepthPrepass` — a g-buffer channel holds the previous frame's surfaces,
and a pass reading it there names the slot in `readsPrevious`
(`readsPrevious = { "scene_normal" }`); one that does not is held back rather
than handed a stale normal. `@scene.colorHistory` is the lit colour the target's
previous render ended with, kept by the engine per render target and never
cleared by a frame: what a pass tracing at `afterDepthPrepass`, against this
frame's depth, takes its light from — reprojected through the previous
view-projection `@frame.camera` carries. A capture drawn once, or a camera drawn
again after a pause, is drawn lit first when a pass reads the history, so its
first frame holds one.
Every `@scene.*` channel, what it holds, its format, the phase it is first
valid from, and the other names it answers to:
| Name | Holds | Format | Valid from | Also named |
|---|---|---|---|---|
| `@scene.color` | the scene's lit colour; the display composite at a post-scene phase | the scene target's format at a scene phase, the display composite's at a post one | every phase | — |
| `@scene.depth` | opaque depth, reversed (1.0 near, 0.0 far/empty sky) | `Depth32Float` — binds through a `texture_depth` compute slot, not `texture2d` | `afterDepthPrepass` on | — |
| `@scene.motion` | screen-space NDC velocity since the previous frame | `Rg16Float` | `afterOpaque` on | — |
| `@scene.normal` | world-space normal + the per-pixel surface-flag field | `Rgb10a2Unorm` | deferred path, `afterOpaque` through `afterPost` (previous frame's before — declare `readsPrevious`) | — |
| `@scene.shaded` | what a surface SENT — its shaded colour, linear and scene-referred | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.albedo` |
| `@scene.material` | what a surface IS — base colour (RGB565) + metallic + perceptual roughness | `Rgba8Uint` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.mr` |
| `@scene.emissive` | radiance a pass stamped on the surface, added at the composite | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | — |
| `@scene.ao` | scene occlusion a feature wrote, read back by shading: occlusion in r, the bent normal laid flat on the octahedron in g and b, and in a whether a bent normal was written | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.sunOcclusion` | the share of the sun's direct light a feature found taken on the way to each pixel's surface (`.rgb`, 0 none to 1 all), read back by the sun's term alone | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.reflection` | traced reflection radiance (`.rgb`) + confidence (`.a`) | `Rgba16Float` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.indirect` | the indirect diffuse light the surfaces closing each pixel's hemisphere send it (`.rgb`, in the ambient term's units) + the share of the closed hemisphere it answers for (`.a`), read back by the diffuse term through `zero_scene_indirect_here`; the second layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | every scene phase (cleared at the top of every scene render) | — |
| `@scene.decal` | the base colour stamped over each pixel's opaque surface, premultiplied by its coverage (`.rgb`), with that coverage (`.a`); written at `afterDepthPrepass` (blend `premultiplied`), and every opaque surface takes it into its own base colour before it is lit (`zero_take_scene_decal`, which `zero_pbr_shade` calls), so the stamp is lit, shadowed and written to `@scene.material` with the surface; the third layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | `afterDepthPrepass` through `afterSky` (cleared at the top of every scene render and again once the opaque surfaces have shaded, so a surface drawn after them takes none) | — |
| `@scene.colorHistory` | the lit colour the target's previous render ended with | `Rgba16Float` | every phase | — |
| `@scene.media` | the media trace's coverage by kind: what the participating media and the see-through draws laid in front of each pixel's opaque surface, as the share the cloud layer covers (`.r`), a volumetric medium (`.g`: a volume, smoke, fire, a volume sequence, a fog bank) and a see-through surface (`.b`: every blended draw, such as water, glass, particles and cards, and a fluid surface) cover, premultiplied, with their coverage in `.a`. A blended draw covers the share of the pixel its blend equation changes: its alpha under `alpha` and `premultiplied`, the strength of the light it adds (its brightest channel, saturating at 1) under `additive`, and how far its factor departs from 1 under `multiply`. Each producer blends its trace premultiplied source-over what stands behind it, so the nearer hold the larger share. A view keeps it only while a pass reads it; a pass writing it alone runs only on such a view. `@builtin::shaderModules.media_trace` reads and writes it | `Rgba16Float` | `afterSky` through `afterPost`, the post-scene phases included (cleared at the top of every scene render) | none |
| `@scene.mediaSurface` | the distance from the camera to what covers each pixel (`.r`, world units) and its world normal laid flat on the octahedron (`.gb`; a medium states the direction back toward the camera), premultiplied by the coverage in `.a`; the second layer of the texture `@scene.media` is the first of | `Rgba16Float` | as `@scene.media` | none |
| `@scene.lights` | the punctual-light storage buffer: 1024 light entries of eleven vec4s each (the light, then its projection, which names the shadow record it casts through), the light grid, then the virtual shadow map's region: a shadow record per casting light and their page tables. A loop runs over the first `@frame.camera[4].w` entries, the lights in use; the buffer's length counts the regions after the lights too, so `arrayLength` does not size a light loop | storage buffer | every phase | — |
| `@scene.shadowPool` | the depth pool every shadow-casting light renders its shadow pages into, read beside `@scene.lights` through `@builtin::shaderModules.light_shadows` (`zero_light_shadow`): the shadow a point, spot or area light casts at any world point, the one the surfaces take. A frame with a pass reading it keeps the coarsest page of every map of each casting light whose reach meets the view | `Depth24Plus` — binds through a `texture_depth` compute slot | scene phases only | — |
| `@scene.sunShadow` | the sun's virtual shadow map as the view being drawn reads it: its basis, depth range, clipmap levels and window origins and where its page table starts in `@scene.lights`, read beside `@scene.lights` and `@scene.shadowPool` through `zero::sun_shadow` (`zero_sun_visibility`): how much of the sun reaches any world point, past the occluders that shadow the surfaces. A frame with a pass reading it keeps the sun's pages under the air the view looks through | storage buffer (`ZeroVsmUniform`, a `kind: buffer` slot with `array: false`) | scene phases only | — |
| `@scene.environment` | the reflection-probe cube array | texture cube array | scene phases only | — |
| `@scene.environmentSampler` | the filtering sampler for `@scene.environment` | sampler | scene phases only | — |
| `@scene.reflectionProbes` | the environment buffer: the probe blend data naming which probe reaches a point, then the irradiance light-probe volumes | storage buffer | scene phases only | — |
The rendering and ray-tracing guides (`guides { path = "topics/rendering" }`,
`guides { path = "topics/raytracing" }`) point here rather than repeating this
table.
**What a full-frame pass reads, at each stage, on each path.** A full-frame
pass is a fragment or compute pass of a render feature, or an effect of the
post-process chain (`postprocess.add`). The G-buffer channels above are what the
deferred path knows about each pixel's surface, and they are the four the paths
differ on:
| Channel | Deferred path | Forward path |
|---|---|---|
| `@scene.color`, `@scene.depth`, `@scene.motion` | every stage (depth and motion from `afterDepthPrepass` and `afterOpaque` on, as the table states) | the same |
| `@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive` | `afterOpaque` through `afterPost`: the `lighting`, `medium`, `preTemporal`, `temporal`, `postTemporal`, `meter`, `optics`, `display` and `ui` stages, and every layer of the chain. Before `afterOpaque` a pass naming one in `inputs` reads the previous frame's surfaces (`readsPrevious`), and the surface helpers read their stated substitute with `zero_scene_surfaces_drawn()` false | none: the forward path draws no G-buffer. A pass naming one as an input is skipped, and the log names the channel and the reason; every pass reading a render target that pass writes is held back in that view too, whatever the target holds from an earlier frame (`renderer.passSchedule().heldBack`), so a chain over the G-buffer composites nothing on the forward path. A shader reading one through the surface helpers reads its stated substitute (zero) and `zero_scene_surfaces_drawn()` reads false, so it draws a picture of its own there |
Two readers reach them. A pass names a channel in `inputs` (or a compute
binding), as above. A fragment pass's shader, or a chain effect's, reads them
by screen uv through the post framework's surface helpers (`zero_scene_normal`,
`zero_scene_material`, `zero_scene_shaded`, `zero_scene_emissive`; the shader
type README's post-process section has the table), which spend none of the
pass's input slots. Either way a render keeps a channel only when
something reads it: a queued pass naming it, a queued fragment pass whose
shader calls its helper, or a running chain effect that does. The channels
are at the scene's resolution, so a pass after an upscale reads them by uv.
A pass before the `temporal` stage reads each channel as the raster drew it,
with this render's sub-pixel offset. With temporal antialiasing running
(`@builtin::systems.antiAliasing.temporalAntiAliasing`), a reader after the
`temporal` stage reads `@scene.depth`, `@scene.normal` and `@scene.material`
restated at each pixel's centre, with no sub-pixel offset, so under a still
camera they hold still the way the resolved picture does: the restatements
run on a frame where a pass after them names the channel or a shader reads it
through its helper, and a chain effect reading the helpers is such a reader.
`@scene.shaded` and `@scene.emissive` keep the raster's sub-pixel offset at
every stage. `ctx.renderPath` names the path a feature's
`render(ctx)` runs on, and `postprocess.status()` lists, for each effect, the
channels it `reads` and, after a frame it drew with their substitute, the
`substituteReason`.
**Two g-buffer channels describe the surface, and they answer different
questions.** `@scene.shaded` is what a surface SENT — the colour the geometry
pass shaded it to, linear and scene-referred, so a surface lit above the
display's peak reads above 1 there. `@scene.material` is what the surface IS:
the base colour it reflects, its metallic and its perceptual roughness, each in
[0, 1] and each independent of how brightly the surface happens to be lit. A
pass that multiplies incoming light by a reflectance — a bounce multiplier, a
Fresnel tint, an ambient floor — reads `@scene.material`; a pass that filters
the picture reads `@scene.shaded`.
`@scene.material` is an `Rgba8Uint` channel packing all three into 32 bits, so
its slot declares `sample: uint` and the module unpacks it:
```yaml
# bindings.yaml
- { name: scene_material, kind: texture2d, sample: uint }
```
```wgsl
#include "@builtin::shaderModules.gbuffer_material"
let m = zero_gbuffer_material(scene_material, coord);
let bounce = incoming * m.base_color;
```
`@scene.albedo` is another name for `@scene.shaded` (the SHADED lit colour) and
`@scene.mr` for `@scene.material` (the material channel). The engine logs the
substitution once per name, naming the canonical one to write.
`@scene.motion` carries screen-space velocity: the NDC displacement each pixel's
surface underwent since the previous frame, so a still surface under a still
camera reads `(0, 0)`. Opaque geometry contributes it on both render paths:
the visibility raster writes it for every surface it records, and an opaque
surface whose depth state the raster cannot express writes its own where it
draws. A moving entity, a moving camera and an animated pose all reach it in
the viewport; transparents, particles and sky carry none. A surface a
material's `vertex()` hook displaces carries the displacement's own velocity. A render target's own camera and a
capture keep no view history, so velocity there is the entity's motion with no
camera term.
`@frame.camera` is a reserved **buffer** input carrying the camera CURRENTLY
being drawn: 18×`vec4<f32>` = the inverse view-projection (columns `[0..4)`,
column-major) + camera world position (`[4].xyz`, with the number of lights
`@scene.lights` holds in `[4].w`) + the previous render's view-projection
(columns `[5..9)`), which projects a point into the picture that render left +
the view-projection itself (columns `[9..13)`), which projects a world point
onto the view being drawn and is the matrix the scene rasterized with + the
sub-pixel offset that matrix carries (`[13].xy`, in NDC; zero without a
temporal upscale) + the view-projection with no sub-pixel offset (columns
`[14..18)`), the matrix the view's next render states as its previous one, so
a view drawn again from where its camera stands reads `[14..18)` word for word
equal to `[5..9)`. A compute pass declares a
`buffer` binding and binds it via `inputs = { name = "@frame.camera" }`, then
reconstructs a pixel's world position from `@scene.depth`:
```wgsl
let inv_vp = mat4x4<f32>(cam[0], cam[1], cam[2], cam[3]);
// ndc.z is the `@scene.depth` sample itself. Scene depth is reversed — 1.0 is
// the near plane, 0.0 the far plane and empty sky — and this matrix inverts
// that same range, so a sample goes in unmodified.
let wh = inv_vp * vec4<f32>(ndc, 1.0);
let world_pos = wh.xyz / wh.w;
```
Like `@scene.*`, the engine resolves it **per render target** — so the same pass
reconstructs against the live viewport's camera on screen and against an
offscreen capture's / RTT camera off screen. (Pack a camera matrix into your own
buffer instead and the offscreen render reconstructs against the wrong camera.)
> Render-feature passes run in the main viewport render **and** in offscreen
> captures / render-to-texture, each against its own camera. The `capture` tool's
> `source = "position"` / `"entity"` therefore run the pass queue too; using
> `@frame.camera` is what keeps those captures matching the live viewport.
### The view's matrices
`@frame.view` is a reserved **buffer** input carrying the view CURRENTLY being
drawn as the separate matrices a view-space algorithm is written against, which
`@frame.camera` states only as their product: 17×`vec4<f32>`, every matrix
column-major and none carrying a sub-pixel offset. Columns `[0..4)` hold
world-to-view; `[4..8)` hold view-to-clip, so `[4..8)` times `[0..4)` is
`@frame.camera`'s view-projection with no sub-pixel offset (`[14..18)`).
`[8..12)` and `[12..16)` hold the same two matrices as the view's previous
render drew with, the pair `@frame.camera`'s `[5..9)` is the product of; a view
with no previous render, or one that opens a new shot, states its own matrices
there. `[16]` holds the camera's near distance in `x` and its far distance in
`y` (both 0 where the view's projection is handed in whole, an environment
face, whose view-to-clip holds that whole matrix under an identity
world-to-view), and in `zw` the sub-pixel offset the render's projection
carries in pixels of the raster it is drawn at, along the NDC axes (x to the
right, y up; zero without a temporal upscale).
Like `@frame.camera` it is resolved **per render target**: the viewport, a
capture and a render-to-texture camera each read their own camera's matrices.
Its words differ from view to view and frame to frame, so a versioned pass that
binds it is refused. A pass that stands from frame to frame reads it on the
GPU like the other `@frame.*` buffers.
```yaml
# bindings.yaml
- { name: frame_view, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
let world_to_view = mat4x4<f32>(frame_view[0], frame_view[1], frame_view[2], frame_view[3]);
let view_to_clip = mat4x4<f32>(frame_view[4], frame_view[5], frame_view[6], frame_view[7]);
let near = frame_view[16].x;
let jitter_pixels = frame_view[16].zw;
```
```luau
inputs = { frame_view = "@frame.view" }
```
### The scene's light
`@frame.light` is a reserved **buffer** input carrying the scene's sun and
ambient term as the camera being drawn is shaded by them, the values the lit
passes read in the same frame: 3×`vec4<f32>` = the direction the sun's light
travels (unit, world space) with its intensity in `w`, the sun's colour with
`w` 1 while it casts shadows, and the ambient colour with its intensity in `w`.
A pass that lights a participating medium (clouds, haze, fog) reads its sun
here rather than carrying one of its own, so a day cycle, a scripted sun and a
sun switched off reach the medium in the frame they reach the surfaces, and a
scene with the sun and every light at zero leaves it black. `#include
"@builtin::shaderModules.frame_light"` reads it, and states the sun's light
either in the units the scene's lights are stated in
(`zero_frame_light_sun_irradiance`), for a medium that scatters those lights
too, or as the share of a medium's authored brightness the sun lights (its
intensity up to a unit sun, `zero_frame_light_sun_tint`):
```yaml
# bindings.yaml
- { name: scene_light, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
#include "@builtin::shaderModules.frame_light"
let light = zero_frame_light(scene_light[0], scene_light[1], scene_light[2]);
let toward_sun = zero_frame_light_toward_sun(light);
let sun = zero_frame_light_sun_tint(light) * authored_brightness;
```
```luau
inputs = { scene_light = "@frame.light" }
```
### The frame's clock
`@frame.clock` is a reserved **buffer** input carrying what the frame is doing:
3×`vec4<f32>`, the same for every view drawn in the frame. `[0]` holds the
shading time in seconds (the instant a `renderer.temporal.hold` pins while one
stands) in `x`, the seconds the frame advanced it by in `y`, that step in
sixtieths of a second in `z`, and the frame index in `w`, counted from the
engine's start and wrapping at 2^24 so a float holds it exactly (0 while a hold
stands, with a step of 0). `[1]` holds four values drawn uniformly from [0, 1)
by hashing the frame index: the seed a pass derives its per-frame random
rotation, jitter or sample offset from. `[2]` holds in `x` the wall-clock
seconds since the renderer drew its previous frame (at most 1), which runs in
every mode, paused play and a `renderer.temporal.hold` included: the step a
rate on the wall clock, such as an exposure adapting, advances by. A pass
reads these words, so a feature
whose passes stand from frame to frame writes none of them into a buffer of its
own, and states no `version`: a versioned pass that binds the clock is refused,
since the words differ on every frame.
```yaml
# bindings.yaml
- { name: frame_clock, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
let time = frame_clock[0].x;
let step_scale = frame_clock[0].z;
let frame = u32(frame_clock[0].w);
let seed = frame_clock[1];
let wall_step = frame_clock[2].x;
```
```luau
inputs = { frame_clock = "@frame.clock" }
```
### The environment
A compute pass reads the scene's captured surroundings — the reflection-probe
cube array, its sampler and the environment buffer (the probe blend data, then
the irradiance light-probe volumes) — through three reserved inputs, bound to
bindings of the shapes group(0) binds them in:
```yaml
bindings:
- { name: environment_map, kind: textureCubeArray }
- { name: environment_sampler, kind: sampler }
- { name: zero_environment, kind: buffer, access: read, element: ZeroEnvironment, array: false }
```
```luau
inputs = {
environment_map = "@scene.environment",
environment_sampler = "@scene.environmentSampler",
zero_environment = "@scene.reflectionProbes",
}
```
Named like that, `#include "zero::environment"` in the shader resolves the
environment at a world point along a direction — `zpbr_sample_environment(world_pos,
dir, lod)`, the probes whose radius reaches the point blended by rank and
proximity, each through its proxy volume, and the sky under them — exactly as a
material's environment term does, so a reflection a pass draws and one a
material draws agree about the room they are in. A pass that reads several
directions at one point selects the probes once, `let probes =
zpbr_select_probes(world_pos);`, and gathers each direction with
`zpbr_gather_environment_with_probes(probes, world_pos, dir, lod)`, which answers
the radiance in `rgb` and the share of it the probes and sky claimed in `a`.
The three bind at the scene phases; a post or UI phase carries none. A `textureCubeArray` binding takes
`@scene.environment` alone, and a fragment pass has no slot of that shape.
## Pass kinds
`enqueue` runs one of six kinds (the `kind` field; default `"fragment"`):
- **`"fragment"`** — a full-screen shader over input textures. The program is a
GPU **material** (or `shader`) the feature constructed; `inputs` bind live
textures (`@scene.*` or RT guids), `output` is the target RT (omit = the
phase's default scene target). Post-process, blur, edge effects.
**Writing named G-buffer channels (`outputs`).** Instead of the single `output`
RT, a fragment pass may declare an `outputs` array — one or more targets, each a
named engine channel (`@scene.shaded` / `@scene.normal` / `@scene.emissive` /
`@scene.color`) or an RT guid — each with its own blend mode:
```luau
ctx.enqueue {
kind = "fragment",
shader = myShaderKey,
outputs = {
{ target = "@scene.shaded", blend = "under" }, -- premultiplied dst-over-src
{ target = "@scene.emissive", blend = "additive" }, -- one fullscreen pass, two targets (MRT)
},
phase = "afterOpaque", -- deferred: G-buffer filled, before the composite
}
```
Blend modes — the keywords every pass's `blend` takes, `src` being what the
pass returns and `dst` what the target holds:
| Keyword | Result |
|---|---|
| `"replace"` | `src` — overwrites |
| `"alpha"` | `src.rgb * src.a + dst.rgb * (1 - src.a)` — straight-alpha source-over |
| `"premultiplied"` | `src + dst * (1 - src.a)` — source-over for a colour already multiplied by its alpha |
| `"additive"` | `src + dst` — sums |
| `"under"` | `src * (1 - dst.a) + dst` — premultiplied destination-over-source: what the target holds stays in front, which accumulates coverage-weighted contributions |
A keyword outside the table raises from `ctx.enqueue`, naming the field. A
`@scene.*` channel resolves only where it exists (the deferred
G-buffer at a pre-composite phase); a pass whose targets are all unavailable at
its phase is skipped (logged). `output` + `blend = true` remains the shorthand
for a single alpha-blended target. The shader's returned colour is written to
every target in the set.
A fragment shader returns `vec4<f32>`, so the channels it can target are the
float ones. `@scene.material` (also named `@scene.mr`) is
`Rgba8Uint`, which binds as `uint` — naming it as an output is refused by
name, with the channel's format and class in the log, and the rest of the
frame draws. A fragment pass's `inputs` reads through the same fixed float
slot, so naming `@scene.material` there is refused the same way; a compute
pass reads that channel through a `sample: uint` slot instead.
**What a pass with no `inputs` samples.** A fragment pass that declares no
`inputs` reads `@scene.color` — the shape of an effect that filters the scene
image. A pass that names `@scene.color` among its own `outputs` samples a 1x1
transparent texel instead, because the scene colour is that pass's render
target and one texture is a colour attachment or a sampled resource in a render
pass, never both. Declare `inputs = { src = "@scene.color" }` and write an RT
to read the scene image and write somewhere else in one pass.
- **`"compute"`** — a workgroup dispatch (`shader`, `storage`, `buffers`, `dispatch`;
see "Compute passes").
- **`"geometry"`** — draw scene geometry with a constructed pipeline. The program
is a **material** the feature built (`renderer.material.create`); the engine
draws the scene's render-objects with that material's pipeline + uniforms.
- **`"draw"`** — rasterize the feature's OWN geometry: `geometry` names a buffer
created with `usage = { "vertex" }`, `storage.index` one created with
`usage = { "index" }`, and `select` the one entity whose transform and
material the draw lands through. `params[0]` is how many indices to submit —
or name a buffer under `storage.indirect` (created with
`usage = { "indirect" }`, holding a `DrawIndexedIndirectArgs` block: index
count, instance count, first index, base vertex, first instance) and the count
comes from the GPU instead, so a compute pass that compacts geometry pays only
for what it kept and nothing waits on a read-back. `first_instance` must be 0;
the engine resolves the entity's per-instance data another way, because a
non-zero one needs a device feature WebGPU does not guarantee.
- **`"splat"`** — rasterize a compute buffer of particle records as instanced
camera-facing billboards into feature RTs (see "Splat passes").
- **`"raster"`** — draw geometry the feature makes itself with a `.rasterShader`
of its own: `vertexCount` vertices for each of `instanceCount` instances,
pulled from the buffers the pass binds, into the scene or the feature's
targets, depth-tested against the scene (see "Raster passes").
### Geometry passes
A geometry pass re-draws the scene's meshes with a material you supply — the
generic primitive for mesh-space effects (the engine names none of them):
```luau
ctx.enqueue {
kind = "geometry",
material = myMaterial, -- the HANDLE renderer.material.create
-- returned (or its registry-key string)
geometry = "@geometry.opaque", -- which drawables: "@geometry.opaque" |
-- "@geometry.transparent" | "@geometry.all"
select = { entityA, entityC }, -- OPTIONAL: restrict to these entities
-- (entity refs); omit = every matching mesh
phase = "afterLighting", -- afterLighting = lit scene + valid depth
}
```
`select` restricts the draw to the given entities — the per-instance signal that
turns a whole-scene pass into a chosen-meshes effect. A pass with no `select`
also draws the instanced populations (`renderer.mesh.drawInstanced`) its
`geometry` set takes, every copy at its own slot, so a whole-scene pass sees an
instanced forest as it sees the entities around it. The **material** decides how
those meshes are drawn; you control three things:
- **Pipeline render-state.** `renderer.material.create` takes a `render` block —
`cull` (`back`/`front`/`none`), `depthWrite` (bool), `blend`
(`opaque`/`alpha`/`additive`) — so the pass can rasterize differently from the
surface pass:
```luau
local myMaterial = renderer.material.create({
shader = myShaderKey, -- a .shader you authored (identity, not guid)
render = { cull = "none", depthWrite = false },
properties = { outline_color = { 1, 0.4, 0, 1 } }, -- seed the shader's uniforms
}, "my_pass_mat") -- pass `myMaterial` (or "my_pass_mat") as the pass `material`
```
- **The shader.** A geometry `.shader` is a surface shader: author `fn vertex(v:
VertexData) -> VertexData` to move vertices (object-local `v.position` /
`v.normal`) and `fn fragment(input: FragmentData) -> vec4<f32>` for the colour.
- **Its properties.** A shader reads ONLY the uniforms IT declares in
`properties.yaml`, via `material.<yourProp>`. Referencing a field it didn't
declare (e.g. a StandardMaterial `material.base_color`) fails to compile and the
mesh renders **magenta** — declare the property or use a constant.
What effect those three produce (outline, x-ray, wireframe, highlight, …) is
yours to design — the engine just draws the selected geometry with your pipeline.
#### What a pass starts its target from (`load`)
A geometry or draw pass with no `output` draws over the phase's own scene target,
which holds the frame as it stands. A pass naming an `output` render target begins
by setting that target's colour and depth to a starting state, and `load` says
which:
| `load` | the target starts as |
|---|---|
| `"clear"` (default) | empty: transparent colour and the far depth, so the target holds only what this pass draws |
| `"keep"` | what it holds: colour and depth as the last pass to draw into it left them, so this pass draws over that, depth-tested against it |
Two geometry passes naming one `output` therefore leave only the second one's draw
by default, since the second pass starts from an empty target. State `keep` on the
second to draw both, the way one camera draws many entities into one target:
```luau
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupA, phase = "afterLighting", order = 0 } -- starts from empty
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupB, phase = "afterLighting", order = 1,
load = "keep" } -- draws over groupA's
```
`keep` loads what the target holds when the pass begins: the draws of the passes
before it this frame, and the previous frame's picture where none drew it first
(and where a screen-sized target is made again, an empty one). The first pass to
draw a target each frame says `"clear"` so the target starts the frame empty; an
accumulation across frames is the one that says `"keep"` there too. `load` is
refused, naming the field, on a pass that is not a geometry or draw pass or that
has no `output`. A splat pass loads its targets with `blend = true`, and a raster
pass clears them with `clear = true`.
**How much of each mesh it draws.** A pass drawing into a small map (a
top-down cover or height map, a coarse occlusion mask) holds none of the
detail finer than a texel, and two fields keep it from paying for that detail:
- `detail = 1.0` states the world-space size of the finest detail its target
holds. Each static mesh then draws at the coarsest cut of its cluster
hierarchy whose error, placed at the object's scale, stays within that size,
the cut the scene's own draw takes for a distant object: a building keeps its
walls and roof and a tree its crown, in far fewer triangles than their full
detail. A mesh drawing from its own vertex streams (a skinned or morphing
mesh, one with no cluster set yet) and an instanced population draw in full.
- `rigid = true` leaves out every mesh a skeleton poses or morph targets blend,
so a crowd of characters costs the pass nothing.
`renderer.feature.drawn()` reads what each geometry pass drew on the last drawn
frame, as `{ objects, triangles }` keyed by its material, so the difference
either makes is a number.
**Where each surface stands.** A geometry pass draws every object through the
pass's own material, at that material's depth bias. `objectDepthBias = true`
adds to it the depth bias (`depthBias`, `depthBiasSlope`, `depthBiasClamp`) each
object's own material states, so a pass testing against the scene's depth meets
a decal or an overlay its material lifts toward the camera at the depth the
frame drew it at; the `zfighting` capture view counts surfaces this way. A clamp
either side states caps the sum, and a versioned pass stating it draws in every
view.
### Compute passes
A compute pass dispatches a `.computeShader` program over a workgroup grid:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
storage = { outTex = myStorageRtGuid }, -- slot -> storage-texture RT guid
buffers = { particles = "my_particle_buf" },-- slot -> named compute buffer
inputs = { camera = "@frame.camera" }, -- slot -> @frame.*/@scene.* buffer
dispatch = { x = 64, y = 1, z = 1 },
}
```
**`dispatch` is optional.** Omit it and the pass is dispatched over what it
WRITES: a grid covering its first `storage` texture, at the `@workgroup_size` the
shader's entry point declares. With a screen-sized storage target that grid
tracks the render target being drawn, so a screen-space effect covers the live
viewport, an offscreen capture and an RTT camera without the feature knowing any
of their resolutions:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
inputs = { scene_color = "@scene.color", cam = "@frame.camera" },
storage = { outTex = myScreenSizedRt.guid }, -- screen = true
phase = "afterLighting",
}
```
State an explicit `dispatch` for a grid that is not one thread per output texel
(a reduction, a particle sim), or when the shader's `@workgroup_size` is an
override/const expression the engine cannot read.
**`dispatch = { indirect = <buffer>, offset = <bytes> }`** takes the grid from the
GPU: the pass runs the workgroup counts (x, y, z, three `u32`) found `offset`
bytes into the named compute buffer (default 0; a multiple of 4), which a pass
earlier in the frame wrote. A scheduling pass counts the work that exists this
frame, writes the counts, and the passes after it dispatch over exactly that
work, so a pass that touches one object in ten costs the one in ten:
```luau
-- the buffer is created with usage = { "indirect" }; the first pass writes its
-- three counts, the second dispatches over them
local args = schedule:createBuffer("args", { type = "f32", len = 3, usage = { "indirect" } })
ctx.enqueue { kind = "compute", program = schedule, buffers = { args = args }, dispatch = { x = 1, y = 1, z = 1 }, order = 1 }
ctx.enqueue { kind = "compute", program = work, buffers = { items = items }, dispatch = { indirect = args }, order = 2 }
```
`indirect` takes the buffer's handle or its name. A pass naming a buffer that does
not exist, was created without `usage = { "indirect" }`, or holds fewer than
three `u32` from `offset`, is skipped with a warning naming the buffer. A count
of zero in any dimension runs no workgroups. The pass that dispatches from a
buffer does not bind that buffer as a writable storage binding (the GPU reads
the counts while the pass runs); each count stays within the device's
`max_compute_workgroups_per_dimension` (65,535 on the WebGPU baseline), so a
count past it is split over x and y by the pass that writes it. `dispatch` states
either `x`, `y`, `z` or `indirect`, not both. Native and the web build dispatch
the same way.
Each WGSL storage-buffer binding in the shader resolves its bound slot in this
order: an explicit `buffers` mapping (the handle a buffer's owner holds, or a
name), then `inputs` (`@frame.camera` / `@frame.view` / `@frame.light` / `@scene.lights` /
`@scene.reflectionProbes`), then — when a slot has neither — a buffer whose
engine-side name equals the slot's own name. `buffers`
is the seam a pass binds through: the buffers a shader works over are the ones
handed to it, whatever each is called. `storage` binds storage TEXTURES (RT
guids) the same way, one map per resource kind.
**A table built from a few settings.** A compute pass whose targets follow
from inputs that rarely change (a lookup table, a baked noise volume) states
the version of those inputs as `version`, a string or a number. The pass runs
in a view only while some render target it writes holds no picture this
program recorded at this version, so the table is built in the first view
after the version moves and skipped in every later view and frame:
```luau
ctx.enqueue {
kind = "compute", program = bakeLut,
buffers = { settings = settingsBuf },
storage = { lut_out = lutRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g", density, falloff),
}
```
A pass reading the table later in the frame reads the picture it holds. The
table is built again when the version changes, when the pass's own
`params`, `dispatch`, `buffers` or `storage` change, when the program's
pipeline is rebuilt (an edit to its source), when a render target it reads
through its `inputs` holds a new picture (so a table built from another table
is built again whenever that one is, and one built from a camera's target or a
video target whenever that target draws), when another texture it reads there
holds new texels, when a pass of any other version or none writes the target,
when the target is reallocated or cleared, and when the device reports an error
after the build was recorded. What the build reads from a buffer's contents or
from a value its program holds (`ref:setParam`) belongs in the version. A pass reading a
texture a GPU producer outside the texture cache writes, a 3D texture, or the
scene's acceleration structure and hit tables is built in every view.
**A table built from the view being drawn.** A table that follows the camera
too (a sky seen from the camera's altitude) binds `@frame.camera`, and names
what its program reads of the view in `viewReads`: `"@frame.camera.position"`
(the camera's world position, `@frame.camera[4].xyz`) and `"@frame.light"`
(the whole light buffer). The engine names the build by those values as each
view holds them, so the table is built in a view drawn from where it was not
built and stands in every view and frame drawn from where it was. `render`
runs once a frame and states what follows from the frame alone in `version`;
the engine adds what each view holds:
```luau
ctx.enqueue {
kind = "compute", program = skyTable,
inputs = { cam = "@frame.camera", lut = transmittanceRt.guid },
buffers = { settings = settingsBuf },
storage = { sky_out = skyRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g,%.17g", sun.x, sun.y, sun.z),
viewReads = { "@frame.camera.position" }, -- built again when the camera moves
}
```
Every view of a frame shares the target, so a capture or a render-to-texture
camera standing elsewhere builds the table for its own camera, and the next
view drawn from the viewport builds it again for the viewport's. The program
reads nothing else of the camera buffer: its orientation, its projection and a
temporal upscale's sub-pixel offset move from frame to frame and name n
# temporalUpscale
The settings behind the reconstruction, and the switch that starts it.
```lua
local Upscale = require("@builtin::systems.temporalUpscale.temporalUpscale")
Upscale.enable({ renderScale = 0.5 }) -- render at half, present at full
Upscale.enable({ sharpness = 0.5 }) -- retune; omitted fields keep their value
Upscale.get() -- what is in force, incl. the live scale
Upscale.active() -- whether the pass is running
Upscale.disable() -- release the pass
```
| field | effect |
|---|---|
| `historyWeight` | How much of the accumulation to keep each frame. Higher resolves more and settles smoother; it also takes longer to let go of what a surface used to look like. |
| `neighbourhoodClamp` | How far outside the current frame's own colour spread an accumulated sample may sit before it is pulled back in. |
| `sharpness` | How much of the edge lost to averaging — and to the interpolation that brought the frame up to size — is added back. |
| `motionRejection` | How much fast motion shortens the memory, which is what keeps a moving object from trailing behind itself. |
| `renderScale` | The fraction of the display's resolution the scene rasterizes at. Omit to leave it wherever it is. |
`enable` moves the render scale only when you pass `renderScale`, so a
dynamic-resolution controller (`@builtin::systems.renderScale.renderScale`)
keeps steering it while the reconstruction runs.
·computeshader · born here
❒asset # stable_depth
The scene depth a temporal reconstruction restates for the passes after it.
Each render's projection samples a different point inside every pixel, so the
raster's depth moves under a still camera by up to half a pixel from one render
to the next while the reconstructed picture holds still. An effect after the
reconstruction that draws from depth (an outline, a pattern laid on surfaces)
would move with the raster and not with the picture.
For every pixel this keeps one real depth sample: the one taken nearest the
pixel centre since the pixel last changed. A pixel keeps its sample while no
surface in its 3x3 neighbourhood moves on screen and the sample still lies
between the nearest and farthest depths that neighbourhood holds now; anything
else (a moving surface, a disocclusion, a view with no history) takes this
render's sample. Over one pass through the offsets a still pixel settles on the
sample nearest its centre and keeps it, so the depth is the same on every frame
of a still view.
## Bindings
| name | kind |
|------|------|
| `scene_depth` | `texture_depth` |
| `scene_motion` | `texture2d` |
| `stable_history` | `texture2d` |
| `stable_state` | `buffer` |
| `stable_offset` | `buffer` |
| `stable_out` | `storage2d (rg32f)` |
`stable_state` is the history target's state buffer, written by the engine
before each render of a view: `x` whether `stable_history` holds that view's
previous result. A render of the view that ran without the pass (a frame with
nothing reading the depth, a cut, a change of size) leaves it 0, so the first
render with the pass again takes its own sample everywhere. `stable_offset`
carries the render's sub-pixel offset in pixels in `zw`. When the engine moves
the projection (`renderer.setProjectionJitter`), every history state it writes
for the render carries that offset, and the writer binds another of its history
targets' states here: a dispatch binds each buffer at one binding. When the
writer moves the projection itself (`renderer.setProjectionOffset`), it binds a
buffer of its own.
`stable_out`
holds, per pixel, the kept depth in `x` and the squared distance of its sample
from the pixel centre, in pixels, in `y`. The distance is a square, never
negative, so its sign bit says whether this render kept the sample it held
(set) or took its own (clear), which `stable_surface` follows for the G-buffer
channels. Both words are the ones the render wrote, so the depth is the
raster's to the last bit. A fragment pass restating `@scene.depth`
(`restates = true`) hands `x` back to the frame. Both run on a frame where
something after them reads the depth, or `stable_surface` reads the kept
sample (`whenRead`).
# renderer
GPU-resource factory plus CPU codec/store wrappers — the GPU/CPU half of the asset↔resource split. Moves a resource Disk → CPU → GPU in explicit steps and returns inert handles describing each live resource. assetType behaviours, components, and every other module call `renderer.*`.
A resource moves through three states, each an explicit call:
- `ref:load()` → `renderer.<res>.loadCpu(ref)` decodes the asset's primary content into the guid-keyed CPU store and returns a CPU handle (holds only a guid plus dims/counts and the read/encode/unload ops).
- `renderer.<res>.create(cpuHandle | rawData, guid?)` uploads CPU → GPU, keyed by guid, and returns a GPU handle. `create` never takes an `AssetRef` — load the CPU first.
- `renderer.destroy(handle)` frees the GPU resource; a CPU handle's `:unload()` frees the CPU copy.
A `MeshHandle` / `TextureHandle` / `MaterialHandle` is an inert data record (`{ kind, category, guid, name, ... }`) describing one live GPU resource. Every GPU op lives on `renderer.*` and takes the handle.
Anywhere a call names a resource it takes any of the forms you already hold — the handle `create` returned, the CPU handle `loadCpu` returned, the guid, or the `AssetRef` `asset.resolve` returned. Handles compose: what one call hands back, the next call accepts.
## Types
- `Aabb` — `{ min = {x,y,z}, max = {x,y,z} }`.
- `MeshHandle` / `MeshCpuHandle` / `MeshGeometry` / `MeshBuffers`.
- `TextureHandle` / `TextureCpuHandle` / `TexturePixels`.
- `MaterialHandle` / `MaterialContent`.
## renderer.mesh
- `encode(geom) -> string?` / `decode(zmsh) -> (geom?, errmsg?)` — the ZMSH CPU codec.
- `loadCpu(ref) -> MeshCpuHandle` — Disk → CPU load (called by `meshRef:load()`).
- `create(src, guid?) -> MeshHandle` — create or fetch a GPU mesh from a `MeshCpuHandle`, raw geometry `{positions, indices, normals?, uvs?, colors?}`, compute buffers `{vertexBuffer, indexBuffer, vertexCount, indexCount, aabbMin?, aabbMax?}`, or a `MeshHandle`.
- `geometry(mesh) -> MeshGeometry` — the mesh's vertex data, the read that pairs with `create`.
- `update(handle, src) -> MeshHandle` — overwrite the GPU resource in place under the same guid.
- `readback(mesh, into?) -> MeshCpuHandle`: GPU → CPU recovery of a runtime mesh's geometry. `into` lands the copy under a CPU-store key of the caller's own, which stays resident until the caller unloads it, whatever re-registers or unloads the mesh itself.
- `isResident(mesh) -> boolean` / `isCpuResident(mesh) -> boolean`.
- `clusters(mesh)` / `scheduleClusters(mesh, opts?)` / `clusterBakes()` — the mesh's level of detail. Every static mesh draws through clusters, and a baked hierarchy of them (`kind = "dag"`) is cut by the GPU per view and per instanced copy, so detail falls off continuously with distance with no authored LOD meshes; `kind = "lod0"` draws full detail at every distance until a bake lands. `guides { path = "topics/world-detail" }` covers which meshes bake on their own.
Geometry moves in four directions, two per axis — DATA the caller holds, and the geometry of a mesh the ENGINE holds:
| From | → bytes | → geometry |
|---|---|---|
| geometry (data the caller holds) | `encode(geom)` | — |
| ZMSH bytes (data the caller holds) | — | `decode(zmsh)` |
| a mesh the engine holds | `encodeCpu(mesh)` | `geometry(mesh)` |
`geometry(mesh)` reads the resident CPU copy when there is one and reads the geometry back off the GPU when there isn't (yielding a frame or two), so a mesh straight out of `create` answers it:
```luau
local h = renderer.mesh.create({ positions = P, indices = I, tangents = T })
local geom = renderer.mesh.geometry(h) -- { positions, indices, tangents, ... }
```
An optional stream is present only when the mesh carries one. The GPU vertex layout has no "unset" — it holds a zeroed tangent, a zeroed skin binding, and a second UV set copied from the texture UVs for every mesh — so a stream saying only what its absence already says is reported absent. `geom.tangents == nil` is therefore the answer to whether a mesh has a tangent basis, and `geom.uvs1 == nil` to whether it has a second UV set.
## renderer.texture
- `encode(rgba, width, height, opts) -> (string?, errmsg?)` / `encodeFromImage(bytes, opts) -> (string?, errmsg?)` / `decode(ztex) -> (rgba?, width?, height?)` — the ZTEX CPU codec.
- `withSampler(ztex, { filter?, wrapU?, wrapV?, anisotropy? }) -> (string?, errmsg?)` — the same payload with only its recorded sampler state changed; every level is byte-identical.
- `loadCpu(ref, encodeOpts?) -> TextureCpuHandle` — Disk → CPU load with per-pixel access.
- `create(src, guid?) -> TextureHandle` — from a `TextureCpuHandle`, raw pixels `{rgba, width, height, srgb?}`, a `TextureHandle`, or render-target dimensions `{width, height, name?}` (an empty GPU texture a render pass writes into).
- `update(handle, src) -> TextureHandle`, `destroy(handle)`, `capture(handle) -> string` (CPU readback result key), `readback(texture) -> TextureCpuHandle`, `isResident(texture) -> boolean`.
## renderer.material
- `create(content, key) -> MaterialHandle` — register or update a material's GPU record (`content = { shader, properties, textures, aliases?, name? }`) under its canonical registry key.
- `animatedTexture(texture, opts?) -> MaterialHandle` — a material that PLAYS a layered texture: its layers bound as the frames, its timing beside them, the built-in `animatedTexture` shader turning the clock into the layer showing now. One call from an imported GIF / APNG / animated WebP to a material an entity can wear. `guides { path: "topics/animated-images" }` is the whole surface.
- `setProperty(key, name, value)` — push one changed uniform.
- `setTexture(key, slot, ref)` — push one changed texture slot (the texture must already be GPU-resident).
- `destroy(key) -> boolean` — drop the definition filed under `key`, so `describe` and `list` stop answering for it. A surface already wearing the handle goes on drawing it.
A `MaterialHandle` and its `guid` are two different currencies. What a surface wears is the HANDLE — `Model:applySessionMaterial(handle)`, or a Model's `material` field. The handle's `guid` is the material's registry key, which is what `setProperty`, `setTexture`, `describe` and `destroy` take. A component field resolves an asset, so a bare registry key in one leaves the component waiting for an asset to register under that name.
## renderer.instanceData
Four `vec4` lanes of generic shader data per entity — the channel that lets ONE material serve many entities that differ in a value, instead of one material per entity. A surface shader reads lane `i` back as `input.shader_data[i]`, and the engine attaches no meaning to what a lane holds.
- `laneCount() -> number` — lanes per entity, so a lane index runs `0 .. laneCount() - 1`.
- `set(target, lane, x, y?, z?, w?)` — write one lane of an entity's block. `target` is an entity proxy or an entity-id string naming a live entity; `y` / `z` / `w` default to 0. The lane reaches the block where the call is made, and the draw on the next frame.
- `clear(target)` — drop the entity's whole block, so its draws read zero again. Takes an entity that has already gone, and does nothing for one holding no block.
A lane index outside the block, or a target no live entity answers to, is an error at the call rather than a write that lands nowhere. A feature picks the lane indices it owns and names them where it writes them: `@builtin::systems.globalIllumination.lightmap` holds lane 0 for a receiver's atlas rect and lane 1 for its layer and enable flag, which is the shape to copy.
The same lanes reach a GPU-driven population through `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, on slots no entity owns.
## renderer.featureTexture
The texture analogue: a shared `rgba16f` 2D array every surface shader can sample as `zero_feature_texture(uv, layer)`, and the array a `SpotLight` projects a layer of through its cone via `cookieLayer`.
- `configure(width, height, layers)` — size the array. A call for the size it already has is left alone; one that changes the size reallocates, and the replacement is zeroed, so it empties every layer in the array — the layers other features and other cookies own along with your own.
- `setLayer(layer, textureKey, x, y)` — copy a GPU-resident `rgba16f` texture into one layer at that offset, GPU to GPU with no readback. Several small images pack into one layer at different offsets.
- `state() -> { width, height, layers, filled, fills }`: the extent the array carries and `filled`, the ascending 0-based indices of the layers a fill has landed in since it was last sized. One array is shared by every feature and every light cookie, and it has no allocator, so this is what a feature asks to tell whether the array it sized and filled is still the array it is writing into. A layer some other `configure` emptied leaves `filled` without it, which is what separates that from a fill that never landed. What it describes is the array a shader samples: the source texture a `setLayer` copied from is a GPU resource of its own and keeps the bytes it was written with, so `filled` is the reading that answers whether the layer behind a `cookieLayer` is live right now. `fills` counts the fills that have landed in each layer since the array was last sized, `fills[layer + 1]` for a 0-based layer: a fill of a layer already holding content leaves `filled` as it was and moves this count, so a feature re-filling its own layer reads its fill arriving here. Measured at the end of the last rendered frame, like every reader below.
```luau
renderer.featureTexture.configure(256, 256, 4)
renderer.featureTexture.setLayer(0, "my_gobo", 0, 0)
-- ... elsewhere in the scene, another feature sizes the array ...
local ft = renderer.featureTexture.state()
if ft.width ~= 256 or table.find(ft.filled, 0) == nil then
-- layer 0 was emptied under us: size it back and re-fill.
end
```
## Reading back what the renderer did
Every call above states an intention. What the renderer made of it is a separate
document, published once per frame and read through these:
- `drawDiagnostics() -> { DrawDiagnostic }` — every renderable that is NOT
drawing what its material says. A surface rendering as the magenta
placeholder, one the renderer could bind nothing for, and one drawing a
program whose most recent compile failed all land here, each naming the entity,
the program asked for, the program bound, and the one cause. It covers every
renderable the renderer holds, whether or not a camera reached it — a row with
`observed = false` and `outcome = "notDrawn"` is the renderer's own resolution
for one this frame drew nowhere, so a broken surface off-screen reads the same
as one in frame. An empty result means every renderable the renderer holds is
drawing the program its material named. **Start here when a surface looks
wrong.**
- `material.renderState(key) -> MaterialObservation?` — the blend / cull /
topology / queue / depth key the renderer holds a material under, and whether
a pipeline exists for it. `nil` means the renderer holds no material under
that key, which is what writes reaching nothing on screen look like. `index`
is the material index its row is filed under, and `textures` the texture key
each slot of that row names, so a `setTexture` the renderer has taken up
reads there.
- `materialCost() -> { MaterialObservation }` — draws, instances, placeholder
draws and material-owned bind groups (`binds` set, `bindsElided` skipped) per
material, over the published frame.
- `shaderCost() -> { ShaderCost }` — pipeline build time and permutation count
per program, summed since engine start, beside the compile gate's word.
- `observe() -> RenderObservation` — the whole document the four above read.
`/zero/runtime/generated_materials` serves the same document as files. Every
`notDrawn` row names why no pass reached it in `notDrawnReason`:
`meshNotResident`, `hidden`, `layer`, `culled` or `viewCull`.
## renderer.destroy
- `destroy(handle) -> boolean` — free the GPU resource behind a `MeshHandle` / `TextureHandle`, routing by the handle's `category`.
## Parts
The module is a folder of parts, each a module of its own that `init.luau` requires:
- `renderer.refs`: guid minting and the coercion from whatever names a material, mesh or texture to the key the renderer indexes it by.
- `renderer.sources`: the `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take, and the bounds and counts raw geometry implies.
- `renderer.shading`: the readings `renderer.shadingOf` builds out of the document the renderer publishes.
## Usage
```luau
local renderer = require("@builtin::modules.api.engine.renderer")
local gpu = renderer.mesh.create({ positions = { ... }, indices = { ... } })
renderer.destroy(gpu)
```
# asset Module
Public Luau surface over the `__asset` Internal FFI namespace —
asset resolver, ref envelope builder, sidecar metadata.
## Purpose
Wrap the raw `__asset.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.asset` via the prelude. Three families:
- **Lookup** — `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`. Every op accepts any name an
asset has (handle, guid, identity, path, bare name) and returns
the requested view.
- **Discovery** — `categories`, `list`, `containing`.
- **Generic `.metadata` sidecar** — `metadata`, `set_metadata`,
field-level `get_field` / `set_field` / `remove_field` /
`has_field`, tag helpers (`tags`, `has_tag`, `add_tag`,
`remove_tag`), and `validate`.
The previously-FFI `bundle.*` namespace was dissolved into the
bundle assetType (see `@builtin::assetTypes.bundle`);
that's not exposed here. The prelude mints `bundle` separately as
a thin Luau table grafted from `bundle_update`.
## Usage
```luau
-- Lookup
local cam = asset.resolve("@builtin::components.Camera")
local ref = asset.ref("animations.idle", "animation")
print(asset.identity(cam), asset.guid(cam), asset.source(cam))
-- Discovery
for _, c in ipairs(asset.categories()) do print(c) end
for _, sceneRef in ipairs(asset.list("scene")) do print(sceneRef.identity) end
local s = asset.containing("/zero/source/scenes/main.scene/scene.json")
-- Metadata sidecar (agent-editable)
asset.set_field(ref, "category", "movement")
asset.add_tag(ref, "looping")
print(asset.has_tag(ref, "looping"))
-- Structural validation
local v = asset.validate(cam)
for _, p in ipairs(v.problems) do print(p.severity, p.message) end
```
## Exports
- Lookup: `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`.
- Discovery: `categories`, `list`, `containing`.
- `.metadata` sidecar: `metadata`, `set_metadata`, `get_field`,
`set_field`, `remove_field`, `has_field`, `tags`, `has_tag`,
`add_tag`, `remove_tag`, `list_fields`, `list_field_values`.
- Validation: `validate`.
·computeshader · born here
❒asset # rcas
Robust contrast-adaptive sharpening of the shown picture, after the temporal
stage, on display-referred code values. Each pixel is recombined with its four
direct neighbours through a negative outer lobe whose strength is limited per
pixel so the result stays inside [0, 1], scaled by the sharpness, and then held
inside the range the pixel and its neighbours span: an edge gets steeper and
gains no halo on either side.
The pass writes only what is shown. The temporal accumulation never reads it,
so the sharpening is applied once per frame and does not compound.
## Bindings
| name | kind |
|------|------|
| `scene_color` | `texture2d` |
| `rcas_params` | `buffer` |
| `rcas_out` | `storage2d (rgba16f)` |
`rcas_params[0].x` is the sharpness in [0, 1], packed by
`@builtin::systems.antiAliasing.temporalAntiAliasing` or
`@builtin::systems.temporalUpscale.temporalUpscale`, whichever reconstruction
runs it.
·computeshader · born here
❒asset # taau_resolve
One composite-resolution pixel per invocation: read the presented frame, find
where its surface was last frame, and mix the accumulation into it.
The pass runs at a post-scene phase, where `@scene.color` is the composited
image — the display's own resolution while the renderer presents the viewport
itself — while `@scene.depth` and `@scene.motion` stay at the resolution the
scene was rasterized into. Every read of the scene buffers maps the composite
pixel back into that grid; the velocity it finds there is in NDC, which is the
same span at either resolution.
| binding | what it is |
|---|---|
| `scene_color` | the presented frame, composite resolution |
| `scene_depth` | scene depth, scene resolution, reversed (near = 1) |
| `scene_motion` | scene motion in NDC, scene resolution |
| `taau_history` | what this pass resolved for this view last render, composite resolution |
| `taau_params` | `(historyWeight, neighbourhoodClamp, sharpness, motionRejection)` |
| `frame_cam` | the camera drawing this view; `[13].xy` is the NDC offset this render's projection carried, which is what places each scene sample inside the pixel |
| `taau_history_state` | `(historyValid, _, _, _)` — the history target's own statement: 1 when `taau_history` holds this view's previous resolve, 0 on the view's first render and after a cut or a resize |
| `taau_out` | this frame's resolve, composite resolution |
Each 8x8 workgroup first reads the scene texels its pixels gather from into
workgroup memory, each once, then every pixel gathers its 4x4 from there. Every
scene texel is read out of the presented frame by four loads blended at its own
centre (one load at render scale 1, where the grids coincide), so reading it
once per block rather than once per pixel that gathers it is what keeps the
pass's reads set by the display's size.
Four things keep the accumulation honest:
- **Sample-position weighting.** Each of the 4x4 scene taps is weighted by how
far its own sample landed from this pixel's centre, jitter included, the
Gaussian taken as one weight per row times one per column — so a
frame that sampled elsewhere contributes little and one that sampled here
carries the pixel. Reading the same neighbourhood unweighted would average
away exactly the detail the jitter sequence is resolving.
- **Velocity dilation.** The velocity is taken from the nearest of the 3x3 scene
neighbourhood, so a silhouette sweeping across the pixel reprojects along the
surface that is actually moving over it.
- **Neighbourhood clipping.** The history is pulled toward the mean of the
current frame's own neighbourhood, along the line between the two, only as far
as it takes to enter the colour box that neighbourhood spans.
- **Motion-weighted feedback.** A long reprojection keeps less of the
accumulation, which is what stops a fast object trailing behind itself.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `interfaces:` | The interfaces every asset of the type implements (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
| `contexts:` | The environment the engine loads a file of the asset into, and what it holds (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export?, export_optional? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## Computed output files
A type can declare files produced by its compiler. Each rule names an exact
asset-relative output path, an activation marker, and guidance for editing the
inputs:
```yaml
computed_files:
- path: "cache.json"
when_exists: "authoring/state.json"
edit: "Edit the recipe and run the asset compiler."
```
Once the marker exists, ordinary writes, removal and individual-file moves are
refused for that output. The marker and output paths stay within the asset.
Declare their folders in `files.required` or `files.optional` as usual.
Compilers commit their outputs with the input revisions through
`modules.sourceOperations.materialize`. A complete asset copy to a new
destination carries its inputs and computed files together. Copying individual
files into protected outputs and merging a tree over protected outputs are
refused before destination leaves change.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. A type that lists `sceneInstantiable` under `interfaces:` guarantees it, and its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `implements`, `as`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
| `validateCommitted` | `(folder, read) -> { { code, message, severity?, remedy? } }` | On every push, for each asset the push changes, over the asset as the commit the push publishes holds it. `read(file)` answers a file's committed text, relative to the asset's folder, or nil for a file the commit holds no text of. A problem of `error` severity (the default) refuses the push, whatever the working tree holds. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
An asset whose picture is what it does to a scene rather than what it looks
like (a lighting setup) names a `subject` on an `instantiate` recipe: a
scene-instantiable asset stood in the studio in its place, while the asset
itself is applied to the world (`applicable`, owner `preview`) for the
shot and dropped after it. `studio_light: false` photographs the subject under
the world's lighting, which the applied asset states, instead of the studio's;
such a picture renders only on an explicit request (`preview.writePreview`,
`assets.generatePreviews`, staging), never from the preview queue or a live
preview.
```yaml
preview:
kind: instantiate
subject: "@builtin::preview.subjects.lookdev"
studio_light: false
```
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in, or a list of categories: a name
there is recorded as the one asset of those categories it answers to, a name
two of them answer to is recorded as neither, and a name written as a path
ending in one of their suffixes is the asset at that path.
A key whose names are assets of any type implementing an interface is stated
under `interfaceKeys`, and is declared typed to the types that implement the
interface, again whenever a type or an interface changes:
```yaml
references:
interfaceKeys:
- { key: "members", implements: applicable, field: "source" }
```
`asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
A JSON or YAML data file of your type is read whole for the references it holds:
every `{ __ref }` envelope, `@` identity and `components` entry in it. When a file
also keeps values that are data rather than links (an edit history holding the
asset a field used to name, say), `documents` names the fields that carry its
links, and the rest of the file is read as data:
```yaml
references:
documents:
- path: authoring/entities/ # every file under this folder of the asset
fields:
- [records, "*", references] # keys from the root; "*" is every entry of a list or mapping
- references
- path: authoring/settings.json # this one file
fields: [references]
```
`path` is inside the asset's folder; the longest `path` covering a file decides
it. Each value a field reaches is read whole. A file that holds none of the
fields is read whole, as is every file no `path` covers. An entry with no valid
`path` or `fields` is refused with a warning naming it.
## What your type guarantees (`interfaces:`)
An interface is an asset (`<name>.interface/`, see the `interface` type) that
states a guarantee: members with signatures, and properties. A type lists the
interfaces its assets implement in its `type.yaml`:
```yaml
interfaces: [sceneInstantiable]
```
Every asset of the type implements every interface the type lists; an asset of
a type that lists nothing never does. The key is a reference to `interface`
assets, so each name resolves like any asset name and is recorded by guid in the
type's reference table, which is where the engine reads the type's marks from.
The `indexing:` role named `interface` is a different thing: it names the file
that states the signatures a caller of an asset uses.
The type meets each member in its `behavior.luau`, implicitly with its own
`M.ref.<member>` of the member's name and signature, or explicitly when its own
method of that name means something else:
```lua
M.ref = { apply = function(self, into) ... end } -- the type's own meaning
M.interfaces = {
applicable = { apply = function(self, owner, values, opts) ... end },
}
```
`M.interfaces` is keyed by the interface's name as the type lists it. A property
the interface states is met by a value or a getter `(self) -> value` in the same
two places, else by the interface's default. A type whose own `<member>` is
shared by two interfaces with different signatures meets at least one of them
explicitly.
| Question | Call |
|---|---|
| Does this asset implement X? | `ref:implements("X")` (a name, identity or guid, or a list meaning any of) |
| Call a member through the interface | `ref:as("X"):member(...)`; `ref:as("X").property` reads a property |
`ref:as("X")` raises, naming the asset and `X`, when the type does not implement
it. A direct `ref:member(...)` reaches the type's own method of that name; when
the type meets the member implicitly, that method is the member and the call goes
through the interface's gate, which checks its inputs and its result. A generic
caller (one that knows only the interface) calls through `:as`.
A declaration that breaks a check is refused: it carries no marks, `asset.validate`
reports each problem as an error that refuses a push, and the engine log states
each once. The codes are `interfaces.shape`, `unknown`, `ambiguous`, `duplicate`,
`missing`, `arity`, `typeKey`, `explicitUnclaimed`, `explicitUnknown`,
`propertyMissing`, `propertyType`, `conflict` and `unloadable`; each message names
the type, the file, the fault and what to write instead. A type that defines
`instantiate` and lists no `interfaces:` (one written before the key existed, or
defined by its `behavior.luau` alone) implements `sceneInstantiable` with the
warning `interfaces.implied`, which names the line to add. `asset.inspect` of an asset lists the interfaces its type
implements, and of a type definition lists them under `detail.interfaces` with
`detail.interfaceProblems` when the declaration was refused. The type's
Inspector shows the same under **Interfaces**: one row per interface (its name,
the first line of its description, and whether the type declares it or it is
implied), then every problem the declaration raised. An interface's own
Inspector shows its guarantee, its contract module and conformance suite, every
member with its signature, inputs and output, and the types that implement it.
The asset browser's **Implements** filter narrows the list to the assets whose
type implements the interface chosen, each interface's description as its
tooltip.
## The environment a file runs in (`contexts:`)
A type whose assets hold a script the engine loads itself states the environment that script runs in, so the engine binds it and the language server checks the script against the same names:
```yaml
contexts:
- name: sceneBuild
file: "build.luau"
surface: "scene's `build.luau`"
globals:
build: "the build surface is bound in a scene's `build.luau`'s own environment, where `build.asset` authors ..."
hooks: [content, editorOnly]
modules: true
```
- `name` is the context's name.
- `file` is the file of the asset folder that runs in the context.
- `surface` names that file in a diagnostic, without an article.
- `globals` are the names the type's loader binds into each run of the file. Each carries the note an unknown-global message gives when the name is used in a file that lacks it.
- `hooks` are the functions the engine calls by name from the file, which the language server does not report as unused.
- `modules: true` says the loader binds the exports of the modules that join the context.
A module joins with `--!context <name>` in its leading comment block. The type's loader builds the environment with `ScriptContext.bind(env, path, values)` (the `script_context` module), which refuses a value the context does not declare. `asset.context(path)` reads the context a file runs in.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# Module (asset type)
A module is Luau code that runs when other code calls it: other code
pulls it in with `require()` and calls its functions. It has no
lifecycle hooks or callbacks; nothing attaches it to an entity or runs
it every frame. Anything that is code can be a module: a whole game
system (rules, an inventory, a level generator, a match flow), a
helper, a format parser, a registry, a shared algorithm. The engine's
own APIs (`physics`, `input`, `audio`, `camera`, `entity`, `asset`,
`http` and the rest) are modules.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the code runs on an entity, driven by hooks and callbacks, use a
`.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# temporalUpscale system
Render fewer pixels than the display has, and get the display's pixels anyway.
Shading cost scales with pixel count, so rasterizing the scene smaller is the
one lever that buys frame time without taking anything out of the frame. What it
spends is sharpness: an upscale invents nothing, and one frame carries only as
many distinct samples as the scene had pixels.
This system spends the frames instead. The projection samples a different point
inside every pixel each frame, so consecutive frames are different estimates of
the same continuous image; the reconstruction carries them forward through the
scene's own motion vectors and mixes each new one in. After a handful of frames
the standing result holds samples from several different grids — detail no
single frame ever rasterized.
## Using it
Put `TemporalUpscale` on any entity in the scene:
```lua
entity(id).component.add("TemporalUpscale", { renderScale = 0.5 })
```
Half the scale is a quarter of the pixels. Every field is live: edit
`renderScale` in the inspector and the scene rasterizes at the new size from the
next frame. Removing the component puts the render scale back where it was
before the component moved it, so the frame returns to the resolution it had.
### The visibility raster
The visibility raster rasterizes through the same sub-pixel offset this pass
moves the projection by, so the depth and motion it lays describe the image the
resolve shades.
For code that wants it without a component — a settings screen, a benchmark —
reach for the module:
```lua
local Upscale = require("@builtin::systems.temporalUpscale.temporalUpscale")
Upscale.enable({ renderScale = 0.5, sharpness = 0.35 })
Upscale.get()
Upscale.disable()
```
Leaving `renderScale` out of `enable` leaves the scale where it is, which is what
lets `@builtin::systems.renderScale.renderScale` keep steering it against a frame
budget while the reconstruction runs.
## Where it runs
The reconstruction is a compute pass at the head of the `display` stage
(`afterScenePost`), ahead of the debanding, edge antialiasing and sharpening
the stage then lays on it: the seam where the
frame has already reached the display's resolution and the UI has not been
composited onto it yet. So the scene is reconstructed and the text over it stays
untouched, drawn once at the display's own size.
Its accumulation is a history target created with `screenSpace = "composite"`,
which is what keeps it the size of that composited image while the scene renders
smaller. Every view accumulates in images of its own: an offscreen render (an RT
camera, a `capture`) runs the reconstruction on its own picture and leaves the
viewport's accumulation as the viewport left it. The scene's depth and velocity
stay at the scene's resolution; the pass maps each composite pixel back into
that grid to read them.
Where the composite lands depends on who presents the viewport. In a runtime
session the renderer presents it, and the upscale to the display's resolution
happens before `afterScenePost` — so the composite is the display's own size and
the reconstruction resolves onto the display's grid. Under a UI viewport panel
the panel draws the scene target at its own rect, nothing upscales before the
composite, and the two spaces carry the same size: the pass then accumulates at
the render resolution and the panel scales the result. It says so in the log on
the second frame when that is what it finds.
## The resolve, and the sample sequence
The reconstruction folds each frame in through the temporal resolve
(`@builtin::systems.antiAliasing.temporal_resolve`), the one temporal
antialiasing runs at scale 1: the history is read through a Catmull-Rom spline,
which keeps the contrast of thin lines through a slow pan; samples
are weighed in a reversible tonemapped space; the history is variance-clipped
in YCoCg against the scene samples within a texel and a half of the pixel; and
the frame's share is halved wherever the history passes the clip untouched.
Every frame takes the same share: a frame trusted more when one of its samples
landed nearest a pixel weighs each pixel by where the jitter fell in its row as
well as its column, which settled the rows of one scene texel on alternating
values along every thin edge. The clip pulls the history fully into the
current frame's neighbourhood wherever it falls outside it, so a surface that
moves across a still background, a change of light and the first frames after
the reconstruction starts reach the picture at once.
The sequence of points inside the pixel the projection samples is eight per
display pixel, scaled by how many display pixels a scene pixel covers: 32 at
half scale. A run too short for that visits some display pixels more often than
others, and the converged picture kept that unevenness as a fixed pattern along
every thin edge.
`sharpness` sharpens the shown picture with `@builtin::systems.antiAliasing.rcas`
after the reconstruction, outside its history, so it never compounds.
## Its relationship to the other temporal pass
`@builtin::systems.antiAliasing.temporalAntiAliasing` is the same resolve at the
scene's own resolution, and a world created from the default template runs it.
The frame has one temporal reconstruction, so enabling this module with a
reconstructing backend (`"taau"`, `"dlss"`, or `"auto"`) has temporal
antialiasing stand aside (`temporalAntiAliasing.yieldedTo()` names this module);
`disable` hands the frame back, and temporal antialiasing runs again if it is
still enabled. Backend `"none"` reconstructs nothing and leaves it running.
## Files
```
temporalUpscale.package/
TemporalUpscale.component/ -- the settings, authored and persisted
temporalUpscale.module/ -- enable / get / active / disable
taau.renderFeature/ -- the jitter, the two targets, the pass
taau_resolve.computeShader/ -- the reconstruction itself
```
# Compute shader (asset type)
A `.computeShader` is a GPU compute (GPGPU) program with a **zero-scaffolding**
authoring contract: you write only `@compute fn main(...)` plus a declarative
`bindings.yaml`, and the engine GENERATES every `@group/@binding` declaration —
storage buffers, textures, samplers, storage textures, and a `params:` uniform —
expands `#include`s, naga-validates the result, and registers it. The single
source of truth for the binding layout is `bindings.yaml`; there are no
hand-written `@binding` lines to keep in sync.
> New to how content lives across the CPU and GPU? Read `core/resource-model`
> first: it covers the asset / CPU / GPU forms every resource takes, the upload
> path, and how compute fits the performance ladder (`core/performance`).
## Folder shape
A `.computeShader` is a folder asset:
```
<name>.computeShader/
shader.wgsl # the WGSL body — only `@compute fn main` + helpers (required)
bindings.yaml # the binding + params schema (required)
README.md # a one-paragraph description of THIS shader (required)
.metadata # asset metadata
```
Each file carries a committed `.meta` sidecar pinning its stable guid. The
identity is `<name>` (the `.computeShader` suffix strips).
Resolve the shader once, then dispatch through the reference:
```lua
local carve = asset.resolve("carve", "computeShader")
carve:dispatch({ buffers = { heights }, workgroups = { 64 } })
```
`asset.resolve` is what records your script's dependency on the shader, so the
shader travels with the world your script lives in — packed, pulled, or
published. It compiles on first dispatch, and on the first frame a render
feature's compute pass names it; there is no setup step.
## bindings.yaml
One ordered `bindings:` list — the binding index is the list position
(0, 1, 2, …) — plus an optional `params:` scalar-uniform block. `kind` defaults
to `buffer` when omitted.
```yaml
bindings:
- { name: clouds, kind: storage3d, format: rgba16f } # texture_storage_3d<rgba16float, write>
- { name: occupancy, kind: texture3d } # texture_3d<f32>
- { name: smp, kind: sampler } # sampler
- { name: out_tex, kind: storage2d, format: rgba16f } # texture_storage_2d<rgba16float, write>
- { name: U, kind: buffer, access: read, element: f32 } # var<storage, read> U: array<f32>
- { name: Uniforms, kind: buffer, access: read, element: VolumeUniforms, array: false } # var<storage, read> Uniforms: VolumeUniforms
params:
- { name: scale, type: float, default: 2.0 }
- { name: count, type: int, default: 0 }
```
| `kind` | extra keys | generated WGSL declaration |
|---|---|---|
| `buffer` (default) | `access: read \| read_write` (default `read_write`), `element: <wgsl type>` (default `f32`), `array: true \| false` (default `true`) | `var<storage, ACCESS> NAME: array<ELEMENT>;` (or `… NAME: ELEMENT;` when `array: false`) |
| `texture3d` | — | `var NAME: texture_3d<f32>;` |
| `texture2d` | `sample: float \| uint \| sint` (default `float`) | `var NAME: texture_2d<f32>;`, or `<u32>` / `<i32>` for the other classes |
| `texture_depth` | — | `var NAME: texture_depth_2d;` — the one sampled shape with no `sample:` of its own; a depth-aspect channel (`@scene.depth`) binds here, not through `texture2d` |
| `storage3d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_3d<FMT, ACCESS>;` |
| `storage2d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_2d<FMT, ACCESS>;` |
| `sampler` | `filter: linear \| nearest`, `mipmap: linear \| nearest`, `address` (or `addressU` / `addressV` / `addressW`): `clamp \| repeat \| mirror`, `anisotropy: 1..16` (with `filter` and `mipmap` linear), `compare: never \| less \| less-equal \| equal \| greater \| greater-equal \| not-equal \| always`; none stated is the engine's linear, clamped sampler | `var NAME: sampler;`, or `var NAME: sampler_comparison;` when it states `compare` (for `textureSampleCompare` on a `texture_depth`) |
| `textureCubeArray` | — | `var NAME: texture_cube_array<f32>;` — the environment cube array, bound to `@scene.environment` by a render feature's pass |
| `vertices` | `access: read \| read_write` (default `read_write`) | `var<storage, ACCESS> NAME: array<u32>;` plus the mesh's layout uniform and the `zeroVertex*` accessors |
| `acceleration_structure` | — | `var NAME: acceleration_structure;` (hardware ray tracing) |
- **Eight storage buffers per shader** — the WebGPU guarantee, and what the
engine asks every device for. `buffer` and `vertices` bindings spend that
budget; textures, samplers, storage textures and `params:` do not. An
`acceleration_structure` brings engine-owned buffers with it — **three** where
the device has hardware ray query (the tables `zeroHitSurface` / `zeroMaterial`
read) and **five** on the software backend (those, plus the scene triangles and
the hierarchy over them) — so a traced pass has three slots of its own on the
backend web users get. Over budget, the engine refuses the shader and logs
which buffers it declared.
- A `buffer` defaults to `array<ELEMENT>`. Set `array: false` for a single
NON-array storage buffer — a struct binding (e.g. `element: VolumeUniforms`,
`array: false` → `var<storage, read> NAME: VolumeUniforms;`). The struct
definition itself lives in `shader.wgsl`, not `bindings.yaml`.
- **A sampled texture binds under the class its FORMAT puts it in**, so
`sample` states that class and the generated `texture_2d<..>` matches it. An
integer channel — `@scene.material`, which is `Rgba8Uint` — is `uint`;
everything else is the `float` default. Bind an integer channel to a `float`
slot and the engine refuses the pass and names both classes, because the
device would otherwise reject the bind group and invalidate the pipeline.
- **A float texture binding filters where the shader samples it.** Each
`texture2d` / `texture3d` binding is laid out from what the shader does with
it: one the shader reads through a sampler (`textureSample*`,
`textureGather*`, in the entry point or any function it calls) is filterable,
and one it reads with `textureLoad` alone is unfilterable and takes every
float texture. `r32f`, `rg32f` and `rgba32f` filter only on a device that
grants 32-bit float filtering, which many mobile GPUs do not; there a pass or
dispatch binding one at a sampled binding is refused and logged, naming the
binding and the format. Read a 32-bit float texture with `textureLoad`, or
keep a texture the shader samples at `rgba16f`.
- A storage texture's `access` decides both the generated declaration and the
layout the engine registers, so the two always agree. It defaults to `write`,
the access every target grants every storage-compatible format. `read_write`
is granted on `r32f` and `r32u` alone; declaring it on any other format is refused at
the compile, with the reason on `compute.programState`. A pass that needs to
read a wider target reads it through a separate `texture3d` / `texture2d`
binding, or through a second storage binding declared `read`.
- `format` tags (storage textures): `r8`, `r16f`, `r32f`, `r32u`, `rg32f`,
`rgba8`, `rgba8u`, `rgba16f`, `rgba32f`. Storage textures only allow
storage-compatible formats (`r32f` / `r32u` / `rg32f` / `rgba8` / `rgba8u` /
`rgba16f` / `rgba32f`). `r32u` holds one unsigned 32-bit word a texel and
`rgba8u` four unsigned 8-bit lanes (the format `@scene.material` is kept in):
the shader loads and stores either as a `vec4<u32>`, and the texel is never
filtered, so a texture bound to a `texture2d` slot reads it with
`sample: uint`. `rg32f` holds two 32-bit floats a texel, each stored and
read back as written and never filtered.
- An `acceleration_structure` binding resolves to the scene acceleration
structure when the shader runs as a render-pass with ray tracing enabled
(`renderer.setRaytrace(true)`). Declaring one makes the engine emit the helper
functions the body can call:
`zeroTraceClosest(origin, dir, t_min, t_max) -> ZeroHit` (struct: `hit, t,
instance, primitive, bary, attr`, where `instance` is the hit object's render
slot), `zeroTraceAny(origin, dir, t_min, t_max) -> bool`
(terminate-on-first-hit over every traced surface, for occlusion rays),
`zeroTraceShadow(origin, dir, t_min, t_max) -> bool` (the same over the
surfaces that cast shadows, for a shadow ray toward a light: a surface with
`castsShadows = false` lets the light through), and
`zeroHitSurface(hit) -> ZeroSurface` (`normal, uv, material`) +
`zeroMaterial(index) -> ZeroMaterial` (`base_color, emissive, metallic,
roughness`) to shade what a hit landed on; its `base_color.rgb` is the
material's `base_color` times the mean colour of its `base_color_texture`. The same surface works on both backends — hardware
ray query and the software/compute path — so the shader doesn't branch on
`renderer.raytraceCapability()`. Both trace helpers pass through the
cut-away texels of an alpha-tested surface (a texel stays where
`base_color.a * base_color_texture.a` reaches the material's `alpha_cutoff`),
read from the engine-owned coverage texture `zeroHitCoverage` bound beside
the hit tables. Bind it from a render-pass, which is where
the scene acceleration structure exists.
`params:` declares scalar uniforms (`type: float | int`). When non-empty the
engine appends a `ZeroComputeParams` uniform as the trailing binding (read it in
WGSL as `params.<name>`) and tunes its values at runtime with
`shaderRef:setParam(prop, value)`.
## The kernel ABI: `columns`, counted and appended outputs, `specialize`, `determinism`
One shader asset can serve many shapes of data. `bindings.yaml` states the shape
with these extensions, and the engine's compile path lowers them to the plain
bindings and WGSL above (`modules/compute_abi`, whose README has the whole
surface):
```yaml
workgroup: 64 # the size the body declares (default 64)
bindings:
- { name: cols, kind: columns, access: read } # a table of columns in one binding
- { name: src, kind: buffer, access: read, element: T }
- { name: dst, kind: buffer, access: read_write, element: T, count: "len(src)" }
- { name: hits, kind: buffer, access: read_write, element: vec4<f32>, capacity: "n * 4", append: true }
specialize:
- { name: T, options: [f32, i32, vec2<f32>, vec3<f32>, vec4<f32>] }
- { name: FOLD, options: [add, min, max] }
- { name: BODY, kind: source, default: "0.0" } # text that replaces the identifier
determinism: exact # or float_order
```
- A `buffer` of a scalar or vector element gets `NAME_get(i)`, `NAME_len()` and
(unless `access: read`) `NAME_set(i, v)`. A `vec3` element is stored as a flat
scalar array, so a column of vec3 keeps its 12-byte stride. `zero_n()` is the
dispatch size.
- `columns` binds a table of columns (`compute_abi.table`) as one storage buffer;
`cols_f32(c, i, lane)`, `cols_vec3(c, i)` and the rest read it.
- `count` / `capacity` give the size, in elements, of an output the run
allocates. `append: true` adds a live counter binding, `NAME_count`, with
`NAME_store(slot, v)`, `NAME_set_count(n)` and, under `determinism: float_order`,
`NAME_append(v)`.
- `specialize` parameters are compile-time: type options become `alias NAME`,
named options become `const NAME` and `NAME_<option>`, `kind: source` text
replaces the identifier. Each specialization compiles once.
- `determinism: exact` refuses `NAME_append`: an exact output is written at ranks
the kernel computed.
Dispatch such a shader through its program:
```lua
local variant = shaderRef:program():variant({ specialize = { T = "vec3<f32>" } })
local run = variant:run({ n = 64, inputs = { src = srcBuffer } })
local values = require("@builtin::modules.compute_abi").read(run.outputs.dst.buffer)
```
`shaderRef:program()` answers the same program, with the variants it has lowered and compiled, for as long as
`shader.wgsl` and `bindings.yaml` hold the bytes they held when it was made. A write to either file, from any origin
(`vfs.contentVersion` moves), makes the next `program()` a new one, and a dispatch through it runs the new text. The
schema `getBindings()` answers is the one the program was made over.
## Writing a mesh's vertices — `kind: vertices`
A mesh's vertices are raw bytes on the GPU, and the engine stores a mesh in one
of two layouts: 92 bytes a vertex with every attribute a `f32`, or 32 bytes a
vertex with normals and tangents quantized to bytes and UVs to shorts. Which one
a mesh got depends on the mesh.
Declare `kind: vertices` and the shader is handed both the buffer and the layout
that mesh is in, plus accessors that address it:
```yaml
bindings:
- { name: verts, kind: vertices } # the mesh, writable
- { name: heights, kind: buffer, access: read, element: f32 }
params:
- { name: lift, type: float, default: 1.0 }
```
```wgsl
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x >= zeroVertexCount()) { return; }
var p = zeroVertexPosition(id.x);
p.y = p.y + heights[id.x] * params.lift;
zeroSetVertexPosition(id.x, p);
zeroSetVertexNormal(id.x, vec3<f32>(0.0, 1.0, 0.0));
}
```
```lua
carve:dispatchOnVertices({ model = meshRef:handle().guid, buffers = { heights }, workgroups = { 64 } })
```
The accessors, over a binding declared `read_write`:
| read | write |
|---|---|
| `zeroVertexCount() -> u32` | — |
| `zeroVertexPosition(i) -> vec3<f32>` | `zeroSetVertexPosition(i, vec3<f32>)` |
| `zeroVertexNormal(i) -> vec3<f32>` | `zeroSetVertexNormal(i, vec3<f32>)` |
| `zeroVertexTangent(i) -> vec4<f32>` | `zeroSetVertexTangent(i, vec4<f32>)` |
| `zeroVertexUv(i) -> vec2<f32>` | `zeroSetVertexUv(i, vec2<f32>)` |
| `zeroVertexColor(i) -> vec4<f32>` | `zeroSetVertexColor(i, vec4<f32>)` |
| `zeroVertexNodeIndex(i) -> u32` | — |
| `zeroVertexWord(i, offset) -> u32` | — |
`access: read` gives you the readers only — a `var<storage, read>` binding
cannot be assigned to, so the writers are left out rather than handed to you
broken.
Once a pass has written a mesh's vertices, the engine bounds that mesh by what
the pass wrote: it reduces the vertices to an AABB every frame and culls against
that, so geometry a pass moves across the scene needs no oversized placeholder
to survive culling. `renderer.mesh.boundsSource(guid)` reports `"compute"` for
such a mesh and `"geometry"` for one still bounded by what it was created with.
A shader declares at most one `vertices` binding; the accessors are generated
for that mesh. It can be declared anywhere in the list — the mesh is bound by
the dispatch, and `buffers` fills the other storage slots in declaration order.
The tangent's `w` carries handedness, and quantized normals/tangents come back
in -1..1 while quantized UVs and colours come back in 0..1, so the values are
the same ones a surface shader sees whichever layout the mesh is in.
## shader.wgsl
Write only `@compute fn main` (and any helpers / `#include`s). The names declared
in `bindings.yaml` are in scope — `data`, `out_tex`, `params.scale`, … — with no
`@group`/`@binding` lines of your own.
```wgsl
// @domain: compute
// Bindings are declared in bindings.yaml — do NOT write @group/@binding here.
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x < arrayLength(&data)) {
data[id.x] = data[id.x] * 2.0;
}
}
```
## Dispatch & runtime
Everything a compute shader does, it does through its reference:
| method | what it does |
|---|---|
| `ref:dispatch(opts)` | `{ buffers, workgroups, params? }` — bind one buffer per declared storage binding, in order |
| `ref:dispatchOnVertices(opts)` | `{ model, buffers?, workgroups, params? }` — bind the mesh `model` names to the `vertices` binding, `buffers` filling the rest |
| `ref:dispatchEx(opts)` | `{ resources, workgroups, params? }` — for shaders mixing textures, samplers and storage textures: one `{ kind, name }` per declared binding, in order; `params = { name = value }` gives the shader's `params:` fields values for this dispatch alone, as `ref:dispatch` takes them. Any other key is refused, naming it |
| `ref:setParam(prop, value)` | write one `params:` scalar uniform |
| `ref:createBuffer(name, opts)` | `{ type, len, usage? }` — a GPU buffer owned by this shader |
| `ref:buffer(name)` | the buffer this shader last made under `name` |
| `ref:getBindings()` | the parsed `bindings.yaml` schema, read and parsed again only after the file is written |
| `ref:getSource()` / `ref:setSource(wgsl)` | read / overwrite `shader.wgsl` |
| `ref:compile()` | compile now instead of on the first dispatch or the first frame a feature pass names it |
| `ref:withIncludes(replacements)` | `{ [module as the shader's WGSL includes it] = shaderModule }` — a program of this shader in which each named `#include` reaches the compiler as the module its value names; answers the key a render pass's `program` or a dispatch takes, compiled again under a new key when the shader, a replacement module or any module the program reaches through its includes is edited (`compute.programState(key)` reads where it stands) |
| `ref:status()` | what the engine did with this shader's dispatches, one record per target |
The `params:` uniform is engine-owned and takes no entry in `buffers` or
`resources`, and neither does a `vertices` binding's layout.
`setParam` writes the uniform every later dispatch reads. A dispatch that
passes `params = { name = value }` reads those values instead, in a copy of the
uniform only it binds, with every name it leaves out at the value the shader
holds — so one shader dispatched twice in a frame over different data reads
different values each time:
```lua
lift:dispatch({ buffers = { a }, workgroups = { 4 }, params = { height = 1.0 } })
lift:dispatch({ buffers = { b }, workgroups = { 4 }, params = { height = 3.0 } })
```
A name the shader does not declare fails that dispatch, and the failure names
what it does declare.
### `dispatchEx` resources
Each `resources` entry fills the binding at its position. Its `kind` says what
the resource is, in the words `bindings.yaml` uses, and the binding decides how
it is read. A slot takes the kind it is declared with; a `texture2d` slot also
reads a storage texture, a side of a history pair or the scene depth, and a
`storage2d` slot also writes this frame's side of a history pair:
| binding's `bindings.yaml` kind | `resources` entry | `name` |
|---|---|---|
| `buffer` | `{ kind = "buffer", name = buf }` | a buffer handle from `ref:createBuffer` |
| `texture3d` | `{ kind = "texture3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` |
| `storage3d` | `{ kind = "storage3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` made with `storage = true` |
| `storage2d` | `{ kind = "storage2d", name = target }` | a storage texture handle from `ref:createStorageTexture2D` |
| `storage2d` | `{ kind = "history_curr", name = history }` | a history pair from `ref:createTextureHistory`: this frame's side |
| `texture2d` | `{ kind = "texture2d", name = tex }` | a handle `ref:copyBufferToTexture` returns, a texture asset's guid once `texRef:handle()` has made it GPU-resident, or a `renderer.texture.create` handle: a render target a render feature draws into, or a texture made from pixels |
| `texture2d` | `{ kind = "storage2d", name = target }` | a storage texture handle, read as a texture |
| `texture2d` | `{ kind = "history_prev", name = history }` / `{ kind = "history_curr", name = history }` | a history pair: the previous frame's side or this frame's |
| `texture2d` | `{ kind = "scene_depth" }` | none: the frame's scene depth |
| `sampler` | `{ kind = "sampler", name = smp }` | a sampler handle from `ref:createSampler` |
A `dispatchEx` is recorded at the start of the frame, ahead of the frame's render
passes, so a render target it reads holds what the previous drawn frame's passes
wrote into it; a pass of a render feature reads what a `dispatchEx` of the same
frame wrote.
`texture3d` and `storage3d` name the same resource, a 3D texture, so either one
fills either slot. The engine's own spellings name the same resources and keep
working: `texture_3d` for `texture3d` and `storage3d`, `texture_2d` for
`texture2d`, and `storage_2d` for `storage2d`. Any other `kind` is refused at the
call, naming every kind it accepts. A `vertices` binding is filled by
`ref:dispatchOnVertices`, and `texture_depth`, `textureCubeArray` and
`acceleration_structure` bindings by a render feature's pass.
```lua
local march = asset.resolve("volume_march", "computeShader")
-- bindings.yaml: density (storage3d), out_tex (storage2d), U (buffer)
march:dispatchEx({
resources = {
{ kind = "storage3d", name = density },
{ kind = "storage2d", name = target },
{ kind = "buffer", name = uniforms },
},
workgroups = { 8, 8, 8 },
})
```
`workgroups` is `{ x, y, z }`, `{ x }`, or a bare `x`, and every dimension it
leaves out is 1. A zero in any dimension is refused: the dispatch is dropped and
recorded as a failure, so it surfaces in `ref:status()` and `compute.failing()`
with the reason. A count derived from how much data there is passes through
`math.max` first, so an empty set dispatches one workgroup rather than none:
```lua
carve:dispatch({ buffers = { heights }, workgroups = { math.max(1, math.ceil(#points / 64)) } })
```
### Buffers and readback (the CPU side)
A buffer is created through the shader that owns it and comes back as a handle.
Pass the handle to a dispatch — including another shader's — to bind it there:
```lua
local double = asset.resolve("@builtin::shaders.compute_double", "computeShader")
-- `type` is the element the shader declares, `len` how many of them.
local data = double:createBuffer("data", { type = "f32", len = 4, usage = { "readback" } })
data:write({ 1.0, 2.0, 3.0, 4.0 }) -- :writeU32 for integer words, :writeBytes for packed bytes
double:dispatch({ buffers = { data }, workgroups = { 1, 1, 1 } })
local pending = data:read() -- starts an async GPU->CPU readback
-- a frame or two later, drain it (nil until it has arrived):
local out = pending:result() -- :resultU32 / :resultBytes read the same bytes another way
data:destroy() -- free it when done
```
`type` is one of `"f32"`, `"vec3"`, `"vec4"`, `"quat"`, `"mat4"`, and `usage`
adds `"readback"`, `"vertex"`, `"index"` or `"indirect"` on top of the storage a
buffer always has. An `"indirect"` buffer holds a draw's arguments where the GPU
reads them, so a shader that compacts geometry writes the drawn count into the
same dispatch that produced it and a render feature's `kind = "draw"` pass
submits exactly that — the `renderFeature` asset type's README documents that
pass and the `storage.indirect` name it reads.
An `"indirect"` buffer also holds the three workgroup counts a compute pass
dispatches over: a render feature pass stating `dispatch = { indirect = buffer }`
runs the counts a pass before it wrote there (`renderFeature`'s README, "Compute
passes").
The handle's key is the shader's guid plus the name you gave it and
a serial, so two shaders that both want a buffer called `data` get one each —
and so do two callers asking this same shader for one. `ref:buffer(name)`
returns the last one made under that name, which is how two callers share one
on purpose.
A buffer that no shader computes — a vertex or index run that is only ever
drawn — is allocated straight from the primitive instead:
`substrate.createBuffer({ name = ..., type = ..., len = ..., kind = "gpu", usage = { "vertex" } })`.
The first dispatch of a shader compiles it, so the very first readback can still
reflect the un-run shader; dispatch again once it is compiled, or `ref:compile()`
to pre-warm. This create/write/dispatch/readback loop is the CPU side of the
resource model in `core/resource-model`.
### Is it compiled?
`ref:compile()` queues the compile; the pipeline is built on the render side
frames later, so that call cannot say whether it produced a program.
A shader whose program the engine holds (`ready`) or is building (`pending`),
compiled again while its `shader.wgsl`, its `bindings.yaml` and every module it
includes hold the content the program was made from, queues nothing and
leaves the program as it is; an edit to any of those files queues the compile
again. A shader that includes a module some code filed under a key of its own
(`shader.registerModule`; the engine's `zero::` names aside) queues the compile
each time, since no file says when that text changed. `compute.programState(ref)` is where that lands:
```lua
if compute.programState(carve) == "ready" then carve:dispatch(opts) end
local state, reason = compute.programState(carve)
if state == "failed" then print(reason) end
```
- `"absent"` — the engine holds nothing under this key and nothing is in
flight: never asked for, or released.
- `"pending"` — a compile was asked for and has not reached the device. A
recompile of a resident program reads pending too, because what it produces
is a different program from the one bound now — which is what makes this the
precondition to wait on after an edit.
- `"ready"` — compiled and resident, so a dispatch naming it binds it.
- `"failed"` — the most recent compile produced no program, and the second
return says why.
A dispatch issued while the program is `"pending"` is held behind the compile
and dropped if it never lands, so a readback taken before `"ready"` reports the
buffer as it was. Wait for `"ready"`, not for a count of frames.
### Did it run?
A dispatch is recorded into a command encoder frames after the call that asked
for it returned, so that call's `true` means "queued", not "ran". `ref:status()`
is where the outcome lands — one record per target, cumulative:
```lua
for _, d in ipairs(carve:status()) do
print(d.target, d.ok, d.dispatches, d.failures, d.lastError)
end
```
`target` is the mesh guid for a `dispatchOnVertices` and the buffers it bound
for a dispatch that writes only those, so two systems driving one shader over
their own buffers read as the two passes they are. `ok` is the most recent outcome; `lastError` says
why the last failure failed and is kept after a recovery. An empty result means
nothing has dispatched this shader at all. `compute.failing()` answers the same
question across every shader at once.
A failing dispatch also posts a notice, so a pass that stops running reports
itself rather than waiting to be found.
### Running one every frame
A `kind = "compute"` substrate job queues one dispatch per frame:
```lua
jobs.register({
phase = "main",
executor = {
kind = "compute",
shader = asset.resolve("carve", "computeShader"),
buffers = { "heights" },
workgroups = { 64 },
},
})
```
### Many dispatches as one call: compute lists
Work that issues many dispatches every frame (a solver's passes, the levels of a
pyramid, a chain of blurs) registers them once as a compute list and queues them
all with one call, so a frame pays for one call rather than one per dispatch:
```lua
local advect = asset.resolve("~.advect", "computeShader")
local project = asset.resolve("~.project", "computeShader")
local key = velA.key .. ":step" -- named from something this system owns
compute.list(key, {
{ write = params, values = { 0, 0, 0, 1 / 60 }, slots = { [4] = "dt" } },
{ program = advect, resources = {
{ kind = "texture3d", name = velA }, { kind = "sampler", name = smp },
{ kind = "storage3d", name = velB }, { kind = "buffer", name = params },
}, workgroups = { 16, 16, 16 } },
{ program = project, resources = {
{ kind = "texture3d", name = velB }, { kind = "storage3d", name = velA },
}, workgroups = { 16, 16, 16 }, slots = { strength = "strength" } },
})
-- every frame:
compute.runList(key, { dt = dt, strength = 0.5 })
```
An entry is a dispatch, binding `buffers` as `ref:dispatch` does or `resources`
as `ref:dispatchEx` does, or a buffer `write` (`offset` in 32-bit words,
`values` as f32, or u32 with `unsigned = true`). `slots` names the values a run
supplies: a `params:` name to a slot on a dispatch, a value's place (from 1) to
a slot on a write. `when = "<slot>"` leaves the entry out of a run that gives
that slot 0, so one list holds the variants a run picks between. Everything
else is fixed when the list is registered, so a list that alternates between two
textures (a ping-pong) is two lists, or one list whose two halves are guarded by
`when`. The entries run in the order the list states them, and runs in the order
they were queued: a write lands after the dispatches before it and ahead of the
ones after it, so a list may write a buffer between two dispatches that read it,
and two runs in one frame each read their own writes.
`compute.list` resolves every reference and handle when it is called and raises
on a malformed entry, naming it; `compute.runList` answers that the run was
queued, and `ref:status()` and `compute.failing()` say what each dispatch did.
Registering again under the same key replaces the list; `compute.dropList(key)`
forgets it when the system is torn down. `fluidSim` steps its whole solver this
way.
## Registration & hot reload
Writing `shader.wgsl` or `bindings.yaml` fires the `.computeShader` assetType's
`onChange`, which compiles it: the binding declarations are generated,
`#include`s expanded, the WGSL validated, and the shader registered. This happens on
create and on every edit, so saving recompiles with no world reload. A shader
with invalid WGSL (a type mismatch, an undefined name) **fails to compile** with
the reason logged (`[compute] Compile of '<name>' failed: …`) and is **not**
registered. You don't need to register a shader before dispatching it — the first
dispatch auto-compiles it on use. `ref:compile()` remains as an optional explicit
pre-warm, only to avoid the one-frame first-dispatch warm-up in a
latency-critical spot.
## What compute is holding, and why a key names nothing
Every buffer, volume, storage target, history pair and sampler a dispatch can
bind is filed under a key, and `compute.observe()` lists all of them with what
each costs:
```lua
local r = compute.observe()
print(r.totals.count, r.totals.bytes)
for _, res in ipairs(r.resources) do
print(res.key, res.kind, res.bytes, res.owner.name)
end
```
A row carries the key verbatim — the same string a dispatch names it by and a
dispatch-failure message prints — plus its `kind`, its `bytes`, its extent and
`format` where it has them, the `usage` bits it was created with, and the frame
it was created on. `owner` is read back out of the key
(`<shader-guid>::<name>#<serial>`), so a resource nothing has ever dispatched
over still names the shader that made it. `compute.resources(ref)` narrows to
one shader's — including the `<shader-guid>::__params` uniform the compile
created for a `params:` block, which the shader owns like any other resource.
`r.totals.bytes` is the `compute` figure of `renderer.gpuMemory()` — the two are
read off the same registries, so a listing accounts for the category exactly.
The same reading is served at `/zero/runtime/compute`.
When a key names nothing, `compute.diagnose(key)` says which of the states the
inventory distinguishes it is in, from the closed set `compute.absentReasons()`
enumerates:
| reason | what the inventory read |
|---|---|
| `resident` | a resource is filed under exactly this key; the row is on `resource` |
| `replaced` | the owner holds the same name at a different serial — `current` names the live key |
| `nameUnused` | the owner holds resources, none under this name |
| `ownerAbsent` | no live resource carries this key's owner |
| `unowned` | the key carries no owner segment, and nothing is filed under it |
| `notPublished` | no renderer has published an inventory, so no key can be answered for |
So a key out of `[compute] dispatch '…' failed` resolves against what exists,
and a typo reports which part of it the engine could not match rather than
coming back empty.
A reason is the inventory at the moment the call read it. The reading is
republished on a frame where a registry gained or lost an entry, so a resource
created and diagnosed inside one script sees the reading from before it was
made; wait a frame and ask again.
## Discovery
- `asset.list("computeShader")` — every registered compute shader.
- `asset.inspect("<name>")` — status, source, parse errors, this README.
- `computeRef:getBindings()` — the parsed `bindings.yaml` schema
(`{ bindings, params }`).
- `compute.programState(ref)` — whether the program is compiled, still
compiling, or failed, and why.
- `compute.observe()` — every GPU resource compute holds, and what it costs.
- `compute.diagnose(key)` — whether a key names a live resource, and why not.
- `profiler.gpuFrame()` — what each dispatch of this shader spends on the GPU.
A dispatch is timed under `compute.<identity>` — the same identity
`asset.resolve` takes, so a timing row names the shader that produced it.
## Common pitfalls
- **Compute shaders don't render** — verify output via a buffer readback or a
debug pass, not a screenshot.
- **`ref:compile()` returns before the program exists** — the pipeline is
built on the render side; `compute.programState(ref)` says when it is
`"ready"`. A dispatch issued before that is held behind the compile and
dropped only if the compile never lands.
- **A dispatch call returning true means queued** — ask `ref:status()` whether
it ran.
- **A destroyed buffer is refused where it is bound** — a handle outlives its
storage, and `buf:alive()` reports which.
- **Binding order is the contract** — `buffers` and `resources` bind in
`bindings:` list order; reordering the list reorders the bindings.
- **Don't write `@group`/`@binding` in `shader.wgsl`** — the engine owns them;
re-declaring is the fastest way to a layout mismatch.
- **Don't infer a mesh's vertex stride** — declare `kind: vertices` and use the
accessors. A wrong stride writes positions correctly and normals into the
wrong word, which renders as flat lighting rather than as broken geometry.
- **Storage-texture format must be storage-compatible** — `r32f` / `r32u` / `rg32f` /
`rgba8` / `rgba8u` / `rgba16f` / `rgba32f`; others are rejected at compile.
- **A key that comes back empty is not the same as one that failed** —
`compute.diagnose(key)` separates a name never used from a generation that
was replaced, and names the live key in the second case.
## Related types
- `.shader`: render-domain shaders (surface, sky, post-process, screen).
## In the Inspector
Selecting a compute shader opens its **Compute** section: whether its program is ready (and why not), how many dispatches it has run and failed in this session (and the last error), tables of the bindings and params its `bindings.yaml` declares, and openers for `shader.wgsl` and `bindings.yaml`.
# antiAliasing system
Geometry is rasterised at one sample per pixel, so a silhouette crossing a pixel
either covers its sample or does not. A shallow-angle edge therefore comes out as
a staircase of hard steps rather than as a line, and that staircase is the most
recognisable artifact of an unfiltered render. In motion it gets worse: the step
pattern shifts as the edge moves, a specular highlight flashes on and off as it
crosses the sample point, and fine texture crawls.
Two corrections live here, and they work from different information.
**Edge antialiasing** (`EdgeAntiAliasing`, FXAA) works from the finished frame
alone. It finds each edge and shifts that pixel's sample across it. Fixed cost,
no dependencies, corrects the staircase in a still image — and knows nothing
about time, so what only appears in motion stays.
**Temporal antialiasing** (`TemporalAntiAliasing`) samples a different point
inside each pixel every frame and accumulates the frames, following the scene's
own motion to know where each pixel's surface was. That recovers detail no single
frame holds and settles exactly what edge antialiasing cannot see — the crawling
and flickering that exist only between frames. It needs the scene's velocity, and
costs a small amount of softening, which its `sharpness` puts back on the shown
picture.
A world created from the default template runs temporal antialiasing from its
first frame: the template's `.world_settings` names `antialiasing = "taa"` under
`[render]`, and the world entrypoint applies it as the world loads, tuned by
`[render.taa]`. A world whose settings name `"off"`, or name no mode, runs none.
They compose: edge antialiasing cleans up within a frame, the temporal pass
handles what happens between them.
## Using them
```lua
local id = entity.spawn("antialiasing").id
entity(id).component.add("TemporalAntiAliasing", { historyWeight = 0.9 })
entity(id).component.add("EdgeAntiAliasing", { edgeThreshold = 0.125 })
```
Every field is live. For runtime control (a quality slider, or turning one off)
drive the modules:
```lua
local antiAliasing = require("@builtin::systems.antiAliasing.antiAliasing")
local temporalAntiAliasing = require("@builtin::systems.antiAliasing.temporalAntiAliasing")
temporalAntiAliasing.enable({ historyWeight = 0.9, sharpness = 0.2 })
antiAliasing.enable({ edgeThreshold = 0.125 })
```
Each module has `.enable` / `.get` / `.active` / `.disable`, acting on its
render feature asset (`fxaa`, `taa`): `enable` lands each value where it takes
effect (a component's or a placed setup's own value when it states it, else the
asset's live value) and applies the pass when nothing else does, `disable` drops
the module's own application, and a component's stays. A component applies the
asset with its fields, owned by its entity; of two, the one edited last is in
force.
Temporal antialiasing draws at a quality level: its `quality` (on the
component and in `enable`) is `low`, `medium`, `high`, or `auto` (the
default), which follows the device's quality tier (`renderer.qualityTier()`).
`high` sharpens the shown picture by `sharpness`; `medium` and `low` show the
accumulation unsharpened, and the sharpening pass and the copy of its result
into the picture leave the frame. The accumulation is the same at every level.
`temporalAntiAliasing.drawn()` reports the level in force and the sharpening it
draws.
To see temporal antialiasing as a player sees it, read the frame the screen
showed: `capture { source = "presented" }` (`frames = n` for a run of
consecutive frames, which is how convergence and flicker read), or
`renderer.presentedFrames()` for the pixels with each frame's jitter and
history reset. Every view keeps its own accumulation: a render-to-texture
camera accumulates over its own renders, and an offscreen capture draws a fresh
view whose single render has no history behind it, so it shows none of the
accumulation and leaves the viewport's untouched. A capture drawing the picture
the viewport draws (the camera holding the viewport, at the viewport's size,
admitting the same of the scene) continues the viewport's accumulation
instead: it is the frame the viewport presents next, and the viewport's own
accumulation goes on as it would have. The capture toolbox README has the
rule.
## What the edge knobs do
| field | effect |
|---|---|
| `edgeThreshold` | How much a pixel's luminance must differ from its neighbours', as a fraction of the brightest of them, before it counts as an edge. Lower catches fainter edges and costs more. |
| `edgeThresholdMin` | The absolute floor under that test. It keeps the pass off dark areas, where a small relative step is still visually flat. |
| `subpixel` | How strongly features finer than one pixel are corrected. |
| `searchSteps` | How far the pass walks along an edge looking for its end. Longer reach resolves shallower edges, at linear cost. |
## What the temporal knobs do
| field | effect |
|---|---|
| `historyWeight` | How much of the accumulated result to keep each frame. Higher resolves more detail and settles smoother, at the cost of taking longer to let go of what a surface used to look like. |
| `neighbourhoodClamp` | How far outside the neighbourhood's own colour spread an accumulated sample may sit before it is pulled back in. Lower rejects more, trading some of the settling for a result that follows change faster. |
| `sharpness` | How strongly the shown picture is sharpened, in [0, 1]: a contrast-adaptive pass (`rcas`) after the display transform, which steepens edges without lifting either side past its plateau and is never written back into the accumulation. 0 shows the accumulation as it is. |
| `motionRejection` | How much fast motion shortens the memory, which is what stops a moving object trailing behind itself. |
| `stillSamples` | How many renders a pixel whose surface holds still accumulates, in [1, 256]. Each render samples a different point inside the pixel, so a still pixel holding several whole passes through the sample sequence settles on their average instead of rippling as the samples visit it; fewer let a still picture follow a slow change of its lighting sooner. |
## How they render
`fxaa.renderFeature` runs one compute pass in the `display` stage, on display
code values, so its edge thresholds read luma the way a viewer sees it. A
picture of the edge antialiasing is read from the presented frame
(`renderer.presentedFrames`, a `capture` with `source = "presented"`): the
`display` stage's render-feature passes draw there. The result is **not a
blur**. A blur softens everything; this moves each edge pixel's sample
perpendicular to the edge by a sub-pixel amount, so the step between two flat
regions becomes a gradient while both regions are left as they were. That is why
the pass has to find the edge's direction and extent rather than filtering a
neighbourhood — the offset depends on where along the edge the pixel falls, so a
pixel near the middle of a long edge barely moves and one near an end moves
nearly a full half-texel.
Luminance drives every decision there. The eye resolves luminance detail far more
finely than chroma, so a step that reads as a jagged edge is a step in luminance,
and an edge that is pure chroma needs no correction. A pixel whose neighbourhood
varies less than the threshold is passed through untouched, which is what keeps
flat regions and gentle gradients out of the filter entirely. Features finer than
a pixel produce no long edge to walk, so the 3x3 luminance average carries their
correction instead.
`taa.renderFeature` offsets where the projection samples each frame and
accumulates the frames that produces, reprojecting through `@scene.motion` and
bounding what it carries by the neighbourhood's own colour statistics. Its README
covers the sample sequence, the tests that decide whether an accumulated sample
is still about the same surface, and why the bound is computed in YCoCg. The
accumulation itself is `temporal_resolve`, the one resolve the temporal upscale
(`@builtin::systems.temporalUpscale`) folds its frames through as well. Both
then restate the frame's depth from `stable_depth`, the depth sample nearest
each pixel's centre while nothing there moves, so an effect after them draws
lines and patterns that hold still with the picture.
## Files
```
antiAliasing.package/
EdgeAntiAliasing.component/ -- the scene's edge antialiasing, authored and persisted
antiAliasing.module/ -- .enable / .get / .disable / .active
fxaa.renderFeature/ -- the edge pass
TemporalAntiAliasing.component/ -- the scene's temporal antialiasing, authored and persisted
temporalAntiAliasing.module/ -- .enable / .get / .disable / .active
taa.renderFeature/ -- the accumulation pass + the per-frame sample offset
taa_resolve.computeShader/ -- the accumulation at render scale 1
temporal_resolve.shaderModule/ -- the temporal resolve every reconstruction accumulates through
stable_depth.computeShader/ -- the depth a reconstruction restates for the passes after it
stable_surface.computeShader/ -- the G-buffer normal and material restated beside it
rcas.computeShader/ -- the sharpening of the shown picture after the temporal stage
```
# renderer.atmospherics
`renderer.atmospherics`: the share of the air between the camera and a surface that reaches the image, and the holds that pin it.
# renderer.baseline
The renderer a caller began with: `renderer.markBaseline`, `renderer.resetToBaseline` and `renderer.releaseBaseline`.
# renderer.bounds
`renderer.bounds`: the extent a render feature publishes for a renderable it draws from its own buffers.
# renderer.captureView
`renderer.captureView`: the named camera passes a render feature publishes, each under a debug channel a capture selects.
# renderer.core
The renderer table every `renderer.*` namespace is defined on, the engine surfaces those namespaces call, the runtime registry a create files a resource in under the holder its scope names, and the handles each create hands out, held weakly so a resource nothing reaches any more is let go.
# renderer.debugPass
`renderer.debugPass`: resolves a debug-pass name to and from the channel it selects, for the built-in passes and the capture views.
# renderer.destroy
`renderer.destroy`: releases the runtime texture, material, mesh or render feature a handle, or a kind and an id, names.
# renderer.feature
`renderer.feature`: the registry of live render features, the context each one's `render(ctx)` runs with every frame, and their settings; `renderer.post`: the post stages; `renderer.output`: the output the frame is presented in.
# renderer.featureInputs
What a render feature's `render` reads, and whether any of it moved. A feature that states its inputs (`dependsOn`, `inputs`) has `render` run only on a frame one of them moved; on every other frame the engine runs the passes the last render handed over. Its settings in force are always one of those inputs.
- `settingsInForce(feat, levels)` answers a feature's settings at the quality levels in force, kept on its row until the authored settings or a level change.
- `NAMES` names each input a feature may state in `dependsOn` and what it stands for.
- `compile(mod, identity)` answers the inputs a feature module states, or nil for one that states none, and refuses an input it does not know by name.
- `holdsStill(feat, levels, frame)` answers whether every input stands as it stood at the feature's last render, so its passes can be replayed.
```luau
local FeatureInputs = require("@builtin::modules.api.engine.renderer.featureInputs")
local inputs = FeatureInputs.compile({ dependsOn = { "viewport", "camera.cell:2" } }, "example")
assert(inputs.viewport == true and inputs.cell == 2)
assert(FeatureInputs.compile({}, "example") == nil)
assert(not pcall(FeatureInputs.compile, { dependsOn = { "weather" } }, "example"))
assert(FeatureInputs.NAMES.lights ~= nil)
```
# renderer.featureTexture
`renderer.featureTexture`: sizes the shared feature-texture array a surface shader reads through `zero_feature_texture(uv, layer)`, sets its layers and reports its state.
# renderer.frameStats
What each frame submitted (culling, draws, skinning, morphs, uploads) and how the frames are paced: the frame pacing and activity readings, frames in flight, the present mode, the spectator mode, local layers and the frame-rate cap.
# renderer.holds
The reads every renderer cell a hold pins answers the same way. A hold on a cell such as `renderer.temporal` (the per-frame clock) or `renderer.atmospherics` (the share of the air that reaches the image) names who took it and the key it was taken under, so a caller reads who holds the cell, an exclusive hold is refused for every other key, and a hold whose task ended is handed back.
- `statedOwner(options)` answers the key `options.owner` states, or nil.
- `actor()` answers the id and display name of the caller the call is attributed to.
- `ownerLabel(owner, ownerName)` answers how a refusal names the holder.
- `holderIsGone(holder)` answers whether the task that took a hold was cancelled or died; `holdingTask()` answers the task taking a hold now.
```luau
local Holds = require("modules.api.engine.renderer.holds")
assert(Holds.statedOwner({ owner = "shot" }) == "shot")
assert(Holds.ownerLabel("abc", "Ada") == "Ada (abc)")
assert(Holds.holderIsGone(nil) == false)
```
# renderer.instanceData
`renderer.instanceData`: the per-entity lanes of the per-instance block a shader reads as `input.shader_data`, set and cleared by entity.
# renderer.letGo
The watch that releases a runtime texture, material, mesh or render feature mid-session once no script reaches a handle to it and nothing else holds it. It reads the renderer's handle sets every few dozen frames: a resource whose last handle the garbage collector took joins the watch and is judged against the runtime resource census, by the holders `renderer.collect` reads, and released once nothing holds it. A resource kept only by the component or scene load that created it stays while that owner does, and the log names an owner once it holds 64 of one kind that way, and again each time that count doubles. A render feature holds what it created through the handles it keeps and the passes it queues, which the census names as references, so a target whose handle the feature dropped and that none of its passes names any more is released while the feature stands. A texture or mesh the asset path uploaded under its asset's guid waits on the watch while that asset stands, and is judged from its holders once the asset index changes and the asset no longer answers. A texture a released material record named goes on the watch with it, the one the device holds for an asset included: that asset is the path the texture is read back by, so it is released once nothing else names it, the way a collection releases it.
- `new(host)` makes the watch over the handle sets, census and release the renderer hands it in `host`, and answers `{ start, rejudge, letGo }`: `start()` starts the task that reads the sets unless it is running, `rejudge(kind, guid)` marks a watched resource due a judgement at the next reading, and `letGo(kind, guid)` puts a resource a holder other than a handle let go of on the watch.
# renderer.lifetime
Runtime resource lifetime: `renderer.hold`, `renderer.release` and `renderer.references`, `renderer.collect`, and the let-go watch that releases a runtime resource once nothing holds it.
# renderer.material
`renderer.material`: the material records (a shader key, property overrides and texture-slot references) the renderer builds a bind group from, and what each one draws with.
# renderer.memory
The render device and what its memory holds: the GPU memory reading, the device generation, state, limits and errors, shadow memory and pages, the reflection environment, render targets and the pass schedule, texture memory, the texture budget and streaming, memory pressure, the material table and the texture bucket slack.
# renderer.mesh
`renderer.mesh`: the ZMSH codec, the guid-keyed CPU mesh store, the GPU meshes created from it, their clusters and level of detail, and the instanced draws of a mesh.
# renderer.observation
The renderer's readings of its pipeline and shader caches, its pending work, the frame it last drew (`renderer.observe`), the draw diagnostics, how a subject shades, what materials and shaders cost, and the material identity table.
# renderer.postStages
The frame's post stages: the ordered list of named seams every post effect runs at. Each stage states the colour space of the picture it holds (`light`, scene-referred light the display transform has yet to fit to the screen, or `display`, display-referred code values) and its resolution (`raster`, `output`, `reduced`, or `rasterToOutput` for a stage that starts on the raster and carries the picture to the output size). A render feature declares `stage = "<name>"` and a post-process chain shader `stage: <name>` in its `properties.yaml`; the engine schedules each from this list, a feature's passes inside the stage's band of orders at its pipeline phase and a chain effect at the stage's chain layer. `renderer.post.stages()` reports the list with the effects standing in each stage.
Inside a stage a feature's pass takes a local order from 0 up to `BAND`, and passes sharing an order run in the order they were enqueued, so a feature whose passes depend on one another (a chain over shared targets) can run them at one order, in sequence. A pass may name a stage of its own (`stage = "display", order = 2`): a feature whose work spans two stages, such as temporal antialiasing (its resolve in `temporal`, its sharpening in `display`), declares one and names the other on those passes. A chain effect takes its place among the chain effects of its stage by `priority`, a number, or `"last"`, after every numbered chain effect of the stage; chain effects sharing a priority, two `"last"` among them, run in the order they registered. The `ui` stage runs `afterUI` feature passes, then its chain effects, then `afterPost` feature passes, so an `afterPost` pass runs after every chain effect of the stage.
The presented frame (`renderer.presentedFrames`, a `capture` of `source = "presented"`) runs every stage. An offscreen render (a capture from a camera or a station, a render-to-texture camera) runs the render features of every stage up to `optics`, the film stages among them (`meter`, `optics`) only when its camera runs post-processing; when it fits the picture to the display it runs the `display` stage too: the display transform, the stage's render features and the chain's `display` layer. It runs the `ui` stage as well (its `afterUI` render features, the chain's `all` layer and its `afterPost` render features) when it renders the picture as the screen presents it: a capture does, and so does a render-to-texture camera with `textureColorSpace = "presented"`. Any other texture camera's picture takes the `ui` stage from the frame that shows it, and one with `textureColorSpace = "linear"` holds the scene's light and runs neither the `display` stage nor the `ui` stage.
Where the built-in effects run:
| stage | built-in effects |
|---|---|
| `lighting` | occlusion, reflections, indirect light, contact shadows, subsurface scattering, area lights, decals, splats, outlines, debug draws and diagnostic views |
| `medium` | aerial perspective, height fog, volumetric light |
| `preTemporal` | depth of field |
| `temporal` | temporal antialiasing |
| `postTemporal` | motion blur |
| `meter` | the exposure meter |
| `optics` | lens flare (render feature), bloom (chain) |
| `display` | the display transform, then the temporal upscale, debanding, edge antialiasing (FXAA) and sharpening (RCAS, CAS), then the chain's looks and the film grain (`lensFx.grain`, `priority = "last"`) |
| `ui` | the UI, then the cutscene fade and letterbox (`priority = "last"`) |
| `output` | the surface encoding |
The stages, in frame order: `lighting`, `medium`, `preTemporal`, `temporal` (one effect at a time), `postTemporal`, `meter`, `optics`, `display`, `ui` and `output`.
- `list()` answers every stage in frame order, each a copy: `{ name, film, space, resolution, single, runs, feature, phases, chain?, chainFirst }`.
- `isFilm(name)` answers whether a stage is one of the camera's film, the exposure meter and the lens light (`meter`, `optics`): a pass a render feature places there, naming no `postProcessing` and no `presented` of its own, is part of the camera's post-process chain, so a camera running no post-processing (a capture asking for the scene ungraded, an environment face) skips it, and `postProcessing = false` on the pass keeps it on every camera.
- `get(name)` answers the stage a name names, or nil and a message listing the stages there are.
- `index(name)` answers where a stage stands in the frame, 1 for the first.
- `chainLayer(name)` answers the chain layer (`scene`, `display` or `all`) a post-process effect declaring that stage runs at, or nil and the reason.
- `stageOfLayer(layer)` answers the stage a chain layer's effects run in.
- `stageOfPosition(phase, order)` answers the stage a render-feature pass placed by phase and order stands in.
- `BAND` is how many orders one stage's band at a phase spans: a declared feature's local order counts from 0 up to, and short of, it.
# renderer.rayTracing
Ray tracing: `renderer.setRaytrace` and the readings of the scene acceleration structure a ray-tracing render feature traces against, transmission shadows, and the main camera's view.
# renderer.refs
How `renderer.*` names a live resource. A runtime resource is filed under a v4 guid, minted from OS entropy or given by the caller; and each call that names a resource takes whatever the caller already holds (the key or guid, the handle `create` returned, the CPU handle `load` returned, or an `AssetRef`) and coerces it to the key the renderer's stores index it by.
- `makeGuid()` mints a guid; `validateGuid(guid, what)` answers `guid` when it is a v4 guid and raises at the caller's line when it is not.
- `materialKey(value, what)`, `meshKey(value, what)` and `textureKey(value, what)` answer the registry key or guid a value names, and raise a rejection that lists the accepted forms.
- `refField(t, name)`, `declaredCategory(value)` and `shapeName(value)` read a ref-like table the way the coercions do.
- `primaryBytes(ref)` answers an asset's primary content bytes, waiting for them under a coroutine when they are still on their way; `textureRefOf(value, what)` answers the ref a texture asset's content is read through.
```luau
local Refs = require("modules.api.engine.renderer.refs")
local guid = Refs.makeGuid()
assert(Refs.validateGuid(guid, "example") == guid)
assert(Refs.meshKey({ kind = "MeshHandle", category = "mesh", guid = guid }, "example") == guid)
```
# renderer.sampling
Anisotropic texture filtering, and where in a pixel the projection samples: its offset and jitter.
# renderer.shaderSources
The programs the engine compiled for each feature set a shader was asked for, and the WGSL the compiler received for a shader.
# renderer.shading
The readings `renderer.shadingOf` builds out of the document the renderer publishes every frame.
- `shadingSubject(value, what)` answers the id a shading question names: an entity proxy's id, an entity-id string, or the registry key of a material in any form a material answers to.
- `publishedRenderable(doc, id)` answers the row that answers for a subject: the entity's own row, or a row drawing with the material, a fault wherever there is one.
- `materialRow(doc, id)` answers the renderer's record for one material.
- `shadingFault(state, means, row)` builds the fault reading a row carries.
```luau
local Shading = require("modules.api.engine.renderer.shading")
local doc = { renderables = { { entity = "e1", material = "m1", substituted = false } }, materials = {} }
local row = Shading.publishedRenderable(doc, Shading.shadingSubject("e1", "example"))
assert(row.material == "m1")
```
# renderer.shadows
Shadow caching and its page breakdown, the skinned and blended batching switches and the skinning pose hold, the shadow configuration and sizing, the caster cutoff, shadow proxies, the shadow views and the shadow hero.
# renderer.sources
The `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take.
- `classifyMesh(src)` answers which mesh src it is (`SRC_GPU`, `SRC_CPU`, `SRC_GEOMETRY` or `SRC_BUFFERS`), and raises for a src that is none of them or a geometry src whose indices address a vertex its positions do not carry.
- `vertexRecordsToArrays(src)` turns geometry written as per-vertex records (`vertices = { { pos, normal?, uv?, uv1? }, ... }`) into the parallel flat arrays the upload takes.
- `boundsFromPositions(positions)`, `vecToAabb(min, max)` and `ZERO_AABB` are the bounds a mesh is created with; `geometryCounts(src)` answers the vertex and index counts raw geometry implies.
- `classifyTex(src)` answers which texture src it is (`TSRC_GPU`, `TSRC_CPU`, `TSRC_PIXELS` or `TSRC_TARGET`).
```luau
local Sources = require("modules.api.engine.renderer.sources")
local src = { positions = { 0, 0, 0, 1, 0, 0, 0, 1, 0 }, indices = { 0, 1, 2 } }
assert(Sources.classifyMesh(src) == Sources.SRC_GEOMETRY)
print(Sources.boundsFromPositions(src.positions).max.x) -- 1
```
# renderer.specShapes
The shapes a render feature's passes are held in. A spec frozen all the way down reads the same on every frame, so the engine keeps it as it read it. A spec a render hands over unfrozen is held as a frozen copy when it reads the same as one handed at the same place in an earlier render, so a feature that builds its specs afresh every frame costs the engine what one handing over frozen specs costs.
- `wholeFrozen(spec)` answers whether a spec and every table inside it is frozen and carries no metatable.
- `heldShapeOf(row, spec)` answers the spec to hand over at the feature row's next place: the held copy the spec reads as, a new held copy, or the spec itself once the place's specs keep moving.
- `placed` holds the placed copy of each frozen spec a stage placed, by the spec it was placed from, with weak keys.
```luau
local SpecShapes = require("@builtin::modules.api.engine.renderer.specShapes")
assert(SpecShapes.wholeFrozen(table.freeze({ kind = "fullscreen" })))
assert(not SpecShapes.wholeFrozen({ kind = "fullscreen" }))
local row = { shapes = {}, handedN = 0 }
local first = SpecShapes.heldShapeOf(row, { kind = "fullscreen", order = 1 })
assert(table.isfrozen(first))
row.handedN = 0
assert(SpecShapes.heldShapeOf(row, { kind = "fullscreen", order = 1 }) == first)
```
# renderer.splat
`renderer.splat`: decodes a Gaussian splat capture into the GPU-ready byte pools a render feature uploads.
# renderer.temporal
`renderer.temporal`: the clock a per-frame effect draws itself against, and the holds that pin it.
# renderer.texture
`renderer.texture`: the texture codec, the guid-keyed CPU texture store, the GPU textures created from it, the render targets, and the readings of a texture's pixels.
# renderer.visibility
What the renderer decides to draw before it draws it: the resolution scale and its mode, the quality tier, the upscaler, the viewport and picture sizes, the screen-size and cluster-error cutoffs, occlusion culling, raster shading, the scene's lighting, and the ray cast against the geometry it draws.
# result
The handle `asset.list` returns.
A query result **is** the array of matched `AssetRef` handles. Entry `1` is the
first match, `#rows` is the count, `ipairs(rows)` walks it, and anything that
accepts a list of refs accepts it unchanged. The handle adds methods on top of
that array through a metatable, so reading the result stays one expression.
```lua
local hero = asset.list({ type = "mesh", fields = { tags = "hero" } }):first()
local prop = asset.list({ type = "mesh", path = "/zero/source/props" }):random()
asset.list("material")
:filter(function(m) return m.name:find("rust") ~= nil end)
:each(function(m) print(m.identity) end)
```
## Methods
| Method | Returns |
|---|---|
| `:first()` / `:last()` | One entry, or nil when the query matched nothing. |
| `:random()` | One entry chosen at random, or nil. |
| `:count()` | How many entries matched. |
| `:isEmpty()` | Whether nothing matched. |
| `:each(fn)` | The same result, after calling `fn(entry, index)` in order. |
| `:map(fn)` | A new result holding `fn(entry, index)` per entry. |
| `:filter(predicate)` | A new result holding the entries kept. |
| `:searchable()` | A new result without the deprecated assets, the ones a search or a picker offers. |
| `:sort(comparator?)` | A new, ordered result; ordered by identity when the comparator is omitted. |
| `:toArray()` | The entries as a plain table, without the handle. |
`:map`, `:filter`, and `:sort` return new results carrying the same methods, so
they chain. `:sort` leaves the result it was called on as it is.
## Ordering
`asset.list` already returns its matches ordered — by identity unless the query
asks for another field with `order` — so `:first()` names the same asset on
every call. `:sort` is for orders the query cannot express, such as one computed
from an entry's fields.
## What the handle does not change
The metatable carries `__index` alone. Length, `ipairs`, `pairs`, `next`,
`table.*`, and serialisation all read the array part, so a result behaves
exactly as a plain array everywhere those are used.
# asset_warmup
`asset.warmup` — a **read-only closure inspector**.
Returns the transitive set of assets that the CPU-residency system *would* load
when the given asset enters `/runtime/` — i.e. the asset plus everything
reachable through its declared content references. It does **not** itself change
residency or touch bytes:
```lua
local closure = asset.warmup("@builtin::meshes.cube")
-- → the asset + every texture/material/mesh it transitively references
```
Residency is owned by the engine's reference-counted CPU-residency system, which
acquires the closure on a `/runtime/` enter (usage 0→1) and releases it on the
last drop (→0), loading/unloading bytes at the per-node 0↔1 boundaries so a
texture shared by two materials stays resident until BOTH are gone. This helper
just lets scripts and agents **inspect** that closure (debugging, "what would loading
X pull in?") without any side effect — it avoids `asset.resolve` (which fires the
BlobStore prefetch) and uses the side-effect-free `asset.guid` / `asset.deps` /
`asset.identity`.
The closure is the generic `.refs` graph, so this is fully type-agnostic —
material/mesh/user-types all resolve the same way with zero per-type knowledge.
By default it follows `asset_ref` / `component` (content) edges and skips
`asset_type` (structural) / `require` (code); `opts.vias` overrides. Deduped by
guid via an explicit work-stack so diamonds appear once and cycles terminate.
Installed onto the FFI `asset` namespace by the prelude.
# frame_light
The scene's sun and ambient term as a render-feature pass reads them from the
`@frame.light` input: the light the surfaces of the drawn view are shaded by,
in the same frame. A participating medium lit through this module follows a
day cycle, a scripted sun and a switched-off one in the frame the surfaces do,
and goes black with them.
`@frame.light` is three `vec4`s:
| Word | Content |
|---|---|
| `[0]` | the direction the sun's light travels (unit, world space), intensity in `w` |
| `[1]` | the sun's colour, `w` 1 while it casts shadows |
| `[2]` | the ambient colour, intensity in `w` |
```yaml
# bindings.yaml
- { name: scene_light, kind: buffer, access: read, element: vec4<f32> }
```
```luau
ctx.enqueue { kind = "compute", program = prog, inputs = { scene_light = "@frame.light" }, ... }
```
```wgsl
#include "@builtin::shaderModules.frame_light"
let light = zero_frame_light(scene_light[0], scene_light[1], scene_light[2]);
let sun = zero_frame_light_sun_tint(light) * authored_sun_brightness;
let toward_sun = zero_frame_light_toward_sun(light);
```
`zero_frame_light_sun_share` is the share of a medium's authored brightness the
scene's sun lights: its intensity up to a unit sun, and 1 from there up. A
weaker sun dims the medium in proportion and a sun at 0 lights none of it.
`zero_frame_light_sun_irradiance` is the sun's light as the surfaces take it
(colour times intensity), in the units the scene's other lights (`@scene.lights`)
are stated in: a medium that scatters those as well takes the sun this way, so
the sun and the lights keep the balance they have on the surfaces.
`light.ambient` is the flat ambient irradiance (colour times intensity).
Pure math, no bindings.
# temporalAntiAliasing
Runtime control of the scene's temporal antialiasing.
```lua
local temporalAntiAliasing = require("@builtin::systems.antiAliasing.temporalAntiAliasing")
temporalAntiAliasing.enable({ historyWeight = 0.9, sharpness = 0.2 })
temporalAntiAliasing.get()
temporalAntiAliasing.active()
temporalAntiAliasing.disable()
```
`enable` creates the pass if it is not running and applies the settings; any
field left out keeps its current value. `disable` releases the pass and returns
the projection to sampling pixel centres, keeping the settings so a later
`enable` brings back the same tuning.
For antialiasing that persists with the scene, add the `TemporalAntiAliasing`
component instead — it drives this module from fields you can edit in the
inspector.
## Settings
| field | effect |
|---|---|
| `historyWeight` | How much of the accumulated result to keep each frame. Higher resolves more detail and settles smoother, at the cost of taking longer to let go of what a surface used to look like. Clamped short of 1, where the accumulation would stop taking in the frame being drawn. |
| `neighbourhoodClamp` | How far outside the neighbourhood's own colour spread an accumulated sample may sit before it is pulled back in. Lower rejects more, trading some of the settling for a result that follows change faster. |
| `sharpness` | How much of the edge lost to averaging over sub-pixel samples is added back. 0 leaves the accumulation as it is. |
| `motionRejection` | How much fast motion shortens the memory. A reprojection over a long distance is the most likely to have crossed onto another surface, so weighting the current frame up there is what stops a moving object trailing behind itself. |
## Choosing between this and edge antialiasing
Both are in this package and they correct different things.
`antiAliasing` (FXAA) works from the finished frame alone. It finds each edge and
shifts that pixel's sample across it, which fixes the staircase in a still image
at a fixed cost, and knows nothing about time — so a highlight that flashes on
and off between frames still flashes.
This one accumulates real samples, so it corrects what no single frame can see:
the crawling and flickering that only exist in motion, and sub-pixel detail no
one sample lands on. It needs the scene's velocity to do it, and pays for it with
a small amount of softening, which `sharpness` puts back.
Running both is reasonable — FXAA cleans up the edges within a frame while the
accumulation handles what happens between them.
# media_trace
Reads and writes the media trace: what the participating media and the
see-through draws laid over each pixel, in front of the opaque surface
`@scene.depth` holds. A full-frame pass (an outline, a toon ramp, a style
block) tells a cloud from the sky behind it, smoke from the wall behind it and
a water surface from the lake bed under it through it.
| Channel | `.r` | `.g` | `.b` | `.a` |
|---|---|---|---|---|
| `@scene.media` | cloud layer share | volumetric medium share (volume, smoke, fire, fog bank) | see-through surface share (blended draw, fluid surface) | coverage |
| `@scene.mediaSurface` | distance from the camera | world normal on the octahedron, x | y | coverage |
Every value but `.a` is premultiplied by the coverage. Each producer blends
its trace source-over what the draws behind it laid, so where several stand
in front of one another the nearer hold the larger share. A medium states the
direction back toward the camera as its normal. Both channels are zero where
nothing stands in front of the opaque surface.
A view keeps the trace only while a pass reads it: name `@scene.media` or
`@scene.mediaSurface` in a pass's `inputs`, at any phase from `afterSky` on,
the post-scene phases included. A pass writing the trace alone runs only on a
view that keeps it.
## Reading it
```yaml
# bindings.yaml of a compute pass
- { name: media, kind: texture2d }
- { name: media_surface, kind: texture2d }
```
```luau
ctx.enqueue {
kind = "compute", program = prog,
inputs = { media = "@scene.media", media_surface = "@scene.mediaSurface" },
stage = "postTemporal",
}
```
```wgsl
#include "@builtin::shaderModules.media_trace"
let m = textureLoad(media, px, 0);
let s = textureLoad(media_surface, px, 0);
let covered = media_trace_coverage(m); // 0..1
let kinds = media_trace_kinds(m); // cloud, medium, surface shares
let dist = media_trace_distance(s); // world units
let n = media_trace_normal(s); // world normal
```
## In front of a kept picture
A haze pass (the height fog, the aerial perspective) fogs the opaque scene
once it is lit and before the transparent phase draws (`afterOpaqueLit`), keeps
that picture, and in the `medium` stage takes what the trace lays in front of
it at its own distance. `media_trace_in_front(media, surface, sky)` states that
part of the trace: its `coverage`, the `cloud` share inside it and its
`distance`. Every producer lays its trace after that seam but the cloud layer
over the sky, so over the sky the cloud belongs to the kept picture.
```wgsl
let f = media_trace_in_front(m, s, depth <= 0.0);
// What covers the pixel, premultiplied: the frame less the kept picture
// showing through it.
let layer = frame.rgb - (1.0 - f.coverage) * kept.rgb;
```
## Writing it
A producer lays its trace with a raster pass whose `fs_main` returns
`@location(0)` for `@scene.media` and `@location(1)` for
`@scene.mediaSurface`, both blended `"premultiplied"`:
```wgsl
let t = media_trace_lay(coverage, MEDIA_TRACE_MEDIUM, distance, -view_dir);
out.media = t.media;
out.surface = t.surface;
```
```luau
ctx.enqueue {
kind = "raster", shader = traceShader, vertexCount = 3,
outputs = {
{ target = "@scene.media", blend = "premultiplied" },
{ target = "@scene.mediaSurface", blend = "premultiplied" },
},
...
}
```
Every blended material draw lays its trace itself, as a see-through surface
at its own distance and normal, covering the share of the pixel its blend
equation changes:
| Blend | Coverage |
|---|---|
| `alpha`, `premultiplied` | the colour's alpha |
| `additive` | the strength of the light it adds: its brightest channel, saturating at 1 |
| `multiply` | how far the factor it scales by departs from 1, in its farthest channel, saturating at 1 |
So an additive glow card lays its trace where it glows and none across the
dark of its quad, and a multiply grime card lays none where its factor is
white.
# field
Single-field component schema builder. Every `public.X` on a component
declares its type, default value, and Sync/NoSync replication mode in
one place via the `Field.<kind>(default, mode)` constructor that
produces a `FieldDesc<T>` descriptor. The engine walks `public` at
component registration, extracts each descriptor into the
per-component asset-fields + sync registries, runs each asset default
through the category-aware resolver, and replaces the descriptor with
its unwrapped default so user code reads `public.X` as the value (not
the descriptor).
This module is exposed as the `Field`, `Sync`, and `NoSync` Luau
globals via `--!global` directives. Component authors call
`Field.<kind>` and `Sync` / `NoSync` directly without a `require`.
`--!global-types` exports `SyncMode`, `FieldDesc<T>`, `AssetRef<C>`,
`EntityRef`, and `ComponentRef<T>` to every typed source.
## Exports
- `Field.number(default, mode, marker?) -> FieldDesc<number>`
- `Field.range(min, max, default, mode, marker?) -> FieldDesc<number>`
- `Field.integer(min, max, default, mode, marker?) -> FieldDesc<number>`
- `Field.string(default, mode, marker?) -> FieldDesc<string>`
- `Field.enum(values, default, mode, marker?) -> FieldDesc<string>`
- `Field.bool(default, mode, marker?) -> FieldDesc<boolean>`
- `Field.vec2(default, mode, marker?) -> FieldDesc<vec2>`
- `Field.vec3(default, mode, marker?) -> FieldDesc<vec3>`
- `Field.quat(default, mode, marker?) -> FieldDesc<quat>`
- `Field.color(default, mode, marker?) -> FieldDesc<color>`
- `Field.entityRef(default, mode, marker?) -> FieldDesc<EntityRef>`
- `Field.assetRef<C>(category, default, mode, marker?) -> FieldDesc<AssetRef<C>>`
- `Field.dataRef<C>(contract, default, mode, marker?) -> FieldDesc<AssetRef<"data">>`
- `Field.componentRef<T>(componentType, default, mode, marker?) -> FieldDesc<ComponentRef<T>>`
- `Field.table<T>(default, mode, marker?) -> FieldDesc<T>`
- `Field.alias(target, description?) -> FieldDesc<any>`
- `Sync` / `NoSync` — string singletons used as the replication-mode argument.
Every constructor's trailing `marker` argument accepts the bare
`Serialized` marker (unchanged meaning), a plain string read as the
field's description, or a `FieldOptions` table carrying `serialized`
and/or `description`.
Types (global via `--!global-types`):
- `SyncMode = "Sync" | "NoSync"`
- `FieldOptions = { serialized: SerializedMode?, description: string? }`
- `FieldDesc<T> = { __zero_field: boolean, kind: string, default: T?, sync: boolean, serialized: boolean?, description: string?, enforced: boolean, category: string?, componentType: string? }`
- `AssetRef<C> = { __ref: string, type: C, name: string, guid: string, identity: string, path: string, primary: string? }` — the envelope `asset.resolve` / `asset.ref` / `asset.list` hand back. The category is in `type`; `primary` is the single content file the resolver found, which `getSource` reads, falling back to `path`.
- `EntityRef` — the live entity proxy (`entity(id)` / `entity.spawn()` / `bundle:instantiate()` return it; carries `id`, `name`, `position`, `component`, …). An `entityRef` field accepts a proxy OR a raw id string on write and reads back a live proxy (`.id` for the string, `nil` if unset); the stored/serialised form is the plain id.
- `ComponentRef<T> = { __ref: string, entity: string, componentType: T }`
## Usage
```luau
-- Inside a `public` block on a component
public = {
positionX = Field.number(0, Sync),
speed = Field.number(5, Sync, "Metres per second at full throttle."),
enabled = Field.bool(true, Sync),
material = Field.assetRef("material", "@my-library::materials.gold", Sync),
source = Field.assetRef("bundle", nil, Sync),
target = Field.entityRef(nil, Sync),
aimCam = Field.componentRef("Camera", nil, NoSync),
idMap = Field.table({} :: { [string]: string }, NoSync),
}
```
## Notes
- `Sync` / `NoSync` is REQUIRED on every constructor. Passing `nil`,
`true`, `false`, or anything else raises a load-time error so a
multiplayer-by-default engine can't silently ship single-player
components.
- `Field.assetRef`'s `category` argument is inferred as a singleton
string type (`C`). Cross-category assignment is therefore a type
error: `AssetRef<"mesh">` does not unify with `AssetRef<"material">`.
- `Field.componentRef`'s `componentType` argument works the same way —
the engine validates the referent's component type at every write.
- `Field.table<T>`: pin the shape by ascribing the default,
`Field.table({} :: MyShape, NoSync)`.
- A live component proxy held in a `Field.table` value, at any depth,
is saved in the scene record as its reference: the
`{ __ref, entity, componentType }` envelope `Field.componentRef`
stores, so a component holding itself saves one envelope naming
itself.
- `Field.range` and `Field.enum` carry a `constraint` the engine checks
on the field's default and on every write, through
`field_constraints.module`. A value outside the declared interval or
member set is refused with the interval or the whole set named, so
what the field reads back is a value its consumer can use.
- `Field.integer` carries the same `range` constraint with `whole = true`:
a fraction is refused as well as a value outside the interval, for a
count, a level or a group number, where a fraction would be read as some
other whole number.
- The engine resolves any string default for `assetRef` through
`asset.resolve(identity, category)` at component registration, so the
first read of `public.<field>` returns a resolved envelope, not a raw
string.
- `Field.dataRef` rides the same `assetRef` machinery (category
`"data"`) plus a contract gate: every write (and the registration-time
default) must resolve to a `.data` instance whose dataType contract
chain includes `contract`, checked through the generic field-constraint
hook. A rejected write raises and leaves the field's previous value
unchanged.
- Constrained fields (`Field.dataRef`) are top-level only — declaring
one inside `Field.struct` / `Field.list` aborts component registration
with an error.
- `FieldDesc.enforced` is true exactly for the kinds that carry a
`constraint` (`enum`, `range`, `bitmask`, `dataRef`, `taggedRef`,
`instantiableRef`) — the field the `field_constraints` hook checks on
every write and default. Every other kind reads `enforced = false`.
# ssr
Screen-space reflections — polished floors reflect what stands on them, from
the frame the engine has already drawn.
```lua
local ssr = require("@builtin::systems.reflections.ssr")
ssr.set({ intensity = 1, maxDistance = 40, quality = "high" })
ssr.get() --> the settings in force
ssr.active() --> are the reflection passes running
ssr.clear() --> off, settings kept for the next set()
```
`set` takes any subset — omitted fields keep their current value, so adjusting
one knob does not mean restating the rest. An `intensity` of 0 turns
reflections off and releases the passes rather than running them at zero
strength.
`roughnessCutoff` is where the reflection starts handing over to the probes and
the sky. A surface at or below it takes the full screen-space reflection, one
0.1 above it takes none, and between the two the reflection fades out. The
default, 0.75, covers wet asphalt and polished stone.
`maxDistance` and `quality` trade against each other. Quality sets how many
steps the march spends, so a long distance at a low quality samples coarsely —
reflections thin out at range rather than disappearing, because refinement
adapts to the step size on its own.
For reflections a scene should simply have, author the
`ScreenSpaceReflections` component instead — it carries the same settings,
persists with the scene, and edits live in the inspector. This module is for
code that changes reflections at runtime: a quality slider, a cutscene, weather
turning pavement wet.
The full description of what each knob does and how the passes work is in the
package readme: `guides { path = "systems/reflections" }`.
# gbuffer_material
The G-buffer's surface description, and the one encoding of it.
`@scene.shaded` carries what a surface sent — the light the geometry pass shaded
it to, scene-referred and unbounded above 1. `@scene.material` carries what the
surface is: the base colour it reflects, how metallic it is, and how rough. A
screen-space pass that multiplies incoming light by a reflectance — a bounce
multiplier, a Fresnel tint, an ambient floor — reads the second.
The channel is `Rgba8Uint`. The pass that fills the G-buffer holds 128 bits of
colour a pixel, the storage a tile-based GPU keeps on chip at its full tile
size: the shaded colour takes 64, the normal 32, and this channel the 32 left,
so 32 bits is the entire budget:
| Lane | Content |
|---|---|
| `.r` | base colour, RGB565 low byte |
| `.g` | base colour, RGB565 high byte |
| `.b` | metallic |
| `.a` | perceptual roughness |
Base colour lands at 5/6/5 — steps of about 3% per channel. Metallic and
roughness keep a full byte each.
The geometry pass packs through `zero_gbuffer_pack_material`; every reader
unpacks through this module, so the layout is stated once.
Pure math, no bindings.
```wgsl
#include "@builtin::shaderModules.gbuffer_material"
// bindings.yaml: - { name: scene_material, kind: texture2d, sample: uint }
let m = zero_gbuffer_material(scene_material, coord);
let bounce = incoming * m.base_color;
```
One value at a time:
```wgsl
let base = zero_gbuffer_base_color(scene_material, coord);
let metallic = zero_gbuffer_metallic(scene_material, coord);
let roughness = zero_gbuffer_roughness(scene_material, coord);
```
A `.computeShader` reading the channel declares its slot `kind: texture2d` with
`sample: uint`, because an `Rgba8Uint` texture binds as `texture_2d<u32>`. The
engine refuses the pass when the declared sample type and the bound texture's
format disagree, and names both.
## Signatures
```wgsl
struct ZeroGbufferMaterial {
base_color: vec3<f32>,
metallic: f32,
perceptual_roughness: f32,
}
fn zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial
fn zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial
fn zero_gbuffer_base_color(t: texture_2d<u32>, coord: vec2<i32>) -> vec3<f32>
fn zero_gbuffer_metallic(t: texture_2d<u32>, coord: vec2<i32>) -> f32
fn zero_gbuffer_roughness(t: texture_2d<u32>, coord: vec2<i32>) -> f32
```
`texel` is one `textureLoad` result off `@scene.material` — the four raw
`u32` lanes before this module gives them meaning. `t` is the bound
`@scene.material` slot itself (`texture_2d<u32>`, declared `sample: uint`);
`coord` is the pixel to read, an integer texel coordinate (`vec2<i32>`) — the
same `textureLoad`-shaped argument every accessor and `zero_gbuffer_material`
take. The three single-value accessors are `zero_gbuffer_material` narrowed to
one field, for a caller that wants only one of the three.
The channel is a G-buffer channel, so the deferred G-buffer fragment entry is
what writes it: an opaque draw on the deferred path. A pixel no geometry wrote
reads a black surface at metallic 0 and mid roughness.
# light_shadows
The shadows the scene's point, spot and area lights cast, as a render-feature
compute pass reads them: the same shadow pages the surfaces are shadowed by. A
participating medium shadowed through this module is dark from a light wherever
a surface standing at that point would be, so a lamp sealed in a box lights
none of the air outside it, and a beam ends at the wall it meets.
The pass binds the scene's light buffer and the shadow pool under these names:
```yaml
# bindings.yaml
- { name: lights, kind: buffer, access: read, element: vec4<f32> }
- { name: shadow_pool, kind: texture_depth }
```
```luau
ctx.enqueue {
kind = "compute", program = prog,
inputs = { lights = "@scene.lights", shadow_pool = "@scene.shadowPool" },
...
}
```
```wgsl
#include "@builtin::shaderModules.light_shadows"
// 1 where nothing stands between light row `li` and `p`, 0 where an occluder does.
let lit = zero_light_shadow(li, p, footprint);
```
`footprint` is the world size of the detail the pass resolves at `p`, such as
a medium's sample spacing or a pixel's width there: the finest shadow mip read
is the one whose texel is no smaller. A light that casts no shadow reads 1, and
a single-sided rect light closes past the edge of the frustum it casts through,
as it does on a surface.
A frame with a pass reading `@scene.shadowPool` keeps the coarsest page of
every map of each casting light whose reach meets the view, so every point a
light reaches in that view has a page to be read from. Where a surface asked
for a finer page of the same place, that page is read.
# assetType.shared.settings
Resolves four questions about an asset's typed settings, all answered from its
type's `type.yaml` — nothing here is found by convention.
```lua
local Settings = require("@builtin::assetTypes.assetType.shared.settings")
-- or, from inside the assetType runtime:
local Settings = require("@builtin::assetTypes.assetType.shared").settings
```
## Where does a type's schema live?
`type.yaml` names it in a `settings:` block:
```yaml
settings:
values: "settings.yaml" # where an instance's own values live
schema: { type: "settings.luau" } # one schema for every asset of this type
```
or, for a type whose settings differ per instance (an importer):
```yaml
settings:
values: "settings.yaml"
schema: { instance: "settings.luau" }
```
or, for a type whose schema is a table its instance's own source declares and
whose values live elsewhere (a component: its `public` fields, valued on each
entity it is on):
```yaml
settings:
schema: { instance: "init.luau", export: "public" }
```
Whether an instance may lack its schema file is what the type's `files:`
block says of that file. Listed under `files.optional`, it may be absent, and
an instance without it declares no settings — the importer type lists it
there, since most importers take none. Listed under `files.required`, or not
listed at all, it must load, and an instance missing it is a broken
declaration and is logged.
`schema.type` is required at the folder relative to the TYPE's own
`.assetType/` directory (one schema shared by every instance).
`schema.instance` is required relative to each INSTANCE's own folder (`init`
resolves the instance's own identity; anything else is a sibling module under
it). Without `schema.export`, the file is required as a module and its return
value IS the schema. With `schema.export`, the file is run in an environment
of its own and `export` is read from a returned table carrying it, or else
from the globals the file assigned — a component's `public` is such a global.
With `schema.export_optional: true`, a file that declares no such table has an
empty schema: the type's instances declare their parameters there and may have
none (a render feature with nothing to tune). Without it, the table is
required, and a file declaring none is a broken declaration and is logged.
That environment reads through to `_G` and takes every write itself; its own
`_G` is itself, its `declare` and `computed` record into it, and its `task`
records spawned, deferred and delayed work instead of starting it. Every other
global is the real one, so a call the file makes through one runs as it does
anywhere. The schema is the declared table's Field descriptors. A schema that
resolves to nothing says why through `Settings.schemaProblemOf(ref)`: the file
could not be read, compiled or run, or declared no such table. An instance
schema is read again when its file, its type's `type.yaml`, or the entry file
of any module the asset `require`s changes. `Settings.blockFor(typeName)`
returns the raw block; `Settings.schemaForType(typeName)` and
`Settings.schemaOfInstance(ref)` resolve the two schema shapes respectively;
`Settings.schemaFor(ref)` tries the type-level schema first, falling back to
the instance-level one. `ref` naming an assetType asset itself — e.g.
`asset.resolve("texture", "assetType")`, rather than an instance of it —
reports that type's own declared schema, the same one every instance of it
reports.
## Where do an asset's values live?
`settings.values` names a file living beside the asset's own content —
`Settings.valuesPathOf(ref)` joins it onto the asset's path.
`Settings.valuesOf(ref)` / `Settings.writeValues(ref, values)` read and write
it; this module only names where it is. A type that declares its schema with
no `settings.values` keeps no values in the asset — a component's live on each
entity it is on — so `valuesOf` answers nil for it, `asset.create` refuses a
`settings` table for it, and `asset.setSettings` refuses a write.
`Settings.recordedWrite(path, text)` writes a file the way every values file
is written, and an editor uses it for any other file it writes. It writes the
whole contents, records the write into the open undo operation when one is
open (so undoing it restores what the file held), and raises when the write
does not land.
## In what order are a schema's fields declared?
Every `Field.*` constructor stamps its descriptor with `declaredOrder`, one
more than the last. Luau evaluates a table constructor's entries in the order
they are written, so `Settings.orderedNames(schema)` lists a schema's fields —
and a struct's subfields — in the order the source writes them.
`asset.setSettings(ref, patch)` writes a partial patch:
`Settings.resolvePatch(ref, patch)` merges it over the current
values and applies the type's derived defaults for the fields it changed, and
`Settings.writeValues(ref, values, patch)` applies the corrections, checks the
schema and writes the file.
## How is a new asset's settings resolved at creation?
`asset.create` calls `Settings.resolveForCreate(typeName, name, destPath,
creationOpts, callerSettings, importerSettings)` before running the type's
`onCreate`, checks the result against the schema, writes it to the values
file, and hands `onCreate` a COPY of it as `opts.settings` (`Settings.
cloneValues`) — never the same table the values file gets, so nothing
`onCreate` does to its own copy can reach what was stamped. `onCreate` reads
settings from `opts.settings` and never writes to it. `asset.create` also
seeds the change baseline with the stamped values
(`Settings.seedChangeBaseline`), so the values file's own first dispatch
reports nothing changed and the payload `onCreate` encoded is the only
encode a create runs.
The layers, lowest priority first, each overriding the ones before it field
by field:
1. The schema's own declared defaults (`Settings.defaultsOf`).
2. The type's own `settingsDefaults(name, opts, asked)` hook, when its
`behavior.luau` exports one. `asked` holds what layers 3 to 5 name, so a
default can follow a field one of them sets.
3. The Preset Manager's matching row (`Settings.presetLayerFor`).
4. The creating importer's settings for this type.
5. The `settings` table the caller passed to `asset.create`.
6. The type's own `settingsDerivedDefaults(values, explicit, changed)` hook,
when its `behavior.luau` exports one — a field whose default follows
another field, set only when no layer from 2 to 5 named it.
7. The type's own `settingsCorrections(values, name, opts)` hook, when its
`behavior.luau` exports one — applied last, once every other layer has
merged.
Layer 7 is `Settings.applyCorrections(typeName, values, explicit, context)`,
the one corrections path every settings write takes — this create chain, and
`Settings.writeValues` for every later write (`asset.setSettings`, a type's
first-encode seed). `explicit` names the fields the writer
asked for: the caller's `settings` table here, the patch for
`asset.setSettings`. A correction lands SILENTLY on a field the writer did not
name — nobody asked for that value, so overriding it just states a fact. A
correction that contradicts a field the writer named REFUSES the write,
naming the field, the value asked for, and why it cannot hold — the same as
every other place this codebase refuses an explicit request it cannot satisfy
(a `Field.checkSchema` violation, a BC7 alignment error) rather than silently
rewriting it into something else. So `asset.setSettings(tex, { compression =
"rgba16" })` on a mipped texture stores `generateMipmaps = false` beside it,
while `asset.setSettings(tex, { compression = "rgba16", generateMipmaps = true })`
is refused.
`Field.checkSchema` runs once, over the result AFTER the corrections hook has
applied — a bad value nothing corrects refuses the creation.
### Three hooks, three different jobs
Every hook is an optional export on a type's `behavior.luau`, alongside
`onCreate` / `onChange`. **None is ever handed a table to mutate** — each
reads what it's given and RETURNS a table of what it wants changed (or nil);
`resolveForCreate`, `resolvePatch`, `applyDerivedDefaults` and
`applyCorrections` are the only places that write to the values, by merging
what a hook returns the same way every other layer merges.
- **`settingsDerivedDefaults(values, explicit, changed) -> partial?`**
answers the values of fields whose default follows another field. At
creation `changed` holds every field; on a write it holds the fields the
write moved. A returned field applies only where `explicit` — the fields
the writer named — does not name it.
- **`settingsDefaults(name, opts, asked) -> partial?`** supplies a DEFAULT
the schema itself has no syntax for — something only knowable at creation
time, like a naming convention, a fact read off a payload the caller handed
in, or a value that follows a field a higher layer sets (`asked` holds what
the Preset Manager, the importer and the caller name, the higher one's
value where two name a field). It runs early (layer 2 above), so any later
layer — Preset Manager, importer, caller — freely overrides it.
`texture.assetType`'s returns the `textureType` the name suggests (a
`_normal`-suffixed name is a `normalMap`), `compression = "uastc"` and
`maxDimension = 4096`, with `rgba8` for a `textureType` of `sprite` that a
higher layer names; for a pre-encoded ZTEX payload it returns the colour
space, compression and sampler the payload's own header carries. Either
way, an explicit `settings = { ... }` from the caller still wins.
- **`settingsCorrections(values, name, opts) -> (partial?, reasons?)`**
enforces a CROSS-FIELD CONSTRAINT the schema itself has no syntax for — a
fact about one field that depends on another field's resolved value, true
regardless of which layer produced that value. It runs last (layer 7
above), over the fully merged `values`, and again on every later write of
the values file. Nothing is left unmet in what gets
validated and stamped — but a value the caller explicitly asked for is
never silently rewritten to satisfy it; `applyCorrections` refuses instead
(see above). The optional second return, `{ [field]: reason }`, supplies
the "why" for that refusal message; a field with no reason falls back to a
generic one. `texture.assetType`'s returns `{ generateMipmaps = false,
maxDimension = 8192, colorSpace = "linear" }` whenever the RESOLVED
`compression` is high-precision (the encoder stores one verbatim, linear,
and refuses a mip chain or a downsample for it outright), paired with a
reason naming the compression, and `nil` otherwise.
## What does a declarer declare?
`Field.settingsOf(identity, mode)` embeds another declarer's schema as a
struct field without restating it. The identity names one of two kinds of
declarer, and `Settings.schemaOfDeclarer(identity)` tells them apart by what
`identity` resolves to:
- **An assetType** (e.g. `"@builtin::assetTypes.texture"`) — embeds the
schema every instance of that type carries, resolved via
`schemaForType`. This is the type-level shared schema from the section
above, not a per-instance one — an assetType has no settings of its own
to declare per instance.
- **Anything else** (an importer, or any other asset that declares settings
of its own) — embeds that asset's own schema, resolved via
`schemaOfInstance`.
Every schema this module serves has already run its `Field.settingsOf`
fields through this resolution — a caller reading `schema.someField.fields`
never sees an unresolved `declarer` with no `fields`. Resolution descends
into an already-literal struct's `fields` and a list's `element` the same
way, so a declarer embedded several fields deep is still reached. A declarer
that embeds itself, directly or through another declarer, stops one level
short of the loop instead of recursing forever.
## What are the defaults?
`Settings.defaultsOf(schema)` reads every field's declared `default` into a
plain table — a field declared without one is absent from the result rather
than holding a `nil` value.
# appliedSystem
What a scene-wide effect held by its asset needs beside the `applicable` gate:
which application of the asset is in force, the asset's live values, a system
API's write landed where the value takes effect, and the runtime hands on a
system whose render feature asset is self-contained.
```lua
local AppliedSystem = require("@builtin::modules.appliedSystem")
-- From a type's own apply / setEnabled / drop:
AppliedSystem.track(self, owner, opts) -- on/off, the owner's writer, newest statement
AppliedSystem.trackEnabled(self, owner, enabled)
AppliedSystem.untrack(self, owner)
AppliedSystem.inForce(ref) -- the owner that last stated something new and is on
AppliedSystem.applications(ref) -- { { owner, enabled, stamp } }
AppliedSystem.values(ref, owner) -- own values, then live values, then what the owner stated
AppliedSystem.setLive(ref, { density = 0.03 })
AppliedSystem.resetLive(ref)
AppliedSystem.write(ref, { density = 0.02 }, "fog.set")
```
`write` sets the live value of a parameter the application written through does
not state, and writes one it does state through that owner's writer, the
`opts.write` it handed `apply`; a stated parameter whose owner handed no writer
raises naming the API, the parameter and the owner. `opts.owner` names the
application written through, else the one in force; `opts.owned` sends every
parameter through the writer. Live values are shared by every application of
the asset for the session mode and go with its runtime state; changing them
applies every application of the asset again. A value equal to the one its
layer already holds (the owner's stated value, or the live value) is left as it
is: `write` hands it to no writer and `setLive` applies nothing for it, so a
script can state the same values every frame for the cost of comparing them.
A system's module and component:
```lua
local system = AppliedSystem.module({
identity = "<render feature identity>",
api = "<system>.set",
owner = "<system>.api",
changes = function(o, _current) return { intensity = o.intensity } end,
drawing = function(values) return (values.intensity or 0) > 0 end,
})
system.set({ intensity = 0.5 }) -- lands where the value takes effect
local life = AppliedSystem.component({
identity = "<render feature identity>",
name = "<Component>",
fields = { "intensity" },
values = function(p) return { intensity = p.intensity } end,
})
function awake() life.awake(public) end
function onDestroy() life.onDestroy(public) end
```
`set` applies the asset for the module's own owner when nothing applies it, and
lands each value with `write`. `valuesOf(ref)` reads the values in force.
# persist.origin
Provenance / origin-context layer for the persist (create-flow) system.
The problem persist must solve: when the agent freezes live play state into
`scene.json`, it must capture **only** the things that would not otherwise be
reproduced on the next load — i.e. creations whose stack root is the agent's
ad-hoc `execute()` context. Anything created by `onLoad` / the scene loader or by
a component callback re-runs on every load, so freezing it would duplicate it.
This layer tags each live creation with its origin context (via wrappers
installed over the entity API) and exposes the current origin, so the serializer
can keep execute-origin entities and drop the rest.
# contract
The shared half of `applicable`. Every call of `apply`, `setEnabled` and
`drop` on an asset whose type implements the interface passes through `gate`,
which checks the owner, the values against `asset.schema`, and `opts.enabled`;
keeps one record per application (the values the owner stated and whether it
is on); calls the type with the asset's own values and what the owner stated
laid over them; and checks the returned `ApplyState` (`status`, `heldBy`,
`notice`).
```lua
local Apply = require("@builtin::interfaces.applicable.contract")
Apply.values(self, owner) -- the values the application receives
Apply.stated(self, owner) -- what the owner stated, sparse
Apply.restate(guid?) -- apply the records again
```
After an edit/play flip, a render-device rebuild and an edit of an applied
asset, the contract applies every record of the asset again, and each type puts
back what of its effect is gone.
# i18n
The player's language: which of a world's languages to show them, the
languages their platform says they read, the locale the engine chose for its
own text, the locales the engine offers, their own choice, and a signal when
any of it changes. The same `i18n` global in every VM.
```lua
local lang = i18n.pick({ "en", "pt", "es" }) -- "pt" for a Brazilian player
i18n.emulate({ "es-MX" }) -- try the world as a Mexican visitor; nil puts this machine's back
print(i18n.locale()) -- "en"
print(i18n.preferred()[1]) -- "pt-BR" on a device set to Portuguese (Brazil)
for _, l in i18n.offered() do print(l.tag, l.nativeName) end
local r = i18n.choose("pt-BR") -- refused unless pt-BR is offered
if not r.ok then log.warn(r.reason) end
local id = i18n.onChange(function(locale, preferred)
log.info(("now %s; platform %s"):format(locale, table.concat(preferred, ",")))
end)
i18n.offChange(id)
```
## How the locale is chosen
One chain, the first link that matches an offered locale deciding:
1. the player's choice (`i18n.choose`), kept on the device for their ZeroMind
account, or for the signed-out player;
2. the language ZeroMind shows the player (the `zeromindLocale` boot argument
ZeroMind's page passes, or the desktop `--zeromind-locale`), and the one
the page names when its reader picks another language while the browser
engine runs;
3. the platform's preferred languages, most preferred first;
4. `en`, the engine's source language.
A link matches an offered locale with the same tag, then one its tag
truncates to (`pt-BR-x-abc` to `pt-BR`), then one with the same language
(`pt` to `pt-BR`). The engine offers a locale once its manifest is launched,
and it offers `en` and `pt-BR`; a player none of whose links matches either
gets `en`. `i18n.sources()` names every link and the one that decided.
The chosen locale is also the one the engine names to ZeroMind on its requests
(`x-zeromind-locale`) and the one the text system picks fallback fonts for.
## API
- `i18n.pick(available) -> string`: which of the content's languages the
player reads (the first of `available` when none matches).
- `i18n.emulate(tags?) -> { ok, locale?, platform?, reason? }`: stand a
visitor's language list in; nil reads the platform's own again.
- `i18n.locale() -> string`: the chosen locale.
- `i18n.fallback() -> {string}`: the chosen locale's fallback chain.
- `i18n.preferred() -> {string}`: the platform's preferred languages.
- `i18n.offered() -> {Locale}`: `{ tag, name, nativeName, fallback }` per
offered locale.
- `i18n.choice() -> string?`: the player's own choice.
- `i18n.choose(tag?) -> { ok, locale?, decidedBy?, reason?, offered? }`:
choose, or clear with nil.
- `i18n.sources() -> Sources`: `{ locale, decidedBy, matched, choice,
zeromind, platform, signedIn, choiceKept }`; `choiceKept` is `device`, or
`run` in an offline engine, which keeps a choice for that run alone.
- `i18n.onChange(fn(locale, preferred)) -> id` / `i18n.offChange(id)`.
## Where the platform list comes from
| platform | source | changes reach the engine |
|----------|--------|--------------------------|
| Linux | `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, `LANG` | at boot |
| Windows, macOS | the user's language list | at boot and when the window regains focus |
| browser | `navigator.languages` | on `languagechange` |
| Android | the activity's configuration locales (the per-app language when set) | on the configuration change, without restarting the app |
# edui.inspector.parts
The building blocks a type's `inspector.luau` composes its sections from. Every
Context carries this module as `ctx.parts`, so an inspector file requires
nothing from `@builtin::editor`:
```luau
return { sections = { {
id = "summary", title = "Summary",
build = function(ctx)
local rows = ctx.parts.facts(ctx, {
{ label = "Vertices", value = 24 },
{ label = "Size", value = ctx.parts.bytes(1536) },
})
local n = #rows
for _, node in ipairs(ctx.parts.action(ctx, "rebuild", "Rebuild", function() ctx.ref:rebuild() end)) do
n += 1
rows[n] = node
end
return rows
end,
} } }
```
Every function takes the section's Context first and returns a list of edui
nodes, unless stated.
| Part | What it shows | Callback key |
|---|---|---|
| `format(v)` | a value as text: integers plain, other numbers to 4 significant digits, booleans yes/no, a list as its length, a map as its entry count (returns a string) | — |
| `bytes(n)` | a byte count as text: `84 B`, `1.5 KiB`, `2.00 MiB` (returns a string) | — |
| `facts(ctx, rows, empty?)` | label/value rows (`{ label, value, mono? }`); the value takes the width its label leaves and wraps within it; a row whose value is nil shows "—", so a value that could not be read is seen to be missing. A row that does not apply to the subject is left out of `rows` by the section; with no rows `empty` shows | — |
| `list(ctx, items, { max?, empty?, mono? })` | one text row per item, at most `max` (40), then "… and N more" | — |
| `table(ctx, key, columns, rows, empty?)` | a table of records, each cell through `format` | `<keyPrefix>:tbl:<key>` (widget id) |
| `links(ctx, refs, { max?, empty? })` | one button per asset (an AssetRef, a `{ __ref = guid }` envelope, or a guid or name), named and typed; clicking selects it. An item that does not resolve is listed as text | `<keyPrefix>:link:<guid>` |
| `entityLinks(ctx, ids, { max?, empty? })` | one button per entity, by name; clicking selects it. An id whose entity no longer exists is listed as text, marked despawned | `<keyPrefix>:ent:<id>` |
| `action(ctx, id, label, run, { primary? })` | a button running `run`; a run that raises shows its message beneath the button until the next run | `<keyPrefix>:act:<id>` |
| `openFile(ctx, path, label?)` | an action opening `path` in the Code panel; nothing when the file is absent | `<keyPrefix>:act:open:<path>`, the path relative to the subject's folder |
| `problems(ctx, problems, clean?)` | one notice per `{ message, code?, severity?, line? }` (error tone, or info for a warning, info or hint), or `clean` ("No problems.") | — |
| `swatch(ctx, color, label)` | a colour square (`{ r, g, b }` in 0..1) beside its label and hex (returns one node) | — |
| `cached(key, paths, compute)` | `compute()`'s value, computed again only when the content version of one of `paths` moves (returns the value). Read through `ctx.parts`, it is held while a Context that read it stays open; read through the module itself, until the next `Inspector.release` | — |
| `state(ctx)` | the table a Context's sections keep state in between builds (a picked zoom, a chosen tab), forgotten when the Context is released (returns the table) | — |
| `check(ctx, path)` | a "Check" action running `lsp.check(path)`, then the counts and diagnostics of the last check of the file's current content | `<keyPrefix>:act:check:<path>`, the path relative to the subject's folder |
| `values(ctx, { subject, schema?, values?, write?, readOnly? })` | typed controls over any values: one control per schema field, each edit checked with `Field.check` and written through `write` inside one undoable operation; `readOnly` shows the values with no control that writes. The same subject shown by two Contexts keeps two states | `<keyPrefix>:val:<subject>:set:<field>` |
## Rules a section keeps
- **No write in `build`.** A build only reads; writes happen in an action's
`run`, in `ctx.setSettings`, or in a `values` part's `write`.
- **Expensive reads are once per content version.** A build that decodes a
payload, walks a file or asks the LSP goes through `cached` (keyed on the
files the value comes from) or runs behind an action. `check` holds each
file's last result for as long as the file's content is unchanged.
- **Every callback key starts with `ctx.keyPrefix`**, so two subjects — the
panel's asset and an inline editor of the same asset — never share one.
- **What the parts hold goes with the Context.** `ctx.parts` is the parts as
that Context reads them. `Inspector.release(keyPrefix)` forgets the
Context's action failures, file checks and state, and every cached value no
other open Context read.
# contactShadows
Runtime control of the scene contact shadows — `.set` / `.get` / `.clear` /
`.active`, with `.lights` reading back the lights this frame's traces aim at
and `.refresh` re-reading the scene's lighting. `set` takes any subset; omitted fields keep their value, and a
`strength` of 0 releases the render pass.
Every world runs contact shadows at `DEFAULTS` while its `render.contact_shadows`
setting is on and nothing else states them (`followWorld`, which the world
loader calls; `byWorldDefault` reads whether the default is what draws, and
`useWorldDefault` brings it back in place of a script's own `set` / `clear`). For
contact shadows a scene should have its own way, author the `ContactShadows`
component instead. The full description of the knobs and the pass is in the
package readme: `guides { path = "systems/contactShadows" }`.
·renderfeature · born here
❒asset # debugViz render feature
Draws the batched geometry buffer that `@builtin::modules.debugViz` rebuilds
every edit-mode tick from every registered provider — bounds boxes, camera
frustums, and any further gizmo the debugViz core gains. One Draw pass over
the core-owned vertex/index buffer pair, rasterized as GPU lines through the
shared vertex-colour unlit material (`@builtin::shaders.debugGeometry`). An
empty state (no providers with geometry yet, or the driving `DebugViz`
component not yet awake) enqueues nothing.
# applicable
Can be applied for an owner, with values for its declared parameters. A type
that lists `applicable` under `interfaces:` in its `type.yaml` guarantees that
any of its assets can be put in effect for an **owner**, with values for the
parameters the asset declares (`asset.schema`), and that the owner can change
those values, turn the application off and on, and drop it, which leaves
nothing behind, and that the owner can read the application's state as it
stands. A caller applies any implementer with the same calls; here `ref` is
any asset whose type lists `applicable`:
```lua
local view = ref:as("applicable")
local state = view:apply("owner-key", {})
view:setEnabled("owner-key", false)
view:state("owner-key")
view:drop("owner-key")
```
## The members
| Member | What it does |
|---|---|
| `apply(self, owner, values, opts?) -> ApplyState` | Puts the asset in effect for `owner` with `values`. Called again for the same owner, it changes the values. |
| `setEnabled(self, owner, enabled) -> ApplyState` | Turns that application on or off while it stays applied; its values are kept. |
| `drop(self, owner)` | Removes that application entirely. Dropping an owner with nothing applied does nothing. |
| `state(self, owner) -> ApplyState?` | The application's state now, the answer `apply` would give, read without applying. `nil` when nothing is applied for `owner`. |
`owner` is a key the caller forms from something only it holds, so two callers
never share an application. With the asset, it identifies the application
across the calls.
`ApplyState` is `{ status = "inForce" | "off" | "held", heldBy?, notice? }`:
`held` when another application is in force instead (`heldBy` names it), and
`notice` the words a person should see about the application. A type may return
more fields beside these and documents them itself. An application's state can
change with no call for it, when another application of the same kind comes or
goes; `state` answers it as it stands on the frame it is asked.
## The values an application receives
Every call of a member passes through the interface's contract
(`@builtin::interfaces.applicable.contract`), which keeps one record per
application: the values the owner stated and whether it is on. The type's
`apply` receives the asset's own values (`asset.settings`, else its schema's
defaults) with what the owner stated laid over them. A name `values` gives that
the schema does not declare, or a value its descriptor refuses, raises at the
call, naming the asset and the parameter. `Apply.values(self, owner)` and
`Apply.stated(self, owner)` read an application's record.
## Values that follow the hour
Any value an owner states can be stated by hour instead of once:
```lua
ref:as("applicable"):apply("owner-key", {
intensity = { byHour = { ["05:00"] = 0.05, ["07:30"] = 0.35, ["16:30"] = 0.35, ["19:30"] = 0.05 } },
})
```
A key names an hour: a number of hours from 0 to 24, a numeral (`"17.5"`)
or `"H:MM"` / `"HH:MM"`. Each key's value is checked against the parameter's
descriptor like a value stated once. The type's `apply` receives the value at
the hour of the drawn sky (`sky.getTimeOfDay()`): a number, a colour or a
vector is blended between the keys either side of the hour, across midnight
from the last key to the first; any other value (a boolean, a name) is the
one of the latest key at or before the hour. One key holds at every hour.
As the hour moves (a sky running its day, or an hour set by hand), the
contract applies every application holding a value stated by hour again with
the value at the new hour, once for each game minute the hour moves and only
when a value lands at something new. Every client of a session draws the same
hour, so every client lands at the same value. `Apply.values(self, owner)`
answers the value at the hour now, `Apply.stated(self, owner)` the value as
stated, and `Apply.atHour(value, hour?)` reads one value at an hour.
A type that hands the values it receives on to members (a scene setup, a sky)
receives a value stated by hour as stated, so the member that puts it in force
resolves it; such a type registers with `Apply.handOnByHour(typeName)`.
After an edit/play flip, a render-device rebuild, and an edit of an applied
asset, the contract applies every record again; no owner acts. A type's `apply`
puts back what of its effect is gone and leaves what still stands as it is.
## Implementing it
```yaml
# <type>.assetType/type.yaml
interfaces: [applicable]
settings: { values: "<type>.yaml", schema: { type: "settings.luau" } }
```
```lua
-- <type>.assetType/behavior.luau
local Apply = require("@builtin::interfaces.applicable.contract")
local M = {}
M.ref = {
apply = function(self, owner, values, opts)
-- make the application `owner` be `values`, on when `opts.enabled`
return { status = if opts.enabled then "inForce" else "off" }
end,
setEnabled = function(self, owner, enabled)
return { status = if enabled then "inForce" else "off" }
end,
drop = function(self, owner)
-- remove everything made for `owner`
end,
state = function(self, owner)
-- the answer `apply` would give now, without applying
local on = Apply.enabled(self, owner)
return { status = if on then "inForce" else "off" }
end,
}
return M
```
A type states `settings:` in its `type.yaml` so its parameters are readable
with `asset.schema`; an empty schema is valid, and such an asset is applied
with no values. A type whose own `apply` means something else meets the member
under `M.interfaces.applicable.apply`.
## Required behaviour
1. **In effect on return.** When `apply` returns `inForce`, the asset's effect
is in effect with those values.
2. **A change is a write.** After `apply(owner, changes)`, the effect is what a
first `apply` with the complete changed values would have given.
3. **Edit and play.** In effect in edit mode and in play mode.
4. **Off keeps values.** `setEnabled(false)` takes the effect away;
`setEnabled(true)` brings it back with the same values.
5. **Drop leaves nothing.** After `drop`, what the application made is gone:
the engine's entities, render features, post-process entries and claims are
as before the first `apply`.
6. **Nothing saved.** Nothing an application holds reaches a saved scene.
7. **Independent.** Two owners' applications of one asset are two: one
changing, turning off or dropping never changes the other, except through
the asset's own rule for which application is in force.
8. **One in force is the asset's rule.** An asset whose effect holds one
application at a time decides among its applications and reports the others
`held`.
9. **Kept in force.** What an application holds is put back after the events
that remove it, by the contract's restatement.
The conformance suite (`conformance`) checks these against every asset of every
implementing type it can reach.
# assetType runtime
The machinery that reads a `<typename>.assetType/behavior.luau` and turns its
declarations into live behaviour.
A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared
code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` /
`onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` /
`settingsCorrections` hooks. None of it runs itself. This is the code that
runs it, and it lives here because reading a type's declarations is the
**assetType type's own behaviour** — the same way `material.assetType` owns
what a `.material` does.
## Sub-modules
| Module | Reads | Responsibility |
|---|---|---|
| `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. |
| `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. |
| `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. |
| `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. |
| `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. |
| `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. |
| `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. |
| `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. |
| `events.module` | `events` | The per-asset event runtime behind `ref.events`. |
| `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. |
| `interfaces.module` | `type.yaml` `interfaces:`, `interfaces`, `ref` | The interfaces a type implements: reads each `interface` asset, reads a type's marks from the references its `type.yaml` records under `interfaces`, runs every check and refusal of the declaration, and answers `implements`. |
| `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. |
| `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.assetType.shared")
rt.ref.loadTypeBehavior("material")
```
Fields resolve lazily. The prelude requires the sub-modules directly, in
dependency order (`ref`, then `changeDispatch`, `onRegister.install()`,
`refShapes.install()`) — a table that required all six on load would take that
ordering away from it.