ZeroJS is a JavaScript interpreter for the Zero engine, written in Luau. It parses and executes ES2017-practical JavaScript entirely inside the Luau VM — no native code, no WebAssembly, no external dependency — and marshals values back to Luau transparently.
## Importing
```luau
local zerojs = require("~zerojs.api")
```
`~zerojs` is this package's alias, registered from the `name` in its `package.yaml` wherever the package sits. The same spelling therefore works from the world that authors the package and from a world that installed it, at any depth. Every module is reachable the same way — `~zerojs.parser`, `~zerojs.stdlib.promise` — and the package's own modules reference each other with those ids.
## API surface
### Module-level
| Symbol | Type | Description |
|--------|------|-------------|
| `zerojs.eval(src)` | `(string) -> any` | Parse and execute `src` in a fresh one-shot VM. Returns the marshaled JS completion value. Raises a Luau error on a JS exception. |
| `zerojs.new(opts?)` | `(table?) -> VM` | Create a persistent VM. `opts.env` seeds additional JS globals from a Luau table. `opts.engine` picks the tier (`"auto"`, `"compiled"`, `"interp"`). `opts.console` is a table of writers by level (`log`, `info`, `debug`, `warn`, `error`): each receives the formatted text of one console call, untagged, and a level without a writer uses `log`'s. With no `opts.console`, the console writes `[zerojs]`-tagged lines to the engine log. |
| `zerojs.null` | sentinel | The JS `null` value (distinct from Luau `nil`). |
| `zerojs.undefined` | sentinel | The JS `undefined` value, which marshals to Luau `nil` when returned. |
| `zerojs.version` | `string` | Version string of this package. |
| `zerojs.lastError(vm)` | `(VM) -> table?` | Returns the structured payload `{ name, message, stack }` from the most recent JS exception on `vm`. `nil` if no exception has occurred on that VM. |
### VM instance
| Method | Description |
|--------|-------------|
| `vm:run(src, opts?)` | Execute `src` in this VM's persistent realm. `opts.sourceName` names the source for error messages and stack frames. Returns the marshaled completion value. Raises directing to `runAsync` when the script leaves a timer armed or a coroutine suspended across a frame. |
| `vm:runAsync(src, opts?)` | Execute `src`, driving its event loop across engine frames until it settles. Returns a `RunHandle` immediately. `opts.timeoutMs` rejects the run if it outlasts that many milliseconds. Only one `runAsync` may be in flight per VM at a time; a second call while the first is unsettled raises. |
| `vm:get(name)` | Read a global from the VM's realm. |
| `vm:set(name, value)` | Write a marshaled Luau value as a JS global in the VM's realm. |
### `RunHandle` (returned by `vm:runAsync`)
| Field | Description |
|-------|-------------|
| `done` | `false` until the run reaches a terminal state, then `true`. |
| `ok` | Once `done`, `true` for a resolved run and `false` for a rejection or timeout. |
| `value` | The marshaled completion value on a resolved run. A run that timed out after its script had already completed with a value (an armed `setInterval`, say, kept the run open) keeps that value here; every other failure leaves it `nil`. |
| `error` | The rendered message text on a rejected or timed-out run. |
| `lastError` | The structured `{ name, message, stack }` payload for a failed run. |
| `thread` | The engine `task.spawn` driver pumping the loop each frame — present only while the run is still pumping, and `nil` once the run settles on its arming frame (a synchronous or microtask-only completion needs no per-frame driver). |
| `handle:await(maxFrames?)` | From a yieldable Luau context, poll `done` frame-by-frame until the handle settles, then return it. |
A `runAsync` stays pending while the loop has work: an armed `setInterval` keeps it pending exactly as an un-`unref`'d handle keeps Node alive — clear the interval or bound the run with `timeoutMs`.
## Marshaling
Luau values passed to `opts.env` or `vm:set` are converted to JS values. JS values returned from `run`/`eval` are converted back to Luau: numbers, strings, and booleans are transparent; arrays become 1-based Luau tables; objects become string-keyed Luau tables; JS functions become callable Luau closures; `undefined` becomes `nil`; `null` becomes `zerojs.null`.
## Step-budget sandbox
Each VM runs with a default execution budget of 1,000,000 interpreter steps. A script that exceeds the budget raises a JS `RangeError: step budget exceeded`, which surfaces as a Luau error. The budget resets on each `run`/`eval` call.
## Language scope
- Variable declarations: `var` (function-scoped hoisting), `let` and `const` with full TDZ enforcement
- Functions: declarations, expressions, arrow functions, closures, rest parameters, default parameters
- Classes: declarations and expressions, inheritance via `extends`, `super()` in constructors and methods, getter and setter accessors, instance fields, static fields and methods, computed method keys, named class expressions, TDZ before declaration
- Destructuring: object and array patterns in declarations, assignment, and function parameters; nested patterns; rename, default, rest; computed keys in object patterns; elision in array patterns
- Spread: array literals, call arguments, `new` arguments, object literals
- Template literals (untagged)
- Optional chaining: `a?.b`, `a?.[k]`, `f?.(x)`. A `null` or `undefined` base ends the whole chain with `undefined` and skips every later link and argument; parentheses end the chain; the chain is not an assignment, update or `new` target
- Nullish coalescing `??` and the logical assignments `??=`, `||=` and `&&=`, which evaluate the right side and write only when the current value calls for it. `??` does not mix with `||` or `&&` without parentheses
- Full coercion and equality semantics: `==`/`!=` abstract equality, `===`/`!==` strict equality, `typeof`, `instanceof`
- `try`/`catch`/`finally`, `throw`
- All loop forms: `for`, `while`, `do-while`, `for-in`, `for-of`; `switch` with fallthrough
- `async`/`await` — real event-loop semantics: an async function returns a promise, runs synchronously up to the first `await`, and resumes from a microtask when its awaited operand settles
- Property enumerability: `for-in` yields only own enumerable keys; object rest excludes prototype methods
### Asynchrony and the event loop
- `Promise` with the full ES surface: `then`/`catch`/`finally`, `resolve`/`reject`, and the combinators `all`, `allSettled`, `race`, and `any` (with `AggregateError` when every input to `any` rejects)
- `queueMicrotask` for scheduling a microtask directly
- Timers: `setTimeout`/`clearTimeout` and `setInterval`/`clearInterval`, with extra arguments forwarded to the callback
- `vm:runAsync(src, opts?)` drives a script's timers, microtasks, and promise settlements across engine frames and returns a `RunHandle` (see the VM table above)
- A long synchronous loop under `runAsync` yields at each step-budget boundary and resumes on a later frame instead of raising `RangeError`; the same script under `vm:run` still raises
### Standard library
- `Object`: callable coercion plus `keys`, `values`, `entries`, `assign`, `freeze`, `isFrozen`, `create`, `getPrototypeOf`, `defineProperty`, `fromEntries`, `hasOwn`, and the `Object.prototype` methods (`hasOwnProperty`, `toString`, `isPrototypeOf`)
- `Function.prototype`: `call`, `apply`, `bind`
- Global conversions and predicates: `parseInt`, `parseFloat`, `isNaN`, `isFinite`, `String`, `Number`, `Boolean`
- `Array` and `Array.prototype`: construction, `isArray`, `from`, `of`, and the iteration/mutation/query methods (`map`, `filter`, `reduce`, `forEach`, `find`, `some`, `every`, `slice`, `splice`, `concat`, `join`, `indexOf`, `includes`, `sort`, `reverse`, `push`, `pop`, `shift`, `unshift`, `flat`, `fill`, `keys`, `values`, `entries`)
- `String.prototype`: `slice`, `substring`, `substr`, `split`, `indexOf`, `includes`, `startsWith`, `endsWith`, `repeat`, `padStart`, `padEnd`, `trim`, `trimStart`, `trimEnd`, `toUpperCase`, `toLowerCase`, `charAt`, `charCodeAt`, `codePointAt`, `at`, `concat`, `replace`, `replaceAll`, `match`, `matchAll`, `search`
- `Number`: `isInteger`, `isSafeInteger`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`, `MAX_SAFE_INTEGER`, `MIN_SAFE_INTEGER`, `MAX_VALUE`, `MIN_VALUE`, `EPSILON`, `POSITIVE_INFINITY`, `NEGATIVE_INFINITY`, `NaN`, and `Number.prototype` (`toFixed`, `toString`, `toPrecision`)
- `Math`: the constants and functions (`abs`, `floor`, `ceil`, `round`, `trunc`, `sign`, `min`, `max`, `pow`, `sqrt`, `cbrt`, `hypot`, `exp`, `log`, `log2`, `log10`, the trig family, `random`)
- `Date`: construction as `new Date()` (now) and `new Date(ms)` (epoch milliseconds), `now` (the wall clock at the moment of the call, never ahead of it and never moving backwards; whole-second readings of the wall clock bound it until a reading crosses a second boundary), `getTime`, `getFullYear`, `getMonth`, `getDate`, `getHours`, `getMinutes`, `getSeconds`, `getMilliseconds`, `getDay`, `toISOString`, `toJSON`
- `JSON`: `parse` and `stringify` (indent argument and array replacer whitelist)
- `Map` and `Set`: construction from iterables, `get`/`set`/`has`/`delete`/`clear`, `add`, `size`, `forEach`, `keys`, `values`, `entries`, insertion-order iteration
- `RegExp`: literals and the constructor, `test`, `exec`, `lastIndex`, `source`, `flags`, `global`, `ignoreCase`, `multiline`, `dotAll`, and the `String` regex methods above
- Errors: `Error`, `TypeError`, `RangeError`, `ReferenceError`, `SyntaxError` constructors and inheritance; `Error.prototype.name`, `message` and `toString`, so `String(e)`, `${e}` and `"" + e` read `<name>: <message>`
- `console`: `log`, `info`, `debug`, `warn`, `error`, `dir` and `assert`. Values print the way a JavaScript console prints them: strings bare at the top and quoted inside, `{ a: 1, b: [ 1, 2 ] }`, `Map(1) { 'a' => 1 }`, `[Function: f]`, errors as `Error: message`, nested values below depth 2 as `[Object]` and `[Array]`, arrays and collections cut after 100 entries, a self-containing value as `<ref *1> { self: [Circular *1] }`, and a rendering wider than 80 characters across lines. A leading `%s`, `%d`, `%i`, `%f`, `%j`, `%o`, `%O`, `%c` or `%%` formats the arguments after it
- `performance.now()` (milliseconds on a monotonic clock since the VM was created) and `performance.timeOrigin`
- `globalThis`, `NaN`, `Infinity`
### Out of scope by design
- Generators and iterators (`function*`, `yield`)
- `Proxy` and `Reflect`
- Labeled statements and `with`
- Tagged template literals
The full divergence list — where ZeroJS behavior differs from a browser engine — lives in the guide's divergence section.
## Test suites
Eleven suites ship with the package, in its `tests/` folder, run via `tools.tests.run`:
```luau
tools.tests.run({ suite = "zerojs_lexer" }) -- tokenization
tools.tests.run({ suite = "zerojs_parser" }) -- AST construction and error recovery
tools.tests.run({ suite = "zerojs_semantics" }) -- runtime semantics end-to-end
tools.tests.run({ suite = "zerojs_language" }) -- ?., ??, logical assignment, error text, console, Date.now, performance.now
tools.tests.run({ suite = "zerojs_stdlib" }) -- the standard-library surface
tools.tests.run({ suite = "zerojs_typed_arrays" }) -- typed arrays, ArrayBuffer, DataView
tools.tests.run({ suite = "zerojs_regex" }) -- the regex engine and RegExp methods
tools.tests.run({ suite = "zerojs_async" }) -- the event loop, promises, and timers
tools.tests.run({ suite = "zerojs_modules" }) -- the module graph
tools.tests.run({ suite = "zerojs_assettype" }) -- the zJs asset type
tools.tests.run({ suite = "zerojs_smoke" }) -- unmodified real-world JS programs
```
# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# pathTracing
A progressive path-traced view of the scene through the active camera — the
converged image the real-time renderer is trying to approximate, on screen next
to it.
The engine's existing path tracers answer "what light arrives at this surface"
and write the answer into a lightmap or a probe field. This points the same
transport at the camera: every pixel is a path, and what comes back is a
reference image. Held still, it converges over seconds; move the camera and it
starts again.
## Using it
```luau
local referenceView = require("@builtin::systems.pathTracing.referenceView")
referenceView.enable({ samplesPerFrame = 4, bounces = 5 })
-- ... let it converge ...
print(referenceView.settings().samples) -- how far along it is
referenceView.disable()
```
`enable` snapshots the scene's geometry and lights into GPU buffers and starts
tracing. `refresh()` retakes that snapshot after the scene changes; `reset()`
restarts the accumulation without re-snapshotting, for a change the view cannot
see by itself (a light retuned in place). The camera is watched automatically —
any movement restarts it.
`settings()` reports `samples` (how many are in the displayed image),
`converged` (whether it has reached `maxSamples`), and the size of the scene
snapshot in triangles, nodes and lights.
## What it traces
- **Geometry** — every visible mesh-bearing world entity, movable ones
included, as a BVH built by `compute.buildBvh`. Alpha-cutout surfaces are
traced through their coverage masks, so foliage reads as foliage.
- **Materials** — the albedo, emissive, roughness and metallic the raster path
shades with, through a GGX-over-Lambert microfacet BSDF split by metalness.
Both lobes are importance-sampled, and paths terminate by Russian roulette
rather than at a fixed depth.
- **Lights** — every light the bake gathers: directional, point, spot, ambient
and area. Area lights are sampled per path, so their penumbrae emerge from
the accumulation rather than being approximated.
## Shape
| Piece | Role |
|-------|------|
| `referenceView.module` | The public surface. Owns the scene snapshot, the accumulation state, and the camera watch. |
| `pathTrace.renderFeature` | The GPU passes: trace-and-accumulate, resolve, blit. Enqueues nothing while the view is disabled. |
The tracer renders the camera the view was enabled for, from parameters the
module packs, rather than the camera of whichever render target a pass runs in.
One accumulation belongs to one camera, so an offscreen capture drawn in the
same frame shows the same converged image instead of resetting it.
Everything is buffer-bound: no hardware ray tracing, no deferred G-buffer, and
so the same code on either backend and either platform.
# postReference_focusBars
Four rows of bar pairs, 8 pairs across the top row and doubling on each row below: the focus chart a depth-of-field reading is taken off.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
·computeshader · born here
❒asset # loops_cut
Finds where each ring and chain of linked edges starts and ends. `STAGE head`
marks the first edge of every list (a chain's head, a ring's smallest edge) in
`head`, from `next` and `head0` (the `loops` outputs) and `label` and `par` (the
min rounds of `jump`); `STAGE cut` makes the edge before each first edge the end
of its list in `cut`. The lists that result are what `jump` ranks. See `loops`
for the whole sequence.
Over a live count (`COUNT=device`, see the abi README) the edges are the first
`domain_count` slots of a capacity `n`, and the `n` param is not read. A slot past
the live edges is no head (`head` 0) and ends its own list (`cut` is the slot itself).
It binds 7 storage buffers (6 in the plain variant).
# postReference_skyRamp
A sky-blue ramp of light from 0.02 to 0.6 across: a clear sky's gradient.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
·computeshader · born here
❒asset # hash
The first step of a spatial hash over a run of points: the bucket of the cell
each point stands in. The sort kernel orders the points by bucket, and
`hash_starts` then states where each bucket's points start and end in that
order. The keys, the order and the bucket spans, with the cell size, are the
index `hash_count`, `hash_gather`, `hash_nearest`, `hash_repel` and `hash_hook`
search. `core.spatial` builds the index with it. Exact: the same points give the
same keys.
It reads `pts` (xyz a point) and writes `keys`, one a point; the params are
`buckets` (a power of two) and `inv_cell` (one over the cell side).
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` slots are live. A slot at or past the live count holds the key
`0x7fffffff`, which is past every bucket: the sort (over the same live count, or
over the capacity) places it after every live key, and `hash_starts` over the
capacity states every bucket's span over the live points only. It binds 3 storage
buffers (2 in the plain variant).
# lookdev (bundle)
The reference subject a lighting preview is photographed on: a grey ground,
a white diffuse sphere, a chrome sphere and an 18% grey card standing behind
them. The diffuse sphere shows the light's direction, colour and softness, the
chrome sphere reflects the sky and the light sources, and the grey card reads
the exposure. Five entities under one root, built from builtin meshes and
materials.
A type whose pictures show what an asset does to a scene names it as its
preview `subject` (a scene setup's preview, for one); the asset is applied to
the world while the subject is photographed.
```lua
asset.resolve("@builtin::preview.subjects.lookdev", "bundle"):instantiate(nil, { position = { 0, 0, 0 } })
```
# reflections system
Screen-space reflections — a polished floor reflects what stands on it, wet
ground reflects what is above it, and metal picks up its surroundings, all from
geometry the camera can already see.
Environment reflections describe a surface's surroundings in general. They
cannot show the character walking across the floor, because that character is
not in the environment — it arrived this frame. Screen-space reflections read
the frame the engine has just drawn, so anything visible can appear in anything
reflective, with nothing authored per surface.
What that buys and what it costs are the same thing: only what is **on screen**
can be reflected. A reflection of something behind the camera, or off the edge
of the frame, is not there to find. So reflections fade out toward the screen
edge rather than cutting off, and where a ray finds nothing the surface keeps
the shading it already had.
## Using it
Reflections are a render feature. List it on the scene's `RenderFeatures`
entity with the settings it should run under, and it persists with the scene:
```lua
local id = entity.spawn("render features").id
entity(id).component.add("RenderFeatures", {
features = {
{ feature = "@builtin::systems.reflections.ssr", settings = {
intensity = 1.0, -- how much of the reflection reaches the image
maxDistance = 40, -- how far a reflection ray travels, world units
quality = "auto", -- low | medium | high | ultra, or auto (the device's tier)
} },
},
})
```
Every setting is live: edit one in the inspector and the reflections follow.
`renderer.feature.schema("@builtin::systems.reflections.ssr")` lists every knob
with its default.
For code that adjusts reflections at runtime — a quality slider, a cutscene,
weather turning pavement wet — the module is the hand on the same knobs:
```lua
local ssr = require("@builtin::systems.reflections.ssr")
ssr.set({ intensity = 0.6, quality = "medium" }) -- any subset; the rest is kept
ssr.get() -- the settings in force
ssr.active() -- are the passes running
ssr.clear() -- the passes down
```
`set` brings the feature up when none is live, and an `intensity` of 0 takes
it down; the same feature is found rather than stacked when `RenderFeatures`
already runs it.
## What the knobs do
| field | effect |
|---|---|
| `intensity` | How much of the reflection reaches the image, in [0, 1]. 0 turns reflections off and releases the passes. |
| `maxDistance` | How far a reflection ray travels, in world units. |
| `thickness` | How thick a surface is assumed to be, in world units. A ray passing behind one by more than this went past it rather than onto it. |
| `roughnessCutoff` | Perceptual roughness up to which a surface takes the full screen-space reflection. Above it the reflection hands over to the probes and the sky, and is gone 0.1 higher. |
| `quality` | `low` / `medium` / `high` / `ultra` — how many steps the march spends and how many neighbouring rays a pixel gathers — or `auto` (the default), which follows the device's quality tier (`renderer.qualityTier()`): `high` on a desktop, `medium` on a handheld and at the medium tier, `low` at the low tier. `ssr.drawn()` reports the level in force and the sampling it spends. |
| `edgeFade` | How far from the edge of the screen reflections fade out, in UV. |
`roughnessCutoff` is the one to understand first. Every pixel traces one ray
drawn from the lobe its roughness describes, and gathers the rays of its
neighbours that stand on the same surface, so a rough floor shows a bright
sign as the soft, stretched streak its lobe spreads the sign into, and a
mirror shows it sharp. Up to the cutoff a surface takes the full screen-space
reflection. Above it the reflection hands over to the probes and the sky, and
it is gone 0.1 higher, so the hand-over has a soft edge in place of a line. The
default, 0.75, covers wet asphalt and polished stone. A scene that states a
lower cutoff (0.4 was the old default) leaves those surfaces to the probes.
Where the screen holds only part of a surface's lobe (the lobe reaches off the
edge of the frame, or behind the camera) the reflection covers the part it
found and the probe or sky fills the rest.
`maxDistance` and `quality` trade against each other: quality sets the step
count, so a long distance at a low quality samples coarsely and reflections
thin out at range. They thin rather than disappear because the hit refinement
adapts to the step size on its own.
How much of a reflection shows through is the surface's own Fresnel term, taken
from the G-buffer's metallic. Metal takes nearly all of it; a dielectric floor
takes a few percent head-on and much more at a grazing angle — which is why a
wet road reads dry underfoot and mirror-like down the street.
## How it renders
`ssr.renderFeature` runs two compute passes at the `afterDepthPrepass` seam,
before anything shades. `ssr_trace` draws one ray per pixel from the pixel's
GGX lobe (a visible-normal sample; a mirror, below roughness 0.1, keeps its
one reflection ray) and marches it against this frame's depth. The surface's
normal and roughness come from the G-buffer as the previous frame left them,
reprojected through the previous view-projection. The pass writes where each
ray hit and how confident the hit is, or the direction it travelled when it
found nothing. A rough pixel's ray marches fewer steps, because the next pass
blurs what the rays find.
`ssr_resolve` gathers each pixel's lobe over its own ray and the rays of up to
twelve neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`),
weighing every ray against the pixel's own lobe and counting a neighbour only
where it shows the same surface. The light at a hit is read from the colour
the previous frame ended with, where the hit stood then. The resolve
accumulates the result over frames in a history target (one image pair per
view), holds that history to the spread of the rays it gathered, and writes the
scene's reflection channel, `@scene.reflection`: the light of the rays that
found something on screen, and the share of the lobe those rays cover.
A material reads that channel the same frame, at its own pixel, inside its
environment term: it mixes the traced light over the probe and the sky by the
share of the lobe the screen answered, so what the screen did not find comes
from the environment, and the material's Fresnel, roughness and tint weigh the
result into the pixel as they weigh any environment. The reflection stands
where the camera is now; only the light in it is a frame old. The `reflection`
capture pass shows it. Where the trace found nothing the channel holds zero and
the material reflects its environment alone.
A blended material (a `blend` other than `opaque` or `cutout`) reads none of
the channel. It draws over the depth the trace ran against, so the channel at
its pixel holds the reflection traced for the opaque surface behind it. A
blended pane of glass reflects its environment, or the reflection its shader
traces for itself through `@builtin::shaderModules.screenReflection`.
A camera drawing a diagnostic pass holds readings in its colour target rather
than light, so the passes have no light to read from that frame: such a frame
is drawn lit first, unpresented, the passes run for that, and the diagnostic
reads the channel gathered for where the camera stands now. A capture drawn
once, or a camera drawn again from a new station, is drawn lit first for the
same reason, so its first frame holds a reflection (without accumulated
history, so it shows more grain than a continuously drawn view). The march
steps uniformly in screen space and compares in world space; the full account,
including why thickness is tested after refinement rather than during the
march, is in the render feature's own readme.
Each view that draws the feature holds three screen-sized images of its own: the
rays and the history pair, about 50 MB at 1080p for the viewport.
The pass takes its camera from `@frame.camera`, so reflections are correct in
offscreen captures and render-to-texture cameras, not only the live viewport.
## The demo scene
The scene `@builtin::systems.reflections.demo.polished_floor`, loaded with the `scene.load` tool, is a polished
stone floor with three coloured pillars standing on it, under an afternoon
sky, with the feature listed on the scene's `render_features` entity. The
floor reflects the pillars and a player walking across it; delete the entity
and it mirrors the sky alone. `demo/polished_floor.scene/build.luau` is the
whole scene as code, materials included.
## Files
```
reflections.package/
ssr.renderFeature/ -- the trace and resolve passes, and the settings they take
ssr_trace.computeShader/ -- draws and marches one lobe-sampled ray per pixel
ssr_resolve.computeShader/ -- gathers each pixel's lobe, accumulates, writes the reflection channel
ssr.module/ -- ssr.set / .get / .clear / .active, the runtime hand on them
ScreenSpaceReflections.component/ -- the older one-feature component; RenderFeatures is the list
demo/polished_floor.scene/ -- the showcase: a polished floor, three pillars, the feature on one entity
```
# volumetrics
Volumetric (3D-texture) rendering, end to end, in one package. Built
entirely on the engine's generic `compute.*` GPU primitives — no
Rust changes are needed to author new volumetric content.
## Layout
| Asset | Identity | Role |
|---|---|---|
| `Volume.component` | `@builtin::systems.volumetrics.Volume` | Attach a 3D voxel texture to an entity; stands it in the scene through the entity's transform AABB, hidden by what stands in front of it. |
| `VolumetricSky.component` | `@builtin::systems.volumetrics.VolumetricSky` | Clouds in the sky: one per scene, the procedural cloud layer lit by the scene's sun (through the physical atmosphere's air and sky when a `PhysicalAtmosphere` stands in the scene), drawn by `volumetricSky.renderFeature` with no composite authored. |
| `VolumetricLighting.component` | `@builtin::systems.volumetrics.VolumetricLighting` | Light shafts, god rays and glowing air: light scattering between the camera and the scene, drawn by `lightScattering.renderFeature`. |
| `ParticipatingMedium.component` | `@builtin::systems.volumetrics.ParticipatingMedium` | Mark an entity as fog/smoke/dust the camera sees through and that shades the sun on what is under it. |
| `Smoke.component` | `@builtin::systems.volumetrics.Smoke` | Smoke rising from the entity's position: a chimney's column, steam, a smoulder, a black column over a big fire, smoke signals; lit by the scene with a shadow of its own. |
| `Fire.component` | `@builtin::systems.volumetrics.Fire` | Fire with its smoke at the entity's position: a campfire, a torch, a bonfire, a building on fire, an explosion's fireball; flames glow along a blackbody ramp and a flickering point light halfway up them lights the surroundings. |
| `plume.module` | `@builtin::systems.volumetrics.plume` | The smoke and fire plumes `Smoke` and `Fire` hold, from a script: styles, sizes, quality levels; fills a volume each drawn frame and stands it with `Volume:draw`. |
| `mediaTransmittance.module` | `@builtin::systems.volumetrics.mediaTransmittance` | The registry of media and the settings every media pass reads. |
| `mediaShadow.renderFeature` | `@builtin::systems.volumetrics.mediaShadow` | Writes the sun the media take to `@scene.sunOcclusion` and marches each view ray through the media. |
| `volume.module` | `@builtin::systems.volumetrics.volume` | Builders (`noise`/`sphere`/`box`/`wrap`) + the `.zvol` header reader + occupancy + brick paging + the per-entity raymarch dispatch + the draws standing in the scene (`Volume:draw`). |
| `volume.renderFeature` | `@builtin::systems.volumetrics.volume` | Runs every standing draw's march and composite for each view the frame draws, against its camera and depth. |
| `VolumeSequence.component` | `@builtin::systems.volumetrics.VolumeSequence` | Play an open volume sequence through an entity's transform AABB. |
| `volumeSequence.module` | `@builtin::systems.volumetrics.volumeSequence` | A run of `.zvol` frames streamed through a fixed ring of resident volumes. |
| `volumeDemos.module` | `@builtin::systems.volumetrics.volumeDemos` | Shared pipeline for the showcase scenes (fill + emissive raymarch + composite). |
| `volumetricSky.module` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer: tiling noise, weather map, raymarch, TAA and composite orchestration. |
| `volumetricSky.renderFeature` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer's passes for every view the frame draws, brought up by `VolumetricSky`. |
| `volumetricLighting.module` | `@builtin::systems.volumetrics.volumetricLighting` | The light-scattering settings, set from code. |
| `lightScattering.renderFeature` | `@builtin::systems.volumetrics.lightScattering` | The light-scattering passes, brought up by `VolumetricLighting`. |
| `shaders/*` | `@builtin::systems.volumetrics.shaders.*` | Compute shaders `volume_raymarch`, `volume_draw`, `plume_fill`, `volume_pages`, `volume_pack`, `cloud_noise`, `cloud_weather`, `cloud_raymarch`, `cloud_taa`, `cloud_layer_surfaces`; shaders `volume_draw_composite`, `cloud_layer_composite`, `cloud_layer_blit`, `cloud_sky_composite`; shader modules `volume_march`, `cloud_light`, `cloud_surface`, `cloud_shell`. |
| `importers/vdb_to_zvol.importer` | (auto-discovered) | `.vdb` → dense `.zvol` via the `openvdb` WASM plugin (procedural fallback when the plugin isn't loaded). |
| `presets/cumulus_default.preset` | `@builtin::systems.volumetrics.cumulus_default` | Canonical full `VolumetricSky` weather preset. |
| `demo/*.scene` | `@builtin::systems.volumetrics.demo.*` | `sdf_solids`, `smoke_plume`, `nebula`, `godrays`, `zvol_viewer`, `sky`, `showcase`, with their fill shaders. |
The guide `systems/volumetrics/documentation/README` (`guides { path = ... }`)
names the component for each effect, clouds, fog, light shafts, a fog or smoke
volume and the sky, with what each does and costs.
## Path convention — fully-qualified builtin identities
Every intra-package reference uses the asset's fully-qualified builtin
identity, the same convention every other builtin package follows:
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
local V = require("@builtin::systems.volumetrics.volumeDemos")
-- shader identities, e.g. asset.resolve("@builtin::systems.volumetrics.shaders.volume_raymarch")
```
Qualified identities are caller-independent: they resolve identically
from a module, a scene entrypoint, or a component. Caller-relative
(`.sibling`) requires are deliberately avoided here because the
component runtime caller identity is `@builtin::components.<Name>`, so a
`.sibling` require from a component resolves against the wrong root.
(An earlier revision of this package used a `~volumetrics` package-root
alias for relocatability; that alias is not resolvable on current main,
so the package uses qualified identities throughout.)
## Usage
```luau
-- Per-entity volume. The component resolves the name through `Volume.get`,
-- so a volume paged into a brick pool renders from the pool under the same
-- name:
local Volume = require("@builtin::systems.volumetrics.volume")
local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 })
cloud:buildSparse({ brickSize = 8 })
cloud:releaseDense()
entity(id).component.add("Volume", { volumeName = "cloud", density = 6.0 })
-- Procedural sky:
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
-- VDB import: drop a `.vdb` into the VFS; the importer writes a `.zvol`
-- alongside it. Load it with the zvol_viewer demo scene.
-- Animated run: one `.zvol` per frame, played through a bounded ring.
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
Seq.open({ name = "plume", frames = framePaths, resident = 3, fps = 24 })
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
## Plugin dependency
The VDB importer delegates real OpenVDB parsing to the `openvdb` plugin
in the builtin library, `@builtin::plugins.openvdb`. Without the plugin
the importer falls back to a deterministic procedural torus so the
pipeline stays functional.
·computeshader · born here
❒asset # search
Binary search of a run of queries in a sorted column: the pick of a value from
a cumulative distribution, the segment of an arc length.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `T` | `f32`, `i32` | the scalar the column and the queries hold |
| `SIDE` | `lower`, `upper` | which boundary a query answers |
`lower` answers the first place whose value is not below the query, `upper` the
first place whose value is above it, and both answer the length of the column
when no place qualifies. The greatest place whose value is not above a query is
`upper - 1`; with the cumulative sums of a run of weights, `upper` of a draw in
`[0, total)` is the index of the weight it lands in.
The column bound as `sorted` is the sorted run, every element of it. One thread
per query; the dispatch size `n` is the number of queries.
Exact: a search reads the column and nothing else, so the same inputs give the
same answers on every dispatch.
`core.sample.surface` picks a primitive by area with `upper`; `attribute.normalize`
and `geometry.shared` search with `lower`.
·computeshader · born here
❒asset # gather
Builds a column from another column and a run of indices: element `i` of the
result is element `index[i]` of `src`. An index below 0 or past the end of
`src` gives zeros. The element type is the `T` specialization (`f32`, `i32`,
and two to four lanes of either); a three-lane column is read and written
tightly packed, twelve bytes an element.
Dispatch over `n`, the number of indices. Exact: each result element has one
writer. It declares `fusion:` (the value of element `i` is `element(i)`, a thread
runs where `skip(i)` is false), so a chain of fused kernels evaluates it inside
one dispatch.
Most nodes that reorder, select or copy elements read their columns through it:
`core.select`, `core.concat`, `core.make`, `core.weld`, `attribute.gather`,
`attribute.promote`, `elements.sort` and the geometry nodes among them.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` slots are live: a slot at or past it holds zeros. It binds 4
storage buffers (3 in the plain variant), and `dst` holds `n` elements.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
·computeshader · born here
❒asset # contour_cells
Whether each cell of a grid of samples straddles the surface: its eight corner
samples hold both a value below zero and one at or above it. It reads `vals`,
the distance at every grid sample (x fastest), over the grid the params state
(`sx`, `sy` samples along x and y; `nx`, `ny`, `nz` cells; `ox`, `oy`, `oz` the
position of sample (0, 0, 0); `h` the cell size). `flag[c]` is 1 for a
straddling cell and 0 otherwise, the keep mask `compact` turns into the list of
cells that own a vertex. The `sdf.mesh` node runs it first.
Dispatch over the cells. Exact: each flag has one writer.
# Chrome
A polished chrome surface built on the `pbr` shader — fully metallic (`metallic: 1.0`) with a bright near-white base colour (`0.95, 0.95, 0.97`) and very low roughness (`0.05`) for mirror-sharp reflections. Opaque, back-face culled, instanced, with the `_METALLICSPECGLOSSMAP` keyword enabled.
## Inputs
- `colors.base_color` (`0.95, 0.95, 0.97, 1.0`) — bright, faintly cool chrome tint.
- `floats.metallic` (`1.0`) — fully metallic.
- `floats.roughness` (`0.05`) — near-mirror sharpness.
- `textures.base_color_texture` (`default:white`): the white base texture the colour multiplies against, so the surface renders `base_color` alone.
# pbr_layered
A surface composed from two complete PBR layers: a base, and a top layer laid
over it wherever coverage says so.
Rust over painted metal, snow over rock, mud over a vehicle, wear over a finish.
Pre-blending those into one texture set bakes the coverage in — it can no longer
change at runtime, and every entity wearing the material wears it identically.
Here both layers keep their own shading inputs and coverage is evaluated per
fragment, so the same material can be pristine on one entity and ruined on the
next.
## Coverage
Coverage is the product of three terms, each neutral by default:
| term | property | what it is for |
|---|---|---|
| mask | `top_mask_texture`, `top_mask_channel`, `top_mask_contrast` | *where* the top layer gathers — creases, edges, upward faces |
| material | `top_coverage` | *how far* the look has progressed, for every entity sharing the material |
| instance | `top_instance_lane`, `top_instance_component` | how far for *this* entity |
`top_coverage` defaults to 0, so a material that sets nothing renders as its base
layer alone.
`top_mask_contrast` shapes the mask: 1 is a linear ramp, higher values pull the
top layer back into the mask's brightest areas, which is what makes rust and snow
gather in creases instead of washing evenly over everything.
## Driving it per instance
Point the material at an `instanceData` lane, then write that lane per entity:
```lua
-- material: top_instance_lane = 0, top_instance_component = 0
local clean, rusted = entity.find("barrel_a"), entity.find("barrel_b")
if clean and rusted then
renderer.instanceData.set(clean, 0, 0.1) -- nearly clean
renderer.instanceData.set(rusted, 0, 0.9) -- heavily rusted
end
```
Both entities share one material and one draw path; only the lane differs.
## Texture slot budget
WebGPU guarantees 16 sampled textures per fragment stage and the engine's
group(0) already holds several. This shader declares **9**, which leaves room for
those plus a margin. Two full five-map layers would not fit, so the top layer
carries the three maps that make it read as a different material — albedo,
roughness/metallic, normal — and takes occlusion and emissive from the base.
Layer count is **two**. The cost is fixed and predictable: both layers are always
sampled, and coverage selects between their inputs rather than branching.
## Why the inputs blend rather than the results
Lighting each layer separately and adding puts more energy back out than arrived,
so a half-covered surface would read brighter than either layer alone.
Interpolating the shading inputs and lighting once cannot do that.
# Snow Particle
A soft, cold-white flake surface for falling-snow particle effects — a near-white base colour (`0.95, 0.97, 1.0`) with a cool blue-grey emissive glow (`0.25, 0.3, 0.4`) so flakes stay faintly visible in shadow. Transparent, double-sided (`cull: none`), and drawn in the transparent queue (`3000`). Built on `@builtin::shaders.snow_material`.
## Inputs
- `colors.base_color` — the cold-white flake tint.
- `colors.emissive` (`0.25, 0.3, 0.4`) — cool self-illumination that keeps flakes readable in dark scenes.
- `floats.roughness` (`0.8`) — matte, non-glossy flakes.
- `floats.metallic` (`0.0`) — fully dielectric.
·computeshader · born here
❒asset # hash_hook
One hooking round of the connected sets of the points that stand within a radius of each other, searched through
the spatial hash the `hash` and `hash_starts` kernels build. `label` names each point's root, and every point of a set
names the same root (a star); `hooked` starts as a copy of `label`. Every point walks the points within the radius and
lowers the entry of its own root in `hooked` to the smallest root among them, so after the round each root links to
the smallest root next to its set, or to itself. Links only ever point at a smaller root, so they form a forest, and
the `find` stage, which follows each point's links in `hooked` to their end and lowers its entry to that root, makes
every set a star again.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `STAGE` | `hook`, `find` | the hooking round over the hash (binds `pts`, `order`, `range`, `label`, `hooked`), or the walk of each point's links to its root (binds `hooked` alone) |
| `MATCH` | `position`, `normal` | every point within the radius is next to the point, or only one whose normal (`nrm`) is within `cos_angle` of its own |
| `COUNT` | `plain`, `device` | every slot is live, or the live count is read from `domain_count` |
A round of hooking then finding halves the number of sets that still have a neighbouring set every two rounds, so
twice as many rounds as the bits of the number of points leave every set a star of its smallest point. `core.weld`
folds that many rounds, with no read-back. Exact: the smallest root wins whatever order the invocations run in.
# `referenceChart` surface shader
A reference chart drawn on a surface, unlit: each point holds light its
properties and its UV state, so a picture of the surface is measured against
known input. The post-verification reference scenes
(`@builtin::scenes.postReference.*`) are built from its materials
(`@builtin::materials.postReference.*`).
| `pattern` | Draws |
|---|---|
| 0 | A grey wedge: one column per whole stop from `evMin` to `evMax`, each middle grey (0.18) at that stop. |
| 1 | The 24 ColorChecker Classic patches, 6 x 4, each its published sRGB value read as linear reflectance. |
| 2 | A ramp from `low` at u = 0 to `high` at u = 1. |
| 3 | A Siemens star of `frequency` spokes, `high` on `low`. |
| 4 | A checker `frequency` cells across, `low` and `high`. |
| 5 | Focus bars: four rows of bar pairs, `frequency` pairs across the top row, doubling on each row below. |
Every pattern's light is multiplied by `color` and `gain`. UV (0, 0) is the
surface's top-left, as the front face of `@builtin::meshes.cube` maps it.
·computeshader · born here
❒asset # compute_fft_scale
Inverse-FFT `1/N` scale pass: divides every complex sample by the per-line N.
Run after the inverse FFT stages. Used by `nx.gpu.fft*`.
Bindings (see bindings.yaml): `data` (read_write `array<vec2<f32>>`), `params`
(read `array<f32>` — `[total_elements, inv_scale]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_fft_scale", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Gold
Polished gold — a fully metallic PBR surface with a warm yellow base colour
(`1.0, 0.84, 0.0`) and low roughness (`0.25`) for bright, sharp reflections.
Built on `@builtin::shaders.pbr`.
## Inputs
- `colors.base_color` — the gold tint.
- `floats.metallic` (`1.0`) — fully metallic.
- `floats.roughness` (`0.25`) — sharpness of the reflection; raise for a
brushed look.
# Checkerboard
A procedural checkerboard pattern rendered by `@builtin::shaders.checkerboard`, alternating a red base colour (`1.0, 0.2, 0.2`) with a blue emissive colour (`0.2, 0.2, 1.0`). Opaque and non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — useful as a UV / scale test surface.
## Inputs
- `colors.base_color` — the red square colour.
- `colors.dark_color` — the blue square colour.
- `floats.roughness` (`0.5`) — diffuse spread on the lit squares.
- `floats.metallic` (`0.0`) — dielectric surface.
# Custom Textured
A textured opaque surface built on `@builtin::shaders.custom_material`, sampling the `array_texture` builtin over a warm peach base colour (`1.0, 0.8, 0.6`). Non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — a worked example of pairing a custom shader with an array texture.
## Inputs
- `textures.base_color_texture` (`@builtin/textures/array_texture`) — the sampled array texture.
- `colors.base_color`: the warm peach colour the texture is multiplied by.
- `floats.roughness` (`0.5`) — diffuse spread.
- `floats.metallic` (`0.0`) — dielectric surface.
# Sky Procedural
A fully procedural atmospheric sky with a day/night cycle, built on `@builtin::shaders.procedural_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), computing gradient, sun, moon and stars analytically from its parameters — no texture required.
## Inputs
- `properties.zenith_color` / `horizon_color` / `ground_color` — the atmospheric gradient from overhead (`0.1, 0.3, 0.6`) through the horizon (`0.5, 0.7, 1.0`) to the ground (`0.3, 0.25, 0.2`).
- `properties.sun_intensity` (`20`) / `sun_size` (`0.02`) — brightness and disc size of the sun.
- `properties.turbidity` (`4`) — atmospheric haze / scattering density.
- `properties.stars_intensity` (`1`) / `moon_size` (`0.03`) — night-sky star brightness and moon disc size.
# `fog` post-process shader
Depth-keyed distance haze. `pp.add(name, "fog", { density = ..., color = { r, g, b } })`
registers it, and `asset.resolve("@builtin::shaders.post.fog", "shader"):getProperties()`
reads the knobs below before it is added.
The pass reads the scene depth already drawn at a pixel, turns it into a distance
in metres with `zero_linear_depth_through(d, near, far, engine.view_proj)`, which
reads a perspective or an orthographic camera's depth alike, and mixes the frame toward
`fogColor` by `1 - exp(-distance * density)` — an exponential falloff, so density
sets how many metres of air it takes to reach the fog colour.
`near` and `far` are the planes the frame was projected through. They are what a
stored depth is turned back into metres by, so they belong to the camera the
scene was drawn with rather than to the look: setting them to something the
camera does not use moves every surface's distance and with it the whole haze.
| Property | Meaning |
|---|---|
| `density` | Falloff rate. 0 leaves the frame untouched. |
| `fogColor` | The colour a fully fogged pixel reaches. |
| `near` | The scene camera's near plane, in metres. |
| `far` | The scene camera's far plane, in metres. |
# Sky Cubemap
A cubemap sky/environment background built on `@builtin::shaders.cubemap_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` with adjustable rotation and exposure.
## Inputs
- `textures.sky_texture` — the cubemap sampled as the sky (`Ryfjallet_cubemap`).
- `floats.rotation` (`0.0`) — yaw rotation of the sky around the vertical axis.
- `floats.exposure` (`1.0`) — brightness multiplier applied to the sampled colour.
·computeshader · born here
❒asset # compute_add_vectors
Reference compute shader that adds two float arrays element-wise into a third —
the multi-buffer pattern with read-only inputs.
Bindings (see bindings.yaml): `a` (read), `b` (read), `result` (read_write) — all
`array<f32>`.
Usage: dispatch by identity — it resolves to the shader's stable guid and
auto-compiles on first use (no setup):
`compute.dispatch("@builtin::shaders.compute_add_vectors", { buffers = { "a", "b", "result" }, workgroups = { 1, 1, 1 } })`.
·computeshader · born here
❒asset # map
The per-element kernel: `dst[id] = TEMPLATE` over `n` elements. The template is
a WGSL expression over `p` (the element's position), `id`, the numbers `u_get(k)`
and the columns of the `cols` table; the preludes `rand`, `noise` and `color`
supply the functions a template calls. `fieldc.mapSpec` writes a chain of field
templates as one function, so a chain of any length is one dispatch.
Specialize `T` (f32, i32, vec2, vec3 or vec4 of f32), `TEMPLATE`, and optionally
`PRELUDE` and `POSITION`. Bind `cols` (a table from `compute_abi.table`) and `u`.
The output `dst` holds `n` elements of `T`, tightly packed.
```luau
local program = ref:program()
local variant = program:variant({ specialize = { T = "f32", TEMPLATE = "zero_rand(7u, id)",
PRELUDE = '#include "@builtin::systems.procgen.kernels.rand"' } })
local run = variant:run({ n = 64, inputs = { cols = emptyTable, u = numbers } })
```
`fieldc.evaluate(field, domain)` runs a Field through this kernel and answers the Column it wrote. Leaves of Int and UInt runs are read through `cols_i32` and `cols_u32`, and a read past a run's end reads its last element.
# lightCookies
Projects an authored image through a spot light's cone — a gobo, window blinds,
a headlight cutoff, a projector pattern.
## How it divides up
The renderer already projects a texture through a spot's frustum. At each shaded
point it reads `zero_feature_texture(uv, cookieLayer)`, with `uv` from that
point's position in the light's own clip space, and multiplies the cone by what
it finds. `SpotLight.cookieLayer = -1` means no cookie.
What the renderer does not decide is what goes in the layer. That is this
package: resample an authored image into one full layer of the shared
feature-texture array, and point a spot at that layer.
## Using it
```luau
local lightCookies = require("@builtin::systems/lightCookies.package/lightCookies")
-- Size the array once for every layer the scene will use.
lightCookies.configure({ resolution = 256, layers = 4 })
lightCookies.project(lampId, "/textures/cookies/window_blinds.png", { layer = 0 })
```
Or attach a `LightCookie` component next to the `SpotLight` and author
`texture` / `layer` / `gain` / `tint` on it.
`lightCookies.clear(lampId)` stops the projection; the layer keeps its contents.
## When a fill lands
`fill` and `project` queue the fill and return its layer at once. The module's
own loop writes it over the frames that follow: the rasterize is issued on the
next frame and the copy into the layer on the frame after, and the fill is
written once `renderer.featureTexture.state().fills` reports the copy landed in
its layer, one fill at a time in the order they were asked for. The loop belongs to the module, so a fill
lands even when the code that asked for it (a one-shot script, a task scope, a
component that is destroyed) has ended.
`lightCookies.status(layer)` reports where the last fill of a layer stands:
```luau
local s = lightCookies.status(0)
-- s.state: "queued" | "rasterizing" | "copying" | "written" | "refused"
-- s.reason: why a refused fill was refused, in the engine's words
-- s.filled: whether renderer.featureTexture.state().filled lists the layer
```
`status` reads a fill `"written"` from the first reading of the array that
reports its copy landed, so `s.state` and `s.filled` agree whichever of the
module's loop and the reader runs first in a frame.
A fill names a layer below the count `configure` sized the array to; one past
it is refused at the call, which returns nil and the reason. A fill that cannot
land once it is on its way (the GPU refuses its rasterize because its image was
given back first, a later `configure` left the array without its layer, or its
copy never reached the array) reads `"refused"` with the reason, and is also
logged as a warning.
A `LightCookie` component whose fill is refused at the call, such as one
authored before the scene's `configure` has sized the array, asks again each
time `configure` sizes it. `lightCookies.observe().configurations` counts
those calls for code of its own that does the same.
`lightCookies.observe()` reports how many fills are waiting, the one in
progress, and the loop's own counters.
## An empty layer puts the light out
The cone is multiplied by what it reads from its layer, so a spot pointed at a
layer nothing has filled renders black rather than plain. `project` fills before
it points the light, which is the order that keeps the cone lit; if you set
`SpotLight.cookieLayer` by hand, fill that layer first.
## The array is shared, and sizing it is explicit
The feature-texture array is one resource that every feature using
`zero_feature_texture` draws layers from, and it has no allocator: sizing it
zeroes every layer, including layers another feature owns. So this package never
sizes it as a side effect of setting a cookie, and `layer` is authored rather
than assigned. `lightCookies.configure` is the one call that resizes, made once
by whoever knows what else in the scene wants layers.
A scene that also bakes global illumination shares this array with the lightmap
atlas. Size it for both, and give cookies layers above the ones the bake fills.
## A cookie fills a whole layer
The cone's lookup runs over the layer's entire `uv` range, so an image is
resampled to the layer's extent rather than placed in a corner of it. One layer
carries one cookie.
## Alpha
The source's alpha is how much of the pattern applies. At alpha 0 the cone
passes through unmodulated, so a fully transparent image is a no-op rather than
a black cone.
·computeshader · born here
❒asset # compute_snow_terrain
GPU heightmap generation for a snowy mountain landscape. One thread per `(x, z)`
column, emitting a single `f32` height per cell. Uses multi-octave FBM for hills,
ridge noise for peaks, and a radial bowl to frame a mountain valley.
Bindings (see bindings.yaml): `params` (read `array<f32>` — `[gridSize,
worldExtent, seed, mountainScale, baseHeight, ridgeStrength, ...]`), `heights`
(read_write `array<f32>`, indexed `[z * gridSize + x]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_snow_terrain", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Default Unlit
A flat, unlit surface that renders its base colour directly with no lighting response, built on the `unlit` shader. Uses a white base colour (`1.0, 1.0, 1.0`) over the `default:white` texture with `emissive` (`1.0`) for full brightness — the go-to default for UI, gizmos, and debug geometry that must stay legible regardless of scene lighting.
## Inputs
- `colors.base_color` — the flat colour shown directly.
- `textures.base_color_texture` (`default:white`) — the white base texture the colour multiplies against.
- `floats.emissive` (`1.0`) — full, lighting-independent brightness.
·computeshader · born here
❒asset # concat
Joins one attribute of several geometries into one column. `sources` is a column
table with one column per geometry, in order, from column `first`; `desc` says,
from word `base`, where each geometry's elements start in the result, how many it
has, how far to shift each value of a linkage column, and whether the geometry
holds the attribute at all. Where it does not, its elements take the default
stated in the first four words of the description, their own place in their
geometry (`absent` 1), or -1 (`absent` 2). The joined column is `dst`, `n * lanes`
words.
The params are `lanes` (the words an element holds), `parts` (how many geometries
are joined), `first` and `base` (where this attribute's columns and description
begin), `kind`, `absent`, `moved` and `scale`.
Linkage is a shift: `vertex.pt` takes the number of points before the geometry,
`primitive.vstart` the number of vertices before it, and `point.id` the amount
that keeps the ids unique across the geometries. Any other attribute shifts by
0. `scale` multiplies every value before the shift moves it. With `moved` 1 a
negative value stays and only the others move: a column of point ids where -1
names no point.
`kind` states the word form of the joined column (0 f32, 1 i32, 2 u32): each
geometry's column is read as the value it holds, by the form its table entry
states, and written as that value in the joined form, so a column one geometry
holds as Int and another as Float joins by value. The default, 3, moves the words
as they stand.
A join of a whole geometry runs the kernel once per attribute of the union of the
geometries' attributes, with one description run for all of them
(`geometry.join`, and `proc.substrate.Geometry.merge` for geometries that count
their elements on the device, whose descriptions the device writes from the
counts).
Dispatch over `n`, the elements of the joined domain. Exact: each result
element has one writer.
# restirLighting
Direct light from many small sources at a cost that does not grow with how many
there are.
A shading pass that loops every light pays for every light at every pixel, which
is why the number of lights has to be capped. Resampled importance sampling
breaks that link: each pixel draws a few candidates, keeps ONE of them with a
probability proportional to what it would contribute, and carries a weight that
makes the survivor stand for the whole set. What it keeps is then reused — by its
neighbours this frame, and by itself on the next one — so the set a pixel
effectively samples keeps growing while the number of candidates it draws stays
where you put it.
A cave of glowing crystals, a street of practicals, a control room of indicator
lamps: hundreds of sources, and each pixel looks at about a dozen.
## Using it
Put an `EmissiveSource` on the geometry that glows:
```lua
local id = entity.spawn("crystal", { position = { 2, 1, 0 } }).id
entity(id).component.add("EmissiveSource", {
color = { 0.3, 0.8, 1.0 },
intensity = 8.0,
radius = 6.0,
size = 0.4,
})
```
Or register sources from a script, which is how a generated scene does it:
```lua
local restir = require("@builtin::systems.restirLighting.restirLighting")
for i = 1, 400 do
restir.set(`lamp{i}`, {
position = { math.random() * 60 - 30, 1.5, math.random() * 60 - 30 },
color = { math.random(), math.random(), math.random() },
intensity = 4.0,
radius = 5.0,
})
end
```
The pass starts with the first source and stops with the last. Settings are on
`restir.configure`, or on a `ResampledLighting` component for a scene to author:
```lua
restir.configure({ candidates = 16, spatialSamples = 6 })
```
## What a pixel pays
`candidates + spatialSamples + 1` evaluations, reported by
`restir.perPixelCost()`. None of those terms is the source count.
The estimate is formed on a grid of one cell per 2x2 pixels (`resolution =
"full"` gives every pixel its own cell), across four passes:
| Pass | Runs over | Does |
|---|---|---|
| `restir_sample` | grid cells | draws `candidates` sources at random, resamples to one, merges the cell's own history |
| `restir_spatial` | grid cells | borrows from `spatialSamples` neighbours, each evaluated against this cell's surface |
| `restir_resolve` | pixels | shades the chosen source with the pixel's own normal, roughness and albedo |
| `restir_denoise` | pixels | averages that light over the cells around the pixel and composites it |
Which source to look at is a low-frequency decision a cell of pixels can share.
What the surface does with it is not, and is computed per pixel.
One source per cell is correct on average and different from its neighbour,
which is the grain a single sample carries. `restir_denoise` averages across the
cells around a pixel, weighing each by how nearly its surface is this one, so the
estimate keeps its value and loses its variance.
`mode = "reference"` replaces the reservoir lookup with a loop over every
registered source at every pixel. That is the picture the resampled mode is
estimating and the cost it is measured against — the same shading, the same
filter and the same composite, so the two are comparable directly.
## Temporal reuse
A cell keeps its reservoir across frames and merges it with the fresh
candidates, so a good find keeps paying after the frame that made it. The stored
world position is what says the cell is still looking at the same surface; a
camera move or an occluder passing in front fails that test and the history is
dropped rather than smeared.
`historyCap` bounds how many candidates the history is allowed to stand for.
Without it a converged cell would outvote every new candidate forever and a
lighting change would never work its way out. At the default of 20 a change is
absorbed over roughly twenty frames.
Removing a source, or turning its `intensity` down to 0, releases it; the pass
stops with the last one.
## Where it sits
Sources registered here are additional to the lights the engine holds rows for.
The passes run in `afterLighting` at orders 80-84 and add to the scene as it was
drawn, reading position, normal, albedo and metallic-roughness back out of the
G-buffer.
A source lights every surface within `radius` that faces it, along the straight
line between them.
## One frame, several targets
A render feature's `render` runs once a frame, and the passes it enqueues run
once per render target — the window, an offscreen capture, a camera rendering to
a texture. Each pass therefore reads the frame size out of the textures it is
handed and works out its own cell grid, so every target resamples at its own
resolution. A reservoir carries the grid width it was written under, which is
what stops one target's history being read as another's.
The reservoir buffers are sized to the widest grid any target has asked for. A
target wider than they have yet been sized for reports the grid it needed, and
the frame after that covers it.
## Reading what it did
`restir.stats()` returns the counters the passes keep on the GPU for the most
recent frame a read-back has landed for, carrying that frame's number so a
repeated read is distinguishable from a fresh one. `meanWeight` is counted in
sixteenths with each cell capped at 16 so the total fits a 32-bit counter;
`peakWeight` alongside it is exact to a thousandth, and is where an estimator
that has come loose shows first.
·computeshader · born here
❒asset # grid
Reads and writes a field of cells in one kernel. The field is a Grid (one tile,
no apron, x fastest, `lanes` values per cell) or a Raster (tiles with aprons,
one batched dispatch) through the layout in `tile_layout`.
- sample (`MODE sample`): the field at positions, nearest or trilinear, held to the
edge cell past the field. Reads each cell from the tile that owns it.
- write (`MODE write`): a patch of values blended into the field (replace, add,
max, min, multiply, optionally weighted per cell). Every tile that holds a cell
as core or apron receives it, so apron copies agree. The patch window is stated
in field cells and may reach past the field (negative origin, or a size beyond
the cell counts): a stored cell a border tile holds past the field takes the
patch where the window covers it.
- stencil (`MODE stencil`): per stored cell, a neighbour at an offset, slope in
degrees, curvature (the laplacian over x and z) or the gradient, with neighbour
reads held to the tile's own stored edge. Slope and curvature are the terrain
mask's. The gradient writes two values a cell, d/dx and d/dz per metre.
`MODE`, `SAMPLING` (nearest, trilinear), `STENCIL` (offset, slope, curvature, gradient) and `BLEND` (replace, add, max, min, multiply) are specializations.
The bindings: `field` (the field, read by sample and stencil), `aux` (the
positions, xyz a position, for sample; the patch values for write), `weight` (one
weight a patch cell, read by write when the param `hasWeight` is 1) and `out` (the
sampled column, the stencil result, or the field being written). Sample runs one
thread per position (`count` of them) and writes `outLanes` values each, from lane
`lane`; write and stencil run one thread per stored cell.
`determinism: exact`: each output element has one writer. The bindings a mode
does not use take any buffer of at least one element that is not bound elsewhere
in the dispatch.
`grid.sample` samples with it, `core.raster.blend` writes a patch into a raster
with it, and `core.raster.stencil` measures slope and curvature with it.
·computeshader · born here
❒asset # topology
Mesh edit operations over a geometry's linkage (`vertex.pt`, `primitive.vstart`,
`primitive.vcount`), selected by the `OP` specialization (`split_edge`, `collapse_edge`, `insert_face`, `delete_face`, `split_vertex`), each stage by `STAGE` (`count`, `write`): split an edge (insert a point),
collapse an edge (merge two points and drop the faces that degenerate), insert a
face, delete a face, split a vertex (give a group of corners a point of their own).
Each operation runs in two stages with an exclusive prefix sum between them. The `count`
stage writes `cnt`, how many output vertices each primitive contributes (`insert_face`
appends one entry per new face after the `np` primitives). The caller's exclusive prefix sum
of `cnt` is `off`. The `write` stage writes the output vertices' points (`o_pt`) and where
each came from (`o_src`). The output primitives are `off` as run starts and `cnt` as run
lengths; a primitive with an empty run is gone, and `core.select` removes it. `split_vertex`
runs per vertex instead: `cnt[v]` is 1 for the first vertex of each group, the groups'
new points are numbered from `npts` in order of their `off`, and `o_pt[v]` / `o_src[v]`
are written at the vertex's own slot. The shader's header states the records each
operation reads in `rec`.
The params are `np`, `nv` and `npts` (the input's primitives, vertices and points),
`nnew` (the faces `insert_face` appends), `wrap` (1 when runs wrap from their last vertex
to their first) and `minv` (the fewest vertices a primitive keeps after a collapse). The
caller binds `nv_out`, the output vertex count `o_pt` and `o_src` are sized by (the total
of the prefix sum). The dispatch is one thread per primitive, per primitive and new face
for `insert_face`, and per vertex for `split_vertex`.
The operation's records come from the edge table: for split edge, the point
for each split edge gathered to the vertex slots through `edges`' side slots
(both faces of an edge name the same point); for collapse, the point each
point becomes, from an independent set of edges. The point an inserted
vertex or a split vertex stands for is carried by the output maps: `o_src` names the vertex
whose attributes an output vertex takes (negative when it is new, with ~v the
vertex a split inserted after), and the compaction of the records names each
new point's source. Integers are 32-bit words, exact.
`geometry.decimate` runs `collapse_edge`.
# grass_material.shader
Grass, shaded root to tip with per-blade colour variation and a soft
half-lambert wrap.
The colouring reads `uv.y` as height along a blade — 0 at the root, 1 at the tip
— and darkens the roots while warming the tips. Per-blade variation comes from a
hash of the fragment's world xz on a 10 cm grid, so every fragment of one blade
shares a seed and neighbouring blades drift apart in hue and brightness. The
lighting is a diffuse half-lambert wrap kept below saturation, so this shader
returns its own final colour instead of a PBR surface.
`sway` is how far the vertex stage bends each vertex along its blade, and it is
what tells this shader that its mesh is a blade mesh: the bend scales with
`uv.y²`, so a vertex at the root holds still while the tip swings hardest. It
defaults to 0, at which every vertex arrives where the mesh put it — a material
that leaves it there shades a surface without moving it. `@builtin::materials.grass`
is that ground surface; `@builtin::materials.grass_blades` sets `sway` to 1 for a
blade mesh.
## Properties
- `base_color` — the grass green the root→tip gradient is built from.
- `sway` (`0`..`4`, default `0`) — how far each vertex bends along its blade.
# Instance Color
A lit white surface that every instance wearing it colours from its own
shader-data lane 2, built on `@builtin::shaders.pbr` with
`instance_color_lane = 2`. One material draws hundreds of members in hundreds of
colours, and a colour that changes every frame costs one
`renderer.instanceData.set` per member: a stress map over a bridge, a heat map,
a damage flash, team colours, a selection highlight, a gauge.
```luau
local LANE = 2
for i, id in members do
local load = loads[i] -- 0 relaxed .. 1 at its limit
renderer.instanceData.set(id, LANE, load, 1 - load, 0, 1) -- green to red, fully covered
end
```
The lane's `rgb` is the colour and its `a` is how much of it covers the base
colour and the emission, 0 none through 1 all; an instance whose lane was never
written reads zero and draws plain white. The colour replaces the base colour
before lighting, so the member still shades, casts its highlights and shows the
lane colour in the `albedo` capture pass. Set `instance_emission` above 0 for a
colour that glows where it covers.
`renderer.mesh.drawInstanced` reads the same lane from its
`instanceDataBuffer`, so a GPU-filled population colours each copy the same
way. The writes are local to the engine that makes them and replicate nothing;
`Model.tint` is the synced form of a tint, for a colour every participant
must see.
## Inputs
- `floats.instance_color_lane` (`2`): the lane read; lanes 0 and 1 carry a
baked lightmap's rect and layer.
- `floats.instance_emission` (`0`): how brightly the lane colour glows.
- `colors.base_color` (white), `floats.roughness` (`0.5`),
`floats.metallic` (`0`): the surface under the lane colour.
·computeshader · born here
❒asset # contour_triangles
Each kept quad as two triangles: `pt` holds, per quad, the vertex numbers of
its corners (`a b c`, `a c d`), and `vstart` the position of each triangle's
first corner in `pt`. Slot `n` of the dispatch is the `n`-th quad `edges[n]`
names (the list `compact` makes of `quad_flag`), read from `quad_v` of
`contour_quads`, so the quads are numbered in edge order.
Dispatch over the kept quads. The `sdf.mesh` node dispatches over every grid
edge and states the kept count times 6 as the vertex count and times 2 as the
primitive count, so the slots past the kept quads lie past the live elements.
Exact: each slot has one writer.
# Emissive White
A bright white light-emitting PBR surface built on the `pbr` shader with the `_EMISSION` keyword enabled. A white base colour (`1.0, 1.0, 1.0`) paired with a strong `emissive` (`20.0`) makes it glow and drive bloom — well suited to light fixtures, emitters, and glowing accents. Non-metallic (`metallic 0.0`) at mid roughness (`0.5`).
## Inputs
- `floats.emissive` (`20.0`) — high emission strength that produces the glow.
- `keywords: _EMISSION` — enables the emissive path in the PBR shader.
- `colors.base_color` — the white surface and emission colour.
- `floats.roughness` (`0.5`) — diffuse spread on the lit surface.
# gpuSort
A stable least-significant-digit radix sort, run entirely on the GPU, over a
caller-owned array of u32 keys.
The three passes here are the body of one radix digit. They read a key array and
a permutation and write a new permutation; they never touch whatever the keys
describe, so any subsystem with a key per item can drive them. The caller
supplies the keys, the identity seed, the per-pass constants and the dispatch
sequence.
## One pass
| Order | Shader | Dispatch |
|-------|--------|----------|
| 1 | `radix_hist` | one workgroup of 256 per 256 items |
| 2 | `radix_scan` | `{ 1, 1, 1 }` |
| 3 | `radix_scatter` | one workgroup of 256 per 256 items |
Each pass sorts on one 8-bit digit and keeps the relative order of items sharing
that digit, so `ceil(bits / 8)` passes over the low digits upward compose into a
total order on `(key, item index)`.
## Driving it
The caller owns six buffers: the keys, two permutation buffers the passes
ping-pong between, the digit histogram (`ceil(count / 256) * 256` entries) and
one constants buffer per pass. A pass reads its constants as
| Word | Meaning |
|------|---------|
| `[0]` | item count |
| `[1]` | block count, `ceil(count / 256)` |
| `[2]` | this pass's digit shift — `0`, `8`, `16`, `24` |
| `[3]` | `1` on the last pass, `0` otherwise |
| `[4]` | the key a dropped item carries |
Every value is fixed for the life of the sorted array, so the constants are
written once rather than re-uploaded per frame.
Each pass flips which buffer holds the permutation, so the parity of the pass
count decides where the caller seeds the identity for the last scatter to land
in the buffer the consumer reads.
An item the caller wants dropped takes a key at or past `[4]` — one past the
last real key — which parks it in the tail of the permutation; the last pass
resolves it to `0xffffffff`, and the consumer reads that as "this slot draws
nothing". A fixed dispatch size with a degenerate tail is what lets a consumer
issue a constant draw with no read-back and no indirect arguments.
·computeshader · born here
❒asset # sort
A stable radix sort of a column's keys into a permutation: place `s` of `perm`
holds the index of the element that sorts `s`-th, so a gather by `perm` puts
any column in key order.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `KEY` | `f32`, `i32` | the scalar a key holds |
Elements with equal keys keep their run order, in both directions
(`params.descending` 1 sorts from the greatest key down), and `-0` and `+0` are
one key. The sort works 4 bits of the key at a time from the least significant
up, and a pass whose digit is the same in every key is skipped, so a run of keys
inside a narrow range takes fewer passes. `work` is the sort's second
permutation; its contents after a dispatch are not an answer.
The dispatch size `n` is the number of keys. One workgroup of 128 works the whole
run; the other workgroups of a larger dispatch return.
Exact: the sort is a function of the keys and their order, so the same keys give
the same permutation on every dispatch.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` keys are live: they are sorted, and a slot at or past the live
count holds its own index in `perm`. A live count of 0 sorts nothing and `perm` is
the identity. It binds 4 storage buffers (3 in the plain variant).
Nodes that order or group elements run it, among them `attribute.order`, `elements.sort`, `core.edges`,
`core.adjacency`, `core.spatial`, `geometry.bvh`, `geometry.boolean`, `geometry.decimate` and `geometry.shared`.
·computeshader · born here
❒asset # compute_ocean
Ocean wave simulation. Displaces a mesh's vertex buffer in place by a sum of
Gerstner waves, recomputing each normal analytically from the wave derivatives.
`steepness` sets how far the surface travels along each wave's direction as well
as up. At `0` every vertex stays on its rest column and the result is a plain
sine height field; raising it sharpens crests and broadens troughs, which is the
shape that reads as a wave rather than a ripple. Values above roughly `1 /
(frequency * amplitude * wave_count)` make the surface self-intersect.
Bindings (see bindings.yaml): `vertices` (read_write `array<u32>` — the mesh
vertex buffer, 76 bytes/vertex, bitcast to f32), `params` (read `array<f32>` —
`[time, grid_size, amplitude, frequency, wind_x, wind_z, steepness, pad]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_ocean", ...)` each frame —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
·computeshader · born here
❒asset # compute_fft_copy
Copies a `vec2<f32>` (re, im) buffer element-wise. Used by `nx.gpu.fft*` to seed
the ping-pong scratch buffer from the caller's input on stage 0 without an extra
ping-pong dispatch.
Bindings (see bindings.yaml): `src` (read), `dst` (read_write) — both
`array<vec2<f32>>`.
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_fft_copy", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Water
An animated water surface with a deep blue base colour (`0.1, 0.3, 0.8`) and low roughness (`0.2`) for glossy, reflective highlights, driven by a scrolling normal map for wave detail. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.water_material`, sampling `@builtin/textures/water_normals`.
## Inputs
- `colors.base_color` (`0.1, 0.3, 0.8`) — the water body colour.
- `floats.roughness` (`0.2`) — low roughness for sharp specular reflections.
- `floats.metallic` (`0.0`) — dielectric surface.
- `textures.normal_texture` — the wave normal map (`@builtin/textures/water_normals`).
# postReference_chrome
A polished metal: its highlight of a bright light is a sub-pixel specular, the firefly a bloom and a temporal resolve are read on in the post-verification reference scenes.
·computeshader · born here
❒asset # bvh_codes
A 30-bit Morton code for each primitive of a geometry: its bounds centre,
normalized inside the scene bounds and interleaved bit by bit. Sorting
primitives by this code puts primitives that are near in space near in the
order, which is what the `bvh` kernel builds its tree from. It reads the points
(`pts`), the point each vertex reads (`vpt`), each primitive's `vstart` and
`vcount`, and the scene bounds `lo` and `hi` (xyz each: a min and a max reduce
of the points), and writes `codes`, one word per primitive, 0 for a primitive
with no vertices. The `geometry.bvh` node runs it, sorts the codes and hands
both to `bvh`. Dispatch over the primitives. Exact.
·computeshader · born here
❒asset # make
Builds the elements and the primitives of a geometry from a count per owner and
a shape (`points`, `strip`, `fan`, `grid`, `ring`, the `SHAPE` specialization).
The result is the columns a Geometry holds: `P` over the points, `vertex_pt` over
the vertices (the point each reads), and `prim_vstart` / `prim_vcount` over the
primitives (each one's run of vertices). All indices are into the result, so
owners' pieces sit end to end with their links already offset.
It runs as two passes of one shader (`PASS`): `sizes` writes the points,
vertices and primitives each owner makes; after a prefix sum of each component
into `bases`, `fill` writes every element once, found by a binary search over the
bases. Exact: each output element has one writer. The shape's layout is stated
at the top of `bindings.yaml`; `grid` takes its second axis from the `across`
param (default 2, at least 2).
`core.make` runs it: the `sizes` pass, a `scan` of the sizes, then the `fill`
pass, and the columns become the Geometry the node answers.
# Grass blades
Swaying grass for a blade mesh, built on `@builtin::shaders.grass_material` with
the same green as `@builtin::materials.grass` (`0.22, 0.62, 0.16`) and `sway` at
`1.0`. The shader bends each vertex along its blade in proportion to `uv.y²`, so
this material belongs on a mesh whose `uv.y` runs 0 at a blade's root to 1 at its
tip — a merged field of blades, each a cross of two tapered quads. It inherits
the Rust-side render defaults (opaque, back-face culled, queue `2000`) so its
pipeline matches the library variant compiled at startup.
## Inputs
- `colors.base_color` (`0.22, 0.62, 0.16, 1.0`) — the grass green tint.
- `floats.sway` (`1.0`) — the full blade bend. `@builtin::materials.grass` leaves
it at the shader's default of `0` for a ground surface.
# Text Default
The default surface for Text3D — a white base colour (`1.0, 1.0, 1.0`) drawn with alpha blending and no depth write so glyphs composite cleanly over the scene. Transparent, double-sided (`cull: none`), `depth_write: false`, in the transparent queue (`3000`). Built on the `pbr` shader.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the glyph colour.
- `render.depth_write` (`false`) — glyphs blend without occluding each other.
- `render.cull` (`none`) — text is visible from both sides.
- `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric defaults.
# procedural_sky
The editable atmospheric sky: a day/night gradient with a sun disc and
glow, a procedural star field, and a moon opposite the sun, authored
entirely from material properties — no texture backs it.
Day, night and the dawn/dusk blend all derive from the sun's elevation:
the directional light's, so the sky follows whatever drives the scene's
sun, or, with `sun_from_hour` at 1, the direction `sun_dir_x`/`_y`/`_z`
states (the procedural backdrop states its hour's sun there, so its day, its
night and the moon opposite the sun come from its hour). The gradient's zenith, horizon and
ground colours, the sun's size and intensity, the stars, the moon,
turbidity and exposure come from `properties.yaml`. `horizon_height`
(degrees, default 7.933) shapes the gradient above the horizon: it is the
elevation where the sky is halfway from the horizon colour to the zenith
colour, so a lower value holds the horizon colour in a narrower band.
As the sun sinks, the gradient falls from those colours to the night
colours (`night_zenith_color`, `night_horizon_color`,
`night_ground_color`) as far as `night_strength` says, and near the
horizon it leans toward the dawn tint (`dawn_zenith_color`,
`dawn_horizon_color`) as far as `dawn_strength` says. Both strengths
default to 1; at 0 the authored zenith, horizon and ground colours are
what is drawn at every hour.
The star field holds still unless `stars_twinkle` is above 0, which
compiles in the `SKY_TWINKLE` program: each star's brightness then swings
by that amount on the frame clock. A twinkling sky changes the picture on
every frame the clock runs, so a renderer that draws only what changes
keeps drawing under it; a still one leaves an idle screen idle.
Output is radiance scaled by `exposure` — the scene's own tone-mapping
does the range compression, the same contract as every sky-domain
shader.
The `ProceduralSky` component owns the runtime material over this shader
(`__procedural_sky`) and pushes its fields here; `sky.get()` reports the
resulting configuration.
# error_marker
The surface of the ERROR sign: the magenta and dark purple world-space checker
the engine's error pipeline draws, as an unlit surface shader. The
`error_marker` material draws the sign with it.
# globalIllumination system
Production-grade baked global illumination for the Zero engine. Two
complementary techniques share one baking pipeline:
- **Lightmaps** — bake full irradiance (direct + multi-bounce indirect)
into a per-entity texture sampled in UV space. For static surfaces.
- **Volume probes** — path-trace incoming radiance at points in a 3D
grid, encode as spherical harmonics (SH L2), and publish the field
into the renderer's irradiance-volume set: every standard-PBR fragment
inside the volume samples the nearest probes by world-space position.
For moving entities and any static surface without lightmap UVs.
Both bake the same lighting model from the same scene: every sample is
path-traced through the scene BVH for up to `bounces` surface
interactions. Each path vertex contributes its emissive plus its albedo
times the shadowed direct light there, so the bake captures indirect
light, color bleed between surfaces, emissive surfaces acting as area
lights, and sky occlusion — the transport that is too expensive to
evaluate at runtime.
## Mobility decides who bakes
`Model.mobility` (`"auto"` | `"static"` | `"movable"`) is the single
selection axis for the whole system:
- **Static geometry** receives lightmaps and occludes / bounces baked
light. `Lightmap.bakeAll()` bakes every static receiver — no
per-entity setup.
- **Movable geometry** (and every player / skinned character) samples
the published probe fields — renderer-level, no per-entity setup. It
never bakes: a moving mesh baked as an occluder would freeze its
shadows into the world and walk away from them.
`"auto"` derives the answer per entity: a non-static `Physics` body, a
`SkinnedModel`, a `ClipPlayer`, a `Mover`/`FreeMover`, or a non-world
runtime participation (players, editor viz, prototypes) makes it
movable, and so does motion: geometry the running world places on more
than one frame (a script's update walking it in play, an engine system
posing it), or carries on an ancestor it places so, reads
`entity.inMotion` true and resolves movable. Everything else is static,
a prop a script places once included. An explicit `"static"`/`"movable"`
on the field overrides the derivation — that is the exclusion switch
when the derivation gets an entity wrong.
## Files
```
globalIllumination.package/
VolumeProbe.component/ -- define a probe volume (bounds + resolution)
BakedLighting.component/ -- keep the bake in step with the scene
lightmap.module/ -- Lightmap.bake / .bakeAll / .applyFromAsset / .clear
volumeProbe.module/ -- VolumeProbe.bake / .restore / .retire
scenarios.module/ -- Scenarios.capture / .blend / .mix
skyResponse.module/ -- SkyResponse.calibrate / .apply / .combine
bakeState.module/ -- BakeState.affects / .invalidate / .rebake
bakeViz.module/ -- the two debug overlays that make a bake visible
baking.module/ -- Shared utilities: light gather, surface
-- attributes, static mesh-instance gather
lightmap_bake.computeShader/ -- Compute shader: per-texel path-traced bake
probe_bake.computeShader/ -- Compute shader: per-probe path-traced bake
```
## A sky that moves without a re-bake
A probe bake follows each path until it escapes, and what escapes carries the
sky's colour — so an ordinary bake fixes the sky the moment it finishes.
The sky enters as `throughput * sky` where a ray escapes, and `throughput` does
not depend on the sky, so the field splits exactly, per channel:
```
field(sky) = lights + sky * aperture
```
```lua
local skyResponse = require("@builtin::systems.globalIllumination.skyResponse")
skyResponse.calibrate(volId) -- two bakes, once
skyResponse.apply(volId, { 0.3, 0.6, 0.9 }) -- no bake
```
`SkyResponse.component` is the authored form: calibrate once, then move
`skyR` / `skyG` / `skyB`.
Both terms come from bakes at the same settings, and the bake seeds each path
from the probe and sample index alone — so the two runs trace the same paths
and the subtraction that isolates the aperture carries no sampling residual.
## Lighting scenarios
A volume holds one bake, so a scene lit for noon cannot become a scene lit for
dusk without baking again — which takes far longer than a transition is allowed
to. Capture each bake under a name and blend the captures:
```lua
local scenarios = require("@builtin::systems.globalIllumination.scenarios")
-- light the scene for noon, bake, then:
scenarios.capture(volId, "noon")
-- light it for dusk, bake again, then:
scenarios.capture(volId, "dusk")
scenarios.blend(volId, { noon = 0.25, dusk = 0.75 })
```
`LightingScenario.component` is the authored form of the two-state case: name a
`from` and a `to` and drive `blend` from 0 to 1.
Irradiance adds, so blending the SH coefficients is the same as blending the
light that produced them. Each coefficient's fourth lane carries the probe's
per-axis visibility reach rather than light, and is taken whole from the
heaviest-weighted scenario — the mean of two distances describes no wall that
exists.
## A bake stays true to its scene
A bake is a photograph of a moment. Move a baked wall and its lightmap
goes on describing where the wall used to be — the shadow it cast stays
painted on the floor it no longer touches.
So a bake maintains itself. `BakedLighting` watches the engine's
authored-change feed (`layers.onEntityChanged`) and reacts the moment an
edit reaches the bake: the artifacts that described the old scene are
dropped, the withheld lights come back, and the scene re-bakes once the
edits settle. The bake attaches that component itself, so a scene that
has been baked is a scene that maintains its bake — there is nothing to
remember to run.
Dropping the artifacts (rather than flagging them) is what makes the
staleness visible: the viewport goes from baked to honest realtime light
the moment the edit lands.
Static geometry and every light the bake consumes reach it. Movable geometry
and dynamic lights never entered one, so editing them reaches nothing.
`BakeState.affects` is the answer, measured against a signature of what
the bake actually reads — which is also why the bake writing its own
bookkeeping back onto the entities it just baked cannot re-trigger it.
Turn off automatic re-baking (invalidation stays) with:
```luau
entity.find("scene").component.add("BakedLighting", { autoBake = false })
```
## Seeing the bake
Baked lighting is the one thing in a scene with no silhouette — texels on
surfaces and coefficients in a grid — so "did this actually capture the
room?" is otherwise a question you answer by reasoning rather than by
looking. Two overlays answer it directly, in the editor's Visualization
panel:
- **Baked Probes** — every baked probe drawn where it sits, tinted by the
light it captured, inside its volume's bounds. Light falling off through
the volume becomes visible and a dead probe reads as a black dot.
Displayed on a gamma curve: indirect light spans orders of magnitude, so
a linear scale against the brightest probe would draw most of a room as
black and claim a good bake captured nothing.
- **Lightmapped Surfaces** — a box around every surface currently drawing
baked texels, so lightmapped and probe-lit geometry are told apart at a
glance.
Both appear in the panel only while the scene holds what they draw. An
unbaked scene lists neither; baking makes them appear. That comes from
`debugViz.registerProvider(name, fn, { label, default, available })` — a
package contributes an overlay and declares when it has something to
show, without the debug driver needing to know it exists.
## How a bake works
1. `Baking.gatherMeshInstances` collects every static mesh-bearing
entity as `{ guid, transform, attributes }` — the attributes carry
the surface's linear albedo (base_color × average base-color texture
color) and emissive, read through the material's own asset behavior.
2. `compute.buildBvh` builds the scene BVH engine-side and uploads the
node + triangle buffers; each triangle carries its instance's
attributes, so the kernels know how every surface reflects and emits.
3. The bake kernel runs one thread per texel (lightmaps) or probe
(volumes). Each thread traces `samples` paths of up to `bounces`
surface interactions, with shadowed next-event estimation at every
vertex and sky on escape.
4. The work is planned, not dispatched whole. `Baking.planChunks` splits it
into dispatches that each stay inside a per-frame ray budget
(`Baking.RAY_BUDGET_PER_FRAME`, 2^20 estimated ray traversals), sized from
a cost model (`Baking.lightmapRays`, `Baking.probeRays`: a lightmap texel
spends `17 + 64 * direct + 64` rays on direct light and contact occlusion
and `bounces * (1 + lights)` per chain; a probe spends `bounces * (1 +
lights)` per sample). Each dispatch carries its stage and range in the
kernel's `params` uniform, and the running sums live in the bake buffer
between dispatches, so how the work was split does not change the result.
5. A `Baking.newGpuScheduler` issues the dispatches, one per pass, a frame's
worth at a time. It waits for the kernels to compile first, ends each frame
with a fence (a read of a one-vec4 buffer the batch records after the
frame's dispatches), keeps at most `Baking.MAX_FRAMES_IN_FLIGHT` fenced
frames queued, and checks the render device on every wait. A device that
was lost or replaced raises `[Bake] the render device was lost during the
bake` with what the device reported (`renderer.deviceErrors`), and
releases what the pass made. The budget bounds each frame, not the bake: a
bake of billions of rays is hundreds of frames of work, which is what keeps
the device alive on an integrated GPU and in a browser.
6. A receiver lights up when its texels are read back with the resolve's
completion flag set. Its bake buffers (144 bytes a texel) are freed once the
texels are persisted, and a `bakeAll` starts a receiver only when what it
holds fits half the device's memory budget (`Baking.bakeLimits`).
### What a device bakes
`renderer.deviceLimits()` states the largest buffer, the largest storage
binding, the workgroups per dispatch and the memory budget the device affords.
The largest lightmap a bake makes is the largest power of two within the atlas
page whose bake output (64 bytes a texel) fits one storage binding (a baseline
WebGPU device binds 128 MiB, which holds a 1024 lightmap and a 2048 one needs
more) and whose bake (144 bytes a texel) fits the bake memory budget. A derived
resolution is cut there with a warning naming the limit; a pinned `resolution`
past it raises.
### When a bake fails
A bake raises with its cause: the stage, a lost device, a dispatch the engine
refused (a buffer past the storage binding limit is refused by name before it
can invalidate the frame's command buffer), an error the device reported. It
leaves nothing applied. `BakeState.rebake` drops the artifacts its stages left
and posts `bake.rebake_failed` instead of "baked lighting is current again";
`baking.all` raises naming each stage that failed; `VolumeProbe.autoPlace` raises naming
the volumes that failed when any did, and marks no light baked. A failed automatic re-bake holds
automatic re-baking until an explicit bake succeeds.
## Quick start
### Lightmap
```luau
local Lightmap = require("@builtin::systems.globalIllumination.lightmap")
-- Bake every static receiver in the world. Without `resolution` each surface
-- derives its own from its area at 32 texels per metre, rounded up to a power
-- of two and capped by what the device can bake.
Lightmap.bakeAll({ samples = 32 })
-- Pin a resolution (a power of two from 32 up to what the device bakes) and, when
-- a scene wants a different pace, the per-frame ray budget: a larger budget
-- finishes in fewer frames, a smaller one leaves more of each frame to the
-- editor.
Lightmap.bakeAll({ resolution = 128, samples = 32, rayBudget = 2 ^ 21 })
-- Bake a single static entity
Lightmap.bake(floorId, { resolution = 256, samples = 64 })
-- Tear down (frees the bake resources + restores the original material)
Lightmap.clear(floorId)
```
### Volume probes
```luau
local VolumeProbe = require("@builtin::systems.globalIllumination.volumeProbe")
-- Author a probe volume that covers a room
local vol = entity.spawn("level_probes")
vol.localPosition = { 0, 0, 0 }
vol.component.add("VolumeProbe", {
sizeX = 20, sizeY = 6, sizeZ = 20,
resX = 8, resY = 4, resZ = 8,
})
-- Bake: publishes the field renderer-wide and persists it into the
-- scene's baked-lighting container. Every entity inside the bounds
-- receives it — no per-entity binding.
VolumeProbe.bake(vol.id, { samples = 256 })
```
## What's static vs dynamic
| Quantity | Static at bake time | Dynamic per frame |
|---|---|---|
| Geometry positions / rotations | yes | no |
| Lights (positions, colour, intensity) | yes | no |
| Sky / ambient values | yes | no |
| Material base colour | no | yes (modulated against lightmap) |
| Object position (inside a probe volume) | n/a | yes (samples nearest probes each frame) |
Re-bake when any of the "static" inputs change. Lighting changes that
are too dynamic to bake (e.g. flickering torch) should be added on top
of the baked term as additional realtime lights.
## Engine integration
This package is Luau / WGSL over generic engine capabilities: compute
shader dispatch, `compute.buildBvh` (scene BVH with per-instance
attributes), component lifecycle, the renderer's irradiance-volume set
(`lighting.setProbeVolume`), and the baked-lighting container asset
(`lightmapData`).
## See also
- `man shaders` — the WGSL bind-group layout these shaders extend
- `man compute` — compute dispatch + buffer management
- `man /Light` — the Light component baked into the result
- `man /Material` — material registry that lightmaps and receivers extend
# Grid Background
A procedural background/reference-grid surface built on `@builtin::shaders.grid_bg`. It draws grid lines over a black base colour (`0.0, 0.0, 0.0`) with full roughness (`1.0`) and no metallic response, rendered opaque with culling disabled (`cull: none`) and instancing enabled so it can back many objects at once.
## Inputs
- `colors.base_color` (`0.0, 0.0, 0.0, 1.0`) — black backdrop behind the grid lines.
- `floats.roughness` (`1.0`) — fully diffuse, no highlights.
- `render.cull` (`none`) — visible from both faces.
- `render.instancing` (`true`) — supports instanced draws.
·computeshader · born here
❒asset # compute_tree_placement
GPU vegetation placement over a terrain heightmap. One thread per `(x, z)` cell:
reads the height, computes local slope, and uses noise-based density to pick what
grows (0 = nothing, 1 = tall pine, 2 = small pine, 3 = shrub, 4 = rock).
Bindings (see bindings.yaml): `params` (read `array<f32>` — `[gridSize,
worldExtent, seed, treeLine, slopeLimit, shrubLine, ...]`), `heights` (read
`array<f32>`), `placement` (read_write `array<f32>`, the per-cell type code).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_tree_placement", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Standard Default
The baseline PBR surface — a neutral white base colour (`1.0, 1.0, 1.0`), half roughness (`0.5`), non-metallic (`0.0`), wired with the full standard texture set (base colour, normal, roughness-metallic, emissive, occlusion) and the `_NORMALMAP` / `_OCCLUSIONMAP` keywords enabled. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.pbr`. This is the starting point most materials copy and retint.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the albedo tint over the base colour texture.
- `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric, mid-gloss default.
- `floats.normal_strength` (`1.0`) / `floats.ao_strength` (`1.0`) — normal-map and occlusion intensity.
- `textures.normal_texture` / `textures.roughness_metallic_texture` / `textures.occlusion_texture` — the PBR map slots, seeded with neutral defaults.
·computeshader · born here
❒asset # intersect_pairs
The entries of two meshes that cut each other. One thread per triangle of mesh A walks the bounding volume
hierarchy of mesh B (the `bvh` family builds it, one primitive a triangle) and, for every triangle of B whose
bounds overlap, lists each part of the cut of the two triangles that `intersect_core` states (the ordinary
cut, the coplanar clips, the points on shared edges).
An entry is three words: `a`, `b` and the part. Two stages with an exclusive prefix sum (the `scan` kernel)
between them: `STAGE count` writes how many entries each triangle of A has, `STAGE write` writes the entries
at the offsets the sum gives, ordered by `a` and, within a triangle of A, in the order the tree is walked and
the parts of a pair in increasing order. Exact: the entries and their order are the same on every run.
Bind `apts`, `atri`, `bpts`, `btri`, `nodes` and, in the write stage, `start`; params `nb` (triangles of B) and
`total` (the sum of the counts, which sizes `pairs`, three words an entry). The count stage writes `cnt`. Over a live
count (`COUNT=device`, see the abi README) a triangle of A past the live ones has no entries.
## The intersect family
`intersect` is a kernel family: `intersect_pairs`, `intersect_cuts`, `intersect_unify` and
`intersect_retri` (shared by `intersect_core`). Two triangulated meshes A and B go in; the pieces of
both, cut along their common curve and along the regions they share, come out. `geometry.boolean` composes the
family with `bvh`, `scan`, `sort`, `compact` and `gather`:
1. Build the hierarchy of B (`bvh_codes`, `sort`, `bvh`, `bvh_pyramid` per level, `bvh_internal`), one
primitive a triangle (`vstart` 3 t, `vcount` 3).
2. `intersect_pairs` `STAGE count`, an exclusive `scan` of the counts, `STAGE write`: `pairs` (a, b, part),
ordered by a. `total` is the scan's total, the number of entries.
3. `intersect_cuts` over `total` entries: the endpoint records, slot `2 * entry + e`. Word 0 to 2 of a record
are the position as f32 bits.
4. `intersect_unify` (three stages) over `2 * total` slots: `rep`. `compact` of the slots with
`rep[s] == s` numbers the cut points; a cut endpoint's point is the number of `rep[s]`, and its
position is the record's position.
5. `intersect_retri` for A with `runs` from the counts and `start` and `order` the entry indices, `side` 0,
then for B with the entry indices stably sorted by b (`sort` on the b words) as `order`, `runs` the first
and count of each b and `side` 1. `STAGE count`, `scan`, `STAGE write`. Vertex references at or above
`npts` are cut endpoint slots, mapped through `rep`.
The pieces of each mesh share the cut points, so the two results agree along the curve and along the
boundary of every shared region. Each piece lies on one side of the other mesh, or on its surface.
## What a boolean reads
A boolean keeps pieces by what lies just outside and just inside each piece's centre, probed along the
piece's normal against the other mesh (`ray` winding at both probe points). Pieces on the other mesh's
surface read the same way:
- Same normal (the two surfaces coincide and face one way): the probe outside the piece is outside the other
mesh and the probe inside it is inside the other mesh.
- Opposite normals (the surfaces coincide and face each other): the probe outside the piece is inside the
other mesh and the probe inside it is outside.
| Operation | Pieces of A kept | Pieces of B kept |
|---|---|---|
| union | outside probe outside B | outside probe outside A and inside probe outside A |
| intersect | inside probe inside B | outside probe inside A and inside probe inside A |
| subtract (A minus B) | inside probe outside B | outside probe inside A and inside probe inside A, flipped |
A region shared with the same normal is kept once from A in a union and an intersection and dropped from
both in a subtract; a region shared with opposite normals is dropped from both in a union and an
intersection, and kept from A in a subtract.
# `retarget` module
`require("modules.retarget")` — skeletal animation retargeting in readable Luau.
Map a clip authored on one humanoid rig onto another, preserving the target's
shape. The behaviour lives here, in Luau, so an agent can follow and tweak it.
## How it works
Each rig maps onto the humanoid avatar type — a role → bone map derived from the
skeleton's structure, with the author's overrides laid over it (`rig:qualify()`,
see the `rig` asset type). Retarget is two steps:
1. **Bone map** — source bone → its role → the target bone filling that role.
Roles are the shared vocabulary, so any two rigs interoperate through their
mappings without a per-pair table.
2. **Shape-preserving transfer** — the target keeps its own bone lengths and rest
orientations; the animation contributes only delta-from-rest motion. Rotations
are bind-pose-corrected (the target reproduces the source's world-space motion
relative to its own rest). Only the pelvis and the root carry translation: the
pelvis's offset is taken through its animated source parent, stood on the axis
the source stands along, sized by the leg-length ratio (thigh plus shin, the
same in every pose) and re-expressed in the target pelvis's animated parent
frame, then applied relative to the target's bind. A source root's travel rides
the target root, or folds onto the target pelvis when the target has no root.
Every other bone keeps the target's own offset, so no limb or spine stretches.
Retarget is **cold**: `bake` once per (clip, target rig) and cache; the hot path
just samples the baked clip, exactly like a native one.
## Surface
- `parseRig(rig)` → enriched rig. Accepts a parsed `.rig` table, a `.rig` JSON
string, or an already-parsed rig (idempotent).
- `plan(srcRig, tgtRig)` → `{ mapped, unmappedSource, unmappedTarget, … }` —
which roles map across the rigs, and which don't (the diagnostic).
- `bake(clip, srcRig, tgtRig)` → a decoded clip table in the target's bone space.
`clip` is a decoded clip (`{ name, duration, channels, bone_names }`).
- `bakeBytes(clipBytes, srcRig, tgtRig, cacheKey?)` → retargeted clip `zanim`
bytes, with an in-memory cache keyed by `cacheKey`.
- `loadRig(ref)` → parsed rig from a `.rig` asset.
- `clearCache(cacheKey?)` → drop cached bakes (call after editing a rig profile).
## Example
```lua
local retarget = require("modules.retarget")
local src = retarget.loadRig(asset.ref("synty_character", "rig"))
local tgt = retarget.loadRig(asset.ref("hero", "rig"))
-- inspect the mapping
local plan = retarget.plan(src, tgt)
print(plan.mapped.leftarm.source, "->", plan.mapped.leftarm.target)
-- bake a walk clip onto the hero rig (cold, cached), then sample it like any clip
local walkBytes = vfs.read(asset.source("walk", "animation") .. "/data.zanim")
local walkOnHero = retarget.bakeBytes(walkBytes, src, tgt, "walk|hero")
local bind = skeleton.bindClip(walkOnHero, heroBoneOrder)
```
·computeshader · born here
❒asset # expand
Turns a count per element into runs. Element `j` takes `counts[j]` slots, in
element order; slot `s` of the result holds `owner[s]`, the element it belongs
to, and `local_index[s]`, its place within that element's run. `offsets` is the
exclusive prefix sum of `counts` (what the `scan` kernel makes of it), so every
slot finds its element by a binary search and has one writer.
`owner` is an appended output: its live count is the sum of the counts, up to
the capacity the dispatch was given. Slots at and past the live count hold -1.
An element with a count of zero has no slot; a column of all zeros gives a live
count of zero.
Dispatch over `n`, the capacity of the result. Exact.
`core.owner` runs it to give every vertex its primitive and its place in the primitive's run. `core.realize`,
`core.pairs`, `core.adjacency`, `core.resample.curve`, `core.sample.surface`, `core.normals.corner` and the geometry
nodes that make new primitives (`geometry.extrude`, `geometry.sweep`, `geometry.triangulate`, `geometry.bevel` and
others) expand their counts with it.
Over a live count (`COUNT=device`, see the abi README) the elements are the first
`domain_count` of `counts` and `offsets`, so they can be held in runs larger than
their live count, and the counter of `owner` states the sum of their counts as it is,
above the capacity too: the first `n` slots are written and the sum minus `n` is how
many did not fit. A node that states `n` as a bound checks the count against it. The
plain variant clamps the count to `n`. It binds 6 storage buffers (5 in the plain
variant).
Over live elements (`ELEMENTS=device`) the elements are the first `element_count` of `counts` and `offsets`, whatever
`n` covers: a result sized by one class (the vertices) expanded from the elements of another (the primitives). It binds
one storage buffer more.
·computeshader · born here
❒asset # hash_count
For each query position, how many indexed points lie within a radius of it,
searched through the spatial hash the `hash` and `hash_starts` kernels build. An
exclusive scan of the counts gives the offsets `hash_gather` writes each query's
neighbour list at; `core.pairs` runs the three in that order. Exact.
It reads `pts`, `order` and `range` (the index), `qpts` (xyz a query) and the
params `buckets`, `inv_cell`, `radius` and `skip_self` (1 leaves out the point
whose index is the query's, for queries that are the indexed points), and writes
`counts`, one a query. Dispatch over the queries.
·computeshader · born here
❒asset # compute_particle_update
Reference compute shader for GPU particle simulation. Each particle is 8 floats
`[px, py, pz, life, vx, vy, vz, age]`; the shader applies velocity, gravity, and
aging every frame — thousands of particles updated entirely on the GPU.
Bindings (see bindings.yaml): `particles` (read_write `array<f32>`), `params`
(read_write `array<f32>` — `[dt, gravity_y, damping, pad]`).
`damping` is the fraction of velocity a particle keeps per 60th of a second, so
the same value produces the same motion whatever rate the shader is dispatched
at: `0.98` keeps 98% of the velocity every 1/60 s at 30 fps and at 144 fps
alike.
Usage: dispatch by identity — it resolves to the shader's stable guid and
auto-compiles on first use (no setup):
`compute.dispatch("@builtin::shaders.compute_particle_update", { buffers = { "particles", "params" }, workgroups = { math.ceil(count / 64), 1, 1 } })`.
·computeshader · born here
❒asset # splat_velocity_merge
Merges the Gaussian-splat velocity accumulation into the frame's velocity
buffer, so every consumer of that buffer — motion blur, temporal
antialiasing, temporal upsampling, a denoiser's history term — sees a moving
cloud move.
## What it reads
| binding | holds |
|---|---|
| `splat_velocity` | `xy` = each splat's NDC displacement summed premultiplied by its alpha, `w` = the coverage those splats add up to. The splat pass writes it as the second target of the Gaussian channel, composited "over" in the same sorted order as the colour. |
| `scene_motion` | The frame's velocity buffer as the geometry passes left it. |
| `merged_out` | Where the merged field lands. A copy lays it back over `@scene.motion`, because a pass cannot sample the attachment it renders into. |
## The weight
`w` is coverage, and coverage is the weight. A texel the cloud fully covers
reports the cloud's displacement; a texel it half covers reports halfway
between the cloud and the surface behind it; a texel it never reached keeps
what the geometry passes wrote, bit for bit. That is the same weight the
cloud's colour arrived at the texel with, so what a velocity consumer treats
as moving is what the image shows moving.
# eye.shader
An eye: an iris refracting behind a clear cornea.
The iris sample is displaced by refracting the view ray at the cornea and
walking it `iris_depth` inward, so the iris slides as the viewing angle changes.
The cornea itself is the engine's clearcoat lobe, which keeps one continuous
specular highlight across the iris and the sclera.
`iris_radius`, `pupil_radius` and `limbus_softness` shape the disc; `iris_texture`
is sampled in the refracted frame, `sclera_texture` in the surface's own UVs.
# characterController system
Self-contained character controller + locomotion package. Install on any
entity to give it a third-person camera, WASD ground movement, and
skeletal animation driven by a Locomotion blend space — without
hand-wiring the underlying components. The player's controls drive the
character once it is bound as the local player's body
(`layers.active.players.localPlayer.avatar = entity(id)`); any other
character moves on what writes its `CharacterController` input bus.
## Layout
```
systems/characterController/
characterController.module/ -- public API (install / uninstall / preset)
init.luau -- surface used by tools and custom code
physics.module/ -- raycast helpers (ground / walls / ceiling)
movement.module/ -- velocity integration + collision resolve
data.module/ -- default config presets (standard, platformer, ...)
presets/ -- (Task 16) shipped controller + animation
-- presets (synty, default humanoid, ...)
files/ -- (Task 17) bundled assets pulled in by
-- the shipped presets (synty rig, anims)
demo/ -- (Task 20) showcase scene exercising the
-- install -> tweak -> preset loop
tools/characterController.toolbox/
-- user-facing tools (install, uninstall,
-- apply-preset). Lives here until runtime
-- VFS-driven toolbox discovery lands
-- (see #1220); the colocated
-- `.toolbox/` is the long-term home.
documentation/ -- long-form reference
01-overview.md -- what the package is, when to use it
02-install.md -- characterController.install(id, opts)
-- recipe and the components it touches
03-presets.md -- shipped presets and how to author your own
04-customize.md -- overriding components, swapping the
-- camera, custom blend spaces
```
## Flow
```
┌────────────────────┐
user / agent ──┤ characterController│
│ .toolbox │
└────────────────────┘
│
▼
┌──────────────────────┐
custom code ──────┤ characterController │── install /
(require) │ .module (API) │ uninstall / preset
└──────────────────────┘
│
▼
┌────────────────────────┐
│ CharacterController │
│ + Locomotion │
│ + MovementState │
│ + AnimDebug │
│ (+ third-person cam) │
└────────────────────────┘
│
▼
WASD-driven character with animation
on any entity, no hand wiring required.
```
`characterController.install(entity, opts)` is the only thing most callers
need — it adds the controller, the locomotion graph, the movement-state
mirror, and (optionally) a third-person camera child. The package is
self-contained: it depends only on standard utility modules and on the
animation graph engine, never on game-specific code.
## Documentation
- [`documentation/01-overview.md`](documentation/01-overview.md) — what
this package is and when to reach for it.
- [`documentation/02-install.md`](documentation/02-install.md) — the
`characterController.install(id, opts)` recipe.
- [`documentation/03-presets.md`](documentation/03-presets.md) —
shipped presets (synty, default humanoid) and authoring your own.
- [`documentation/04-customize.md`](documentation/04-customize.md) —
overriding components, swapping the camera, custom blend spaces.
# postReference_grey18
A lit 18% grey (middle grey) surface, rough and dielectric: what a light of known intensity is read off in the post-verification reference scenes.
# loading_backdrop (screen shader)
A calm, slowly drifting full-screen backdrop for the world loading screen. A deep
near-black field carries two large, soft glows that move along slow independent
orbits, finished with a gentle vignette and a faint animated grain that keeps the
gradient from banding. Animation is driven entirely by `engine.time`, so it
advances on its own during boot with no per-frame uniform updates. It is quiet by
design, so it sits behind the world's cover image, title, and progress bar. Drawn
through the `backgroundShader` UI style after registration with
`ui.registerBackgroundShader`.
# Parallax Cube (Flat)
A brick surface built on `@builtin::shaders.pbr_parallax_occlusion` with `parallax_depth_scale = 0`, so the ray-march is bypassed and the shared brick textures render as plain textured PBR (rough `0.7`, non-metallic, white base colour). Opaque, back-face culled, queue `2000`. Pair it with `parallax_cube` to A/B the parallax effect from a fixed viewpoint.
## Inputs
- `floats.parallax_depth_scale` (`0.0`) — disables the occlusion ray-march, flattening the surface.
- `floats.roughness` (`0.7`) — matte brick finish.
- `floats.normal_scale` (`1.0`) — strength of the normal map.
- `textures.height_texture` — the brick height map (unused while depth scale is `0`).
# postReference_siemensStar
A Siemens star of 36 spokes, 0.9 on 0.02: the spokes narrow below a pixel toward the centre, where a temporal resolve aliases.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# Skybox
An unlit cubemap skybox rendered from the inside of the mesh, built on `@builtin::shaders.cubemap_unlit`. Uses front-face culling and no depth write so it draws behind all scene geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` environment.
## Inputs
- `textures.base_color_texture` — the cubemap sampled as the background (`Ryfjallet_cubemap`).
- `floats.reflect_mode` (`0.0`) — samples the cube directly as a background rather than as a reflection.
- `colors.base_color` (`1.0, 1.0, 1.0`) — tint applied to the sampled cubemap.
·computeshader · born here
❒asset # scan_mat4
The running product of a run of 4x4 matrices, whole or per segment: the frames
of a sweep, each placed relative to the one before it.
A matrix is 16 consecutive floats, column by column. The product runs in run
order, so `out[i] = m[0] * m[1] * ... * m[i]`. `params.exclusive` picks the
product of the matrices before each one (the identity for the first) or the
product up to and including it. `total` holds each group's product, the
identity for an empty group. A segmented scan (`params.segments` above 0, the
number of segments) restarts at each start in `starts`.
One workgroup scans one group at a time, a tile of 128 matrices at a time, with
the product of everything before a tile carried into the next. The dispatch size
`n` is the number of matrices; any workgroup count from 1 up scans every group.
Exact: the order of multiplication is fixed, so the same run gives the same bits
on every dispatch.
# `hdrChart` post-process shader
The synthetic HDR chart: a picture whose every pixel holds light its
properties and its position state, drawn in place of the scene. Registered
first in the chain (`postMetrics.chart.show`, priority -1000), it is the input
the display transform and every effect after it read, so they are measured
against known light with no lighting, geometry or material in between.
`@builtin::modules.postMetrics` computes the same light for any pixel on the
CPU (`chart.light`) and builds the picture a display curve should present for
it (`chart.reference`).
| Property | Meaning |
|---|---|
| `pattern` | 0 ramp, 1 grey wedge, 2 ColorChecker, 3 colour wedge over its grey. |
| `low`, `high` | The ramp's light at the left and right edges. |
| `evMin`, `evMax` | The wedges' leftmost and rightmost stops; each column is middle grey (0.18) at a whole stop. |
| `gain` | The ColorChecker's light, as a multiple of its reflectance. |
| `color` | The ramp's tint, and the colour wedge's saturated patch (scaled to its column's grey luminance). |
| `dither` | Triangular noise of that many code values either way, added in display-encoded sRGB. |
The effect declares `space: light`.
·computeshader · born here
❒asset # intersect_retri
The triangles of one mesh retriangulated along the segments that cut them. One thread per triangle: a
triangle no segment reaches is written as itself; a cut triangle is worked in its own plane, in world
lengths, where its corners and the cut endpoints are the points and its sides and the cut segments are the
constraints. The triangulation holds every constraint first (each cut out by the points that lie on it),
then holds the remaining candidate edges shortest first, a length class at a time (the exponent and top
three mantissa bits of the squared length), each when it crosses no held edge and has no point on it. The held edges are a planar graph: the
neighbours of each point are sorted by direction, the faces are walked with their inside on the left, a face
of three points is a triangle and a face of more is cut ear by ear (each ear a corner that turns left with no
other point of the face inside it or on its sides), and the face outside the triangle is left out. Every
triangle is wound the way the source triangle was, so the pieces of a triangle agree on the direction of every
side they share however thin the sliver between two cut points. A triangle whose three points stand on one
line in the world has no area and is left out. Every cut segment is a union of edges of the result, and the
pieces of a triangle tile it. Points and distances are compared within a few steps of the coordinates'
precision (`5e-7` of the largest coordinate of the triangle, and no less than `1e-7` of its longest side),
the same measure for a triangle of either mesh, so cut points a few millionths apart are told apart by the
triangles of both meshes alike.
Param `side` names the mesh the pass cuts, 0 for A and 1 for B; a segment cuts the mesh when its endpoint
records say so (`intersect_core`). A triangle takes every point of its entries, a segment of no length
giving a point on an edge and nothing more.
`STAGE count` writes how many triangles each triangle becomes; `STAGE write` writes them at the offsets of
the prefix sum, four words each (three vertex references, the source triangle) from word 4 of `out`. A
reference below `npts` is a point of the mesh; `npts + s` is the cut endpoint in slot `s`, which
`intersect_unify`'s `rep` names. `out[0]` is 1 when a triangle ran out of working space, which the sizing
below prevents. `geometry.boolean` builds the pieces of each mesh from `out`.
It binds `pts`, `tri`, `cut`, `runs`, `order` and `out`, with `cnt` in the count stage and `off` (the exclusive
prefix sum of the counts) in the write stage; the params are `npts`, `total`, `entries` and `side`. Over a live count
(`COUNT=device`, see the abi README) a triangle past the live ones becomes no triangle.
## Working space
A triangle takes a slice of working memory sized by its entries, so the number of points a triangle can
carry follows the data: a run of `m` entries gives at most `3 + 2 m` points, `3 + m` segments and three
edges a point, and the slice is `64 + 40 m` words. The slices of consecutive triangles follow one another
and make the tail of `out`, after its 4 header words and the `4 * total` words of the triangles
(`total` is 0 in the count stage): the slice of triangle `t` starts `64 * t + 40 * first(t)` words into the
tail, `first(t)` the first entry of its run, so the runs' firsts are the exclusive prefix sum of their
counts (the `start` of `intersect_pairs` for mesh A, the offsets of the per-b counts for mesh B). `out`
is sized `4 + 4 * total + 64 * n + 40 * entries` words from the params `total` and `entries` (the number of
entries of `intersect_pairs`).
The triangles of mesh A are grouped by `a` already (`runs` is `start` and the counts of
`intersect_pairs`, `order` the identity); for mesh B the entries are stably sorted by `b` first and
`order` holds the sorted entry indices. Exact: each triangle is worked alone and in a fixed order.
·computeshader · born here
❒asset # jump
One round of pointer jumping over a run of links, three ways:
- `rank` (MODE rank): list ranking. Repeated rounds give each element its root and
its distance to it, for chains and trees. Both live in the double-buffered
`parent`/`parent_out` and `value`/`value_out` pairs; the caller swaps them
between rounds.
- `min` (MODE min): doubling of the smallest label within reach. After
ceil(log2 n) rounds, every element on a cycle holds the cycle's smallest label.
- `label` (MODE label): label propagation over pairs, in place. Iterated to
`changed` = 0 it labels each connected set of elements with its smallest label.
`changed` counts what the round altered; the caller zeroes it before a round and
reads it after, so iteration with a stop is one dispatch and one count per round.
Integers are 32-bit words and every mode is exact: the final labels do not depend
on the order invocations ran in.
The label mode reads the pairs from `la` and `lb`; rank and min read `parent` and
`value` and write `parent_out` and `value_out`. `core.boundary` orders its loops
with min and rank rounds, `curve.chain_ranks` ranks chains with it, and
`core.islands` labels connected sets with the label mode.
Over a live count (`COUNT=device`, see the abi README) the elements (rank, min) or
the pairs (label) are the first `domain_count` slots of a capacity `n`, and the `n`
param is not read. In rank and min mode a slot at or past the live count links to
itself with the value 0. It binds 8 storage buffers (7 in the plain variant).
# fluidSurface
A GPU particle simulation, rendered as a continuous liquid.
Water made of particles has a problem: the particles are spheres, and a pile of
spheres looks like a pile of spheres. Turning them into a mesh every frame is
expensive and the mesh is thrown away immediately. This package skips the mesh —
it renders the particles into screen-space fields and shades those, so the
particle data never leaves the GPU and the cost scales with screen pixels rather
than with the surface's geometric complexity.
## What it does
```lua
local fluidSurface = require("@builtin::systems.fluidSurface.modules.fluidSurface")
local rts = fluidSurface.attach("lake", {
particles = { buffer = sim, stride = 16, posOffset = 0, count = 400000, velOffset = 4 },
radius = 0.35,
})
```
`particles` describes the record layout of the buffer the caller's simulation
writes: how wide a record is, where the position sits in it, and how many are
live. Pass the handle a compute shader's `createBuffer` answered. Everything
after that happens per frame until `detach`.
`update` moves the live knobs — the particle count as a sim grows, the sun
direction as the day turns, any composite property:
```lua
fluidSurface.update("lake", { count = active, sunDir = { 0.3, 0.8, 0.2 } })
```
## The chain
1. **Splat** (engine raster). Every particle draws as a velocity-stretched
billboard: nearest-surface depth, hardware z-tested; additive thickness and
thickness-weighted colour; and, when the records carry a foam weight, an
additive foam sprite layer.
2. **Narrow-range filter** (`fluid_narrow_x` → `fluid_narrow_y`, ping-ponged
`iterations` times). Neighbour depths are clamped into a band around the
centre before averaging, so particles fuse into a surface while silhouettes
stay crisp. The body is the `fluid_narrow_filter` shader module, included by
both axes.
3. **Resolve** (one of `fluid_resolve`, `fluid_resolve_col`,
`fluid_resolve_foam`, `fluid_resolve_col_foam`). Packs smoothed depth,
blurred thickness and the foam fraction into `data`, and the mean liquid
colour along each ray into `liq`. Which one runs is decided by whether the
records carry a colour and a foam weight, because that changes which textures
the pass binds.
4. **Composite** (`fluid_surface_composite`, a post-process shader). Refracts the
already-rendered scene through the surface normals, absorbs along the view
ray by Beer–Lambert, marches the reflected ray against scene depth so the
water mirrors what is above it, adds sun specular, and lays foam on the thin
edges. Depth-tested against the scene, so fluid behind geometry stays hidden.
Every stage runs at `resolutionScale` of the screen (half by default).
## Sharing
The passes are compiled once and shared by every surface. What a surface owns is
its render targets, its own filter-parameter buffer, and its own composite —
which is why two lakes at different particle radii filter at different widths
without interfering.
# areaLights system
Lights that emit from a surface rather than from a point.
Every screen, neon sign, glowing window, ceiling panel and lantern face is an
area emitter. Standing a point light in the middle of one gets the brightness
roughly right and the character completely wrong: a point puts a pinpoint
reflection on the floor and a radial falloff on the wall, where the real thing
puts the shape of the emitter and a falloff that follows its extent.
## Using it
An emitter that should follow an entity's face is a component:
```lua
local id = entity.spawn("tv").id
entity(id).component.add("SurfaceLight", {
width = 2.0,
height = 1.2,
face = "front", -- front | back | up | down | left | right
intensity = 6.0,
range = 12,
})
```
The rectangle turns with the entity, so a tilted screen lights the direction it
actually points. Every field is live, and an `intensity` of 0 removes the light.
For code placing emitters directly:
```lua
local surfaceLight = require("@builtin::systems.areaLights.surfaceLight")
surfaceLight.set("strip", {
position = { 0, 5, -12 },
right = { 1, 0, 0 }, up = { 0, 1, 0 },
width = 0.6, height = 7,
color = { 1, 0.72, 0.35 }, intensity = 5,
})
surfaceLight.remove("strip")
surfaceLight.configure({ diffuse = 1, specular = 0.5 })
surfaceLight.clear()
```
## What the knobs do
| field | effect |
|---|---|
| `width` / `height` | Size of the emitting rectangle, world units. The shape of the light is the shape of this. |
| `face` | Which way the entity emits. |
| `range` | How far the light carries, with a smooth cutoff at the end. |
| `intensity` | Brightness. 0 removes the light. |
| `colorR` / `colorG` / `colorB` | Emitter colour. |
| `offset` | Distance the rectangle sits proud of the entity's origin, along the face's normal. |
| `diffuse` / `specular` | Scales on the two terms — the wash across a surface, and the reflected shape of the emitter. |
Shape is the point. A wide panel puts a broad pool on the floor; a narrow strip
puts a narrow elongated one. That difference is not reachable with a point
light at any brightness.
At most 32 emitters are held at once, because the shader loops every light for
every pixel.
## How it renders
`areaLighting.renderFeature` runs one compute pass after lighting. Diffuse is
the exact irradiance of the quad — Lambert's formula over its four edges — which
matters where a point approximation fails hardest: a wide emitter close to a
wall. Specular uses the representative point on the rectangle nearest the
reflection ray, with the lobe widened to cover the emitter's solid angle and its
peak scaled down to match, so a large emitter reads broader rather than
brighter.
## Files
```
areaLights.package/
SurfaceLight.component/ -- an emitter on an entity's face
surfaceLight.module/ -- the emitter registry and scales
areaLighting.renderFeature/ -- the compute pass
```
·computeshader · born here
❒asset # hash_gather
Lists, for each query position, the indexed points within a radius of it, query
after query: query `q`'s points start at `qoff[q]`, the exclusive prefix sum of
the `hash_count` counts. The list is in the order the spatial hash walk visits
points, the same on every run. Exact. It takes the params of `hash_count`
(`buckets`, `inv_cell`, `radius`, `skip_self`) and `total`, the sum of the counts,
which sizes `items`. `core.pairs` lists its pairs with it.
Over a live count (`COUNT=device`, see the abi README) the queries are the first
`domain_count` of a capacity `n`, `total` is the capacity of `items` (the bound the
node states), and `items` is an appended output: its counter is the number of points
the live queries listed, above the capacity too when the lists do not fit (the first
`total` words are written and the counter minus `total` is how many did not). Words of
`items` past the lists are left as allocated, 0. A node that states `total` as a bound
checks the count against it. It binds 8 storage buffers (6 in the plain variant).
# postReference_greyWedge
The grey wedge: one column per whole stop from -10 to +10, each middle grey (0.18) at that exposure.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
·computeshader · born here
❒asset # compact
Turns a keep mask into the indices of the kept elements, and the map back from
every element to the place it holds among them.
`indices` lists the elements whose mask word is not 0 (a float mask of 0.0 and
1.0 reads the same way), in run order; its live count is the number kept.
`inverse` holds, for every element, its place among the kept ones, or -1 for an
element that is not kept, so a column carried to the kept elements (a gather by
`indices`) and a column of per-kept values carried back (a read through
`inverse`) agree on which element is which. The nodes that keep a subset of
elements run it: `core.select`, `core.weld`, `core.edges`, `core.boundary`,
`core.islands`, `curve.grow`, `geometry.extrude`, `geometry.ribbon`,
`instances.to_points`, `sdf.mesh` and `sim.particles`.
The dispatch size `n` is the number of elements. One workgroup of 256 works the
whole run, a tile of 256 elements at a time; the other workgroups of a larger
dispatch return.
Exact: the order is the run's own, so the same mask gives the same answer on
every dispatch.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` mask words are the elements: words past it are not read, a slot
of `inverse` at or past it holds -1, and the slots of `indices` past the kept ones
hold -1. `indices` has room for `n` and its counter is the live count the next kernel
takes as its domain. It binds 5 storage buffers (4 in the plain variant).
# Checkerboard White
A static white/grey checkerboard rendered by `@builtin::shaders.checkerboard`, alternating a white base colour (`1.0, 1.0, 1.0`) with a dark grey check colour (`0.3, 0.3, 0.3`). Animation is disabled (`animation_speed 0.0`), giving a fixed, neutral grid — ideal as a level-design blockout or scale-reference floor. Opaque, non-metallic (`metallic 0.0`) at mid roughness (`0.5`).
## Inputs
- `colors.base_color` — the white square colour.
- `colors.check_color` — the dark grey square colour.
- `floats.animation_speed` (`0.0`) — held at zero for a static pattern.
- `floats.roughness` (`0.5`) — diffuse spread on the squares.
# postReference_white
A flat unlit white of 0.8 light: the thin geometry of the temporal reference scene (wires, a fence, a fan's blades) drawn against the dark, so every pixel it touches stands out from its neighbours.
Drawn by `@builtin::shaders.referenceChart`. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# flipbook (shader)
Plays a texture sheet on a card. The card's `shader_data` lanes say which cells of the sheet to show: lane 0 holds (frame, next frame, how far between them) and lane 1 holds (columns, rows) - the lanes `sim.flipbook` writes onto particle points as `data0` and `data1`. Frames count row by row from the top-left cell. When how far between them is above 0 the two frames are blended by it; a card whose lanes are zero shows the first cell of a 1 by 1 sheet, the whole texture.
The `base_color_texture` is the sheet and `base_color` times the vertex colour tints it; `emission` (0 to 64, default 1) scales the colour for an additive, bloom-fed look. With `face_camera` on (above 0.5, default 1) the card turns to face whichever camera draws it, keeping its own width and height; off, it keeps the pose the instance stands at. `vertexBoundsDilation` (metres, default 4.1) is how far that turn can carry a card's corners, which the cull allows for. The fragment is unlit and returns the sheet's alpha times the tint's, discarding a fragment whose alpha is below 0.001, so the material's blend state (alpha, additive, premultiplied) says how it combines with what is behind it.
# test
Test framework — simple unit testing with the `describe` / `it` /
`expect` pattern. Used by the engine test suite and any user-authored
suites that want a single dependency. Pure Luau; flag-based failure
tracking instead of exceptions (works the same on native and WASM).
## Exports
Definition:
- `Test.describe(name: string, fn: () -> ()) -> Suite` — define a suite. The body declares the suite's cases, so only what it reached is in the run: a body that ends on a raise leaves a `<describe body did not finish>` case behind, naming the describe and what it raised, and the run ends on that case. A body that stands down leaves the same case marked skipped, carrying the reason.
- `Test.it(name: string, fn: (TestContext) -> ()) -> any?` — define a test.
- `Test.skip(name: string, fn: ((TestContext) -> ())?) -> any?` — skip a test. Inside a `describe` with a body it declares a skipped test; inside a running test (its body or one of its hooks) a reason alone stands that test down — the test ends there, is counted under `skipped`, and the reason reaches the console, the per-test record and the report. A reason alone anywhere a test is not running raises, naming the declaration form.
- `Test.beforeEach(fn: () -> ())` / `Test.afterEach(fn: () -> ())` — per-test hooks.
- `Test.expect(value: any) -> any` — expectation builder with `toBe`, `toBeTruthy`, `toBeFalsy`, `toBeNil`, `notToBeNil`, `toBeType`, `toBeGreaterThan`, `toBeLessThan`, `toBeCloseTo`, `toContain`, `toMatch`, `toHaveLength`, `toThrow`, `never()`.
- `Test.captureFailure(fn: () -> ()) -> string?` — run a body and return the failure it records instead of recording it, for tests that assert a matcher rejects something. A body that records several returns the headline for them.
- `Test.captureOutcome(fn: () -> ()) -> Outcome` — run a body the way the runner runs a test body and return `{ failed, error, failures, raised }`: its failures in the order they happened, with a raise that ended the body as the final entry.
- `Test.captureTestOutcome(spec: TestSpec) -> TestOutcome`: run a whole test the way the runner runs one (`beforeEach`, the body, `afterEach`, then the cleanups registered while it ran) and return `{ skipped, reason, failed, error, failures, raised }`. The runner reads its verdict from the same place, so what this reports for a captured test is what a sweep reports for a real one. A scene layer the captured test leaves loaded that was not loaded when it started is unloaded afterwards, as the runner unloads one after each test.
## What a failing test reports
A matcher records its failure and lets the body run on, so one body can produce
several. They are kept in the order they happened:
- `error` — the headline, and the one line the console, the engine log and the
report's result table carry. It is the failure that came first, plus
`(+N more)` counting the ones after it — `(+N more, ended by a raise)` when a
raise is what stopped the body.
- `failures` — the failures in order, on `Test.results[]`, in each per-test
JSON file under `Test.PER_TEST_RESULTS_DIR`, and in the JSON report. The
Markdown report lists them under the failing test's heading. A body that
records more of them than the list keeps ends it with a line counting the
rest and naming the last of them, so one test asserting inside a long loop
stays one bounded entry in the report.
The hooks that run around a body record onto the same list it does, so an
assertion a `beforeEach`, an `afterEach` or a registered cleanup fails — and an
error one of them raises — is a failure of the test it ran for and travels to
every consumer the body's failures reach. Each names the phase it came from
(`afterEach: Expected …`, `cleanup: Runtime error: …`); a body's own failures
stay unlabelled. A cleanup that raises still leaves the cleanups behind it to
run.
## Standing a test down
A test whose precondition this engine does not meet has nothing to verify and
has earned no pass. `Test.skip(reason)` from inside the running test says so:
```lua
Test.it("renders N copies from one transform buffer", function()
if engine.gpuCompute ~= true then
Test.skip("GPU compute reported unavailable (engine.gpuCompute)")
end
-- …the test, on an engine that can run it
end)
```
The test ends at that call. It is counted under `skipped`, printed as
`○ <name> (skipped: <reason>)`, and the reason travels as the `error` field of
its `Result` row, into its per-test JSON file, and into both reports. A
`beforeEach` may stand the test down the same way, and then the body never runs.
Whatever the test's hooks record around a stand-down is a failure of the test
they ran for and outranks it: a teardown that fails after a body stood down
reports the test as failed.
A reason on its own reaches a test that is running. Inside a `describe`, where
`Test.skip` declares, the call takes a body — a reason alone raises there,
naming the declaration form.
Run / inspect:
- `Test.run() -> boolean` — execute every registered suite; `true` when all pass.
Call from a yieldable context (the `tests` toolbox does) so multi-frame tests
yield. Discovering + running every suite is the `tests` toolbox's job
(`tests.run`), not this framework's.
- `Test.clear()` — reset suites + stats (re-run from clean state).
- `Test.getResults() -> { Result }`, `Test.getStats() -> Stats`.
Multi-frame / sandboxing:
- `Test.waitFrames(n: number?)` — yield until at least `n` engine frames elapse.
- `Test.tmpPath(relativePath: string?) -> string` — sandboxed path under `Test.TMP_ROOT`.
- `Test.prepareTmp()` / `Test.cleanupTmp()` — recreate / remove the tmp root.
Notices:
- `Test.noticeMark(template: string) -> NoticeMark` / `Test.noticesSince(mark) -> number`:
how many times a notice posted under `template` fired after the mark.
A drain seals the row it returns and the next emission starts a new row, so
this counts across every row of the template.
- `Test.latestNotice(template: string) -> any?`: the stored row of that template
the most recent emission landed in.
Scene layers:
- `Test.useScene(opts?) -> SceneProxy` — mint an isolated scene for the current
test from a `.scene` fixture and load it (root, or an additive overlay with
`{ additive = true }`). Unloaded and removed at teardown.
- `Test.useSceneEach(opts?)` — suite-level sugar: one freshly minted scene per test.
- `Test.ensureRootLayer() -> SceneProxy` — take a root scene layer for the
current test, so `layers.active` and the scene-scoped surfaces behind it
answer inside a test. Returns the loaded root, loading a stand-in scene from
`Test.BASELINE_SCENE` when none is; the layer is unloaded when the test ends.
- `Test.releaseRootLayer()` — unload the stand-in and remove its source folder.
The runner calls it when a run ends.
- `Test.beginWorldBaseline() -> WorldBaseline` / `Test.restoreWorldBaseline(baseline)` —
bracket a whole sweep: unload the layers the engine booted with (so no suite
depends on ambient content) and put them back afterwards.
Public state:
- `Test.suites`, `Test.currentSuite`, `Test.currentTest`, `Test.stats`, `Test.results`, `Test.TMP_ROOT` (`/zero/source/tmp/tests`).
Types:
- `Stats = { total, passed, failed, skipped: number }`
- `Result = { suite, test: string, passed, skipped: boolean, error: string? }` — on a skipped row `error` is the reason the test stood down
- `TestContext = { waitFrames, expect, fail, suiteName, testName }`
- `Suite = { name, tests, beforeEach?, afterEach? }`
- `Outcome = { failed, raised: boolean, error: string?, failures: { string } }`
- `TestOutcome = Outcome & { skipped: boolean, reason: string? }`
- `TestSpec = { body: (TestContext) -> (), beforeEach?, afterEach?: () -> (), name: string? }`
- `RunAllOpts = { path: string? }`
- `NoticeMark = { template: string, counts: { [string]: number } }`: each stored row's count at the mark, by row
## Usage
```luau
local Test = asset.containing(__FILE__).modules.shared
Test.describe("My Suite", function()
Test.it("does basic things", function()
Test.expect(1 + 1).toBe(2)
Test.expect("hello").toContain("ell")
end)
Test.it("cascade despawn cleans children across frames", function(t)
local parent = entity.spawn("parent")
local child = entity.spawn("child")
child.setParent(parent.id)
t.waitFrames(1) -- let setParent settle
entity.despawn(parent.id)
t.waitFrames(2) -- let cascade + ECS despawn run
Test.expect(entity.exists(parent.id)).toBe(false)
Test.expect(entity.exists(child.id)).toBe(false)
end)
end)
Test.run()
```
## Parts
The module is a folder of parts, each a module of its own that `init.luau` requires:
- `Test.valueText`: the structural, bounded rendering `Test.describeValue` gives a table.
- `Test.worldReadings`: the readings of engine-wide state a teardown settle and the scene-rect hand-back compare.
- `Test.ownership`: which modules, GPU buffers and compute resource rows are the engine's own, which the floor readings leave out of what a suite answers for.
## Notes
- Failure is flag-based, not exception-based — every matcher records the
failure but allows the body to keep executing. Avoids WASM C++
exception handling cost.
- The runner records the loaded scene layers and the entity set before each
test. Afterwards it unloads every scene layer the test left loaded that was
not loaded before it, newest first, so the entities that layer's load built
leave with the layer and the scene's source is what its next load builds
from. It then despawns any other newly-spawned entity (mutations apply after
the `execute()` batch returns; `cleanedUpIds` makes the snapshot tolerate
deferred cleanup).
- After each test the runner defensively returns the scene to `edit`
mode if a body or its `afterEach` leaked `play`. This stops a single
mode-leaking test from cascading silently into every downstream
`vfs.write`-using suite.
- Multi-frame `t.waitFrames` needs a yieldable call chain. A non-yieldable
C-frame above `Test.run` (e.g. driving it from inside a `require`) makes
`waitFrames` raise a sentinel and the test is marked SKIPPED — the body had
nothing to verify, so what it recorded is dropped and what its setup recorded
stands. A hook that fails around such a body still fails the test. The `tests`
toolbox (`tests.run` → `AssetRef:run()`) runs the suite in a plain
coroutine, so the real wait path exercises.
- `toThrow` calls its subject under `pcall` and fails when the call
returns normally. `toThrow("substring")` additionally requires the
rendered raised value to contain that substring. `never().toThrow()`
asserts the call completes.
# parallax_cube
Brick wall material using `@builtin::shaders.pbr_parallax_occlusion`
with the parallax march enabled (`parallax_depth_scale = 0.08`, 48
ray-march layers). Pair with `parallax_cube_flat` for a same-textures,
no-POM A/B comparison.
## Shader
`@builtin::shaders.pbr_parallax_occlusion` — see that shader's README
for the full parameter list.
## Textures
All from `@builtin::textures.parallax_bricks` (height/normal derived
from three.js's MIT-licensed `brick_bump` + `brick_diffuse`):
- `base_color_texture` → `bricks_albedo`
- `normal_texture` → `bricks_normal`
- `roughness_metallic_texture` → `bricks_roughness`
- `occlusion_texture` → `bricks_ao`
- `height_texture` → `bricks_height`
## Usage
```luau
Material.Apply(entityId, "parallax_cube")
-- Override at runtime:
Material.SetProperty("parallax_cube", "parallax_depth_scale", 0.12)
```
Pair it with `parallax_cube_flat` (same textures, `parallax_depth_scale = 0`)
to compare the ray-marched surface against a flat-mapped baseline.
## Notes
- `Material.SetProperty` mutations are global — every entity using
`parallax_cube` sees the change. If you need per-entity variation,
derive a new material name and override the property there.
- Use under any standard camera (forward path). The deferred path is
not yet POM-aware; materials applied to a deferred camera will
render as plain textured PBR.
# `colorGrade` post-process shader
Brightness, saturation and contrast as multipliers around an identity of 1.0.
`pp.add(name, "colorGrade", { brightness = 1.1, saturation = 0.8 })` registers it, and
`asset.resolve("@builtin::shaders.post.colorGrade", "shader"):getProperties()`
reads the knobs below before it is added.
The three run in that order on the sampled frame: brightness scales the light,
saturation scales each colour's distance from the grey of its own Rec. 709
luminance along its hue, and contrast scales luminance in log space about
middle grey as the picture shows it at the exposure in force. Each is a
multiplier, so 1.0 leaves the frame as it was and all three at 1.0 pass it
through unchanged.
Contrast holds middle grey where it was and moves every stop above or below it
by the same share: at 1.25 a shadow two stops under middle grey shows two and a
half stops under it, and a highlight two stops over shows two and a half over.
Every pixel carrying light keeps some, so a dark scene graded with contrast
above 1 keeps its shadow detail and an exposure change after the grade still
lifts it. Saturation stops where a colour's weakest channel reaches no light,
so a colour keeps its hue: orange stays orange and skin stays skin.
On the `display` or `all` layer, after `__display__` has fitted the picture to
the screen, contrast and saturation also hold the picture's white: contrast
moves each stop of a highlight's headroom to white by the same share it moves
a shadow's stops, and saturation stops where a colour's strongest channel
reaches white, so a highlight short of white stays short of it.
Contrast and saturation are `@builtin::shaderModules.colorGrading`'s, which a
grade a world writes includes for the same response.
`color_correction` grades the same three quantities as ADDITIVE offsets around
0.0 and adds a tint colour, so a look authored for one does not transfer to the
other by copying its numbers.
| Property | Meaning |
|---|---|
| `brightness` | Multiplies the colour. |
| `saturation` | 0 is luminance alone, 1 is the frame's own colour, above 1 more colour along the same hue. |
| `contrast` | Scales each pixel's distance in stops from middle grey (log space): 1 leaves it, above 1 spreads the stops apart, below 1 draws them together. |
·computeshader · born here
❒asset # compute_double
Reference compute shader that doubles every `f32` in a storage buffer — the
simplest possible compute pattern (one read-write buffer, no inputs).
Bindings (see bindings.yaml): `data` — read_write `array<f32>`.
Usage: dispatch by identity — it resolves to the shader's stable guid and
auto-compiles on first use (no setup):
`compute.dispatch("@builtin::shaders.compute_double", { buffers = { "data" }, workgroups = { 1, 1, 1 } })`.
# Neon
A glowing cyan neon surface built on `@builtin::shaders.pbr` with emission enabled. It pairs a bright cyan-blue base colour (`0.2, 0.8, 1.0`) with a matching emissive colour driven hard by `emissive: 5.0`, so it reads as a self-lit light source. Low roughness (`0.2`), non-metallic, opaque, instanced, with the `_EMISSION` keyword enabled.
## Inputs
- `colors.emissive` (`0.2, 0.8, 1.0, 1.0`) — cyan glow colour.
- `floats.emissive_intensity` (`5.0`) — strong emissive intensity (feeds bloom).
- `colors.base_color` (`0.2, 0.8, 1.0, 1.0`) — matching cyan base tint.
- `floats.roughness` (`0.2`) — glossy surface under direct light.
# subsurface
A metallic-roughness surface that also transports light beneath itself, for
skin, foliage, wax, marble and thin fabric.
Set `subsurface_color` to the tint of the light that scatters through; leaving
it black makes this a plain metallic-rough surface. `subsurface_radius` sets how
far light spreads beneath — larger values wrap the shading further past the
terminator, and reach further in whichever channels the colour is strongest in.
`thickness` (and `thickness_texture`) control how readily a backlit surface
glows. Thin geometry transmits; thick geometry stays solid.
Both effects are evaluated in the engine's light loop, so they are shadowed and
attenuated like every other lobe.
·computeshader · born here
❒asset # compute_terrain
GPU voxel-terrain generation: produces block data for a chunk. One thread per
`(x, z)` column, filling the full Y column with block types (air, grass, dirt,
stone, sand, water, wood, leaves, snow).
Bindings (see bindings.yaml): `params` (read `array<f32>` — `[chunkSizeX,
chunkHeight, chunkSizeZ, chunkWorldX, chunkWorldZ, seaLevel, seed, 0]`), `blocks`
(read_write `array<u32>`, indexed `[z * H * S + y * S + x]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_terrain", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
·computeshader · born here
❒asset # walk
One thread per walker running `steps` dependent steps: each walker's start state goes in, its end
state and the state after every step come out, with the number of steps it ran. A state is 1 to 8
floats (`width`).
The step is a Field, handed to the kernel the way `map` takes its template: the fields package
fuses the Field into WGSL expressions and the kernel is specialized with them. A node holds no
WGSL.
| Specialization | Type | Meaning |
|---|---|---|
| `WALK_STEP` | `vec4<f32>` expression | lanes 0 to 3 of the next state; default `zero_walk_advance(s)`, the constant step |
| `WALK_STEP_HI` | `vec4<f32>` expression | lanes 4 to 7 of the next state; default `s_hi` |
| `WALK_DONE` | `bool` expression | whether the walker stops before step `k`; default `false` |
| `WALK_PRELUDE` | module-scope WGSL | the functions the expressions call, and `#include` lines for the `rand`, `noise` and `color` preludes |
The expressions read the state leaves `s` (lanes 0 to 3) and `s_hi` (lanes 4 to 7), the step
number `k` (u32) and the walker number `id` (u32), the numbers of `u` (`u_get(n)`) and the columns
of the `cols` table (`cols_f32(slot, i, lane)`, `cols_vec3(slot, i)`), which is how a step reads a
raster, a field column or a per-walker attribute. The constant step needs no Field: its vector is
the params `dx`, `dy`, `dz` and `dw`.
Bind `cols` (a table from `compute_abi.table`), `u`, `start` (`width` floats a walker). Outputs:
`finish` (`n * width`), `path` (`n * steps * width`, row `k` of walker `i` at
`(i * steps + k) * width`) and `steps_run`.
```luau
local variant = ref:program():variant({ specialize = {
WALK_STEP = "vec4<f32>(s.x + 1.0, s.y * 0.5, 0.0, 0.0)",
WALK_DONE = "s.x > 8.0",
} })
local run = variant:run({ n = walkers, inputs = { cols = emptyTable, u = numbers, start = startBuffer },
params = { steps = 8, width = 2 } })
```
`fieldc.walkSpec(step, opts)` writes the specializations from a step Field over the leaves `field.walk_state` and
`field.walk_index`, and `fieldc.bindSpec(spec)` the `cols` and `u` to bind; `device.kernel` runs the kernel with them
(the abi README states the form).
Exact: each walker writes its own path rows, so the result does not depend on thread order.
·computeshader · born here
❒asset # compute_voxelize
Voxelizes a triangle mesh on the GPU. For each grid cell it casts a ray along +X
and counts Möller–Trumbore triangle intersections — an odd count means the cell is
inside the mesh.
Bindings (see bindings.yaml): `triangles` (read `array<f32>`, 15 floats/triangle),
`params` (read `array<f32>` — `[minXYZ, maxXYZ, resXYZ, voxelSize, triCount, 0]`),
`output` (read_write `array<f32>`, one per cell: 1.0 = occupied, 0.0 = empty).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_voxelize", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# probeGI
Indirect diffuse light from a field of probes traced against the scene. The
`probeGI` render feature places probes on a grid that follows the camera, traces
rays from each every frame through the scene's acceleration structure, keeps each
probe's irradiance and distances as small octahedral maps blended over frames,
and adds the light those maps hold to every surface in view in a pass of its own.
- `probeGI.renderFeature` is the member a scene places.
- `probegi_trace`, `probegi_classify`, `probegi_irradiance`, `probegi_visibility`
and `probegi_apply` are the passes it runs.
- `probe_gi_common` and `probe_gi` are the shader modules the passes share.
The light the field adds takes the scene's occlusion channel (`@scene.ao`, which
an ambient occlusion member writes): each surface's light is scaled by the share
of its hemisphere the channel leaves open, raised by the multi-bounce fit for the
surface's colour. `contactOcclusion` states how much of that the field takes, 0
to 1; where no member writes the channel the light stands as the field states it.
The field resolves occluders at about its finest spacing and above, and the
occlusion channel those inside its radius, so a radius under half of
`baseSpacing` keeps the two from occluding the same geometry twice.
# postReference_checker
A checker of 64 cells across, 0.8 on 0.03: the high-frequency background a fast object crosses.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
·computeshader · born here
❒asset # search_curve
Places samples on curves by arc length. Each sample names a curve (`owner`, Int) and how far along it (`at`, Float, 0
at the start to 1 at the end); the kernel answers the segment it stands on (`segment`, a `vec2<i32>` of the vertex the
segment starts at and the one it ends at), where it stands (`placed`: the position in xyz and how far along the
segment in w, 0 at its start to 1 at its end) and the segment's unit direction (`heading`, xyz, zero for a segment of
no length).
| Specialize | Options | Meaning |
|------------|---------|---------|
| `COUNT` | `plain`, `device` | every slot is live, or the live count is read from `domain_count` and a slot at or past it is left alone |
The curves are described per vertex by `vertices` (`vec4<f32>`: the position in xyz and the arc length from the start
of the first curve in w, ascending) and per curve by `curves` (`vec4<f32>`: the vertex its run starts at in x, how many
vertices it holds in y, negative for a closed curve, the arc length that comes before it in z and its own length in
w). A sample stands at arc length `curves[owner].z + at * curves[owner].w`.
A sample on the last vertex of an open curve stands on the segment before it. On a closed curve the last vertex starts
the segment that closes the loop.
One thread per sample; the dispatch size `n` is the number of samples. Exact: every output element has one writer and
reads only its inputs, so the same inputs give the same answers on every dispatch.
`core.sample_curve` runs it and takes the sample's position, its blend between the segment's ends and its tangent from
the outputs.
# quickGeometry
Model a scene in Luau with three.js-shaped code. A `build.luau` or a `.sceneModule` builds `Group`s and `Mesh`es from geometry constructors and materials; at the end of the build the tree is stored in the scene as data, drawn by one `Generator`, and nothing runs per frame.
A bare box reads as a placeholder. Every geometry takes **modifiers** that turn it into a modelled shape: round its edges, taper it, bend it, drill it, smooth it, or build it from a profile or cross-sections. A build whose parts are mostly bare boxes and planes logs a warning that names them.
## Using it
The nouns are globals in a scene's `build.luau` and a `.sceneModule`'s entry script: `sceneNouns` and `quickLighting` join both scripts' contexts, so the engine binds their exports when it loads the script, and the language server knows the same names.
```luau
function content()
local paint = MeshStandardMaterial({ color = "#b0332f", metalness = 0.45, roughness = 0.28 })
local steel = MeshStandardMaterial({ color = "#aab2ba", metalness = 1, roughness = 0.25 })
local body = Mesh(BoxGeometry(1, 1, 1):round(0.14), paint, "rounded_box")
body.position:set(0, 0.8, 0)
local block = Mesh(BoxGeometry(1.1, 1.1, 1.1):subtract(CylinderGeometry(0.3, 0.3, 2, 24)), steel, "drilled_block")
block.position:set(1.5, 0.8, 0)
local hull = Mesh(LoftGeometry({
{ shape = EllipseShape(0.45, 0.28), z = -1.2, scale = 0.25 },
{ shape = EllipseShape(0.45, 0.28), z = -0.55, scale = 0.95 },
{ shape = EllipseShape(0.45, 0.28), z = 0.4, scale = 1.0 },
{ shape = EllipseShape(0.45, 0.28), z = 1.2, scale = 0.3, offset = { y = -0.06 } },
}), paint, "hull")
hull.position:set(3.2, 0.8, 0)
end
```
The same code works in a `.sceneModule`'s builder, where `inputs` declare what a placement may set.
A module joins those contexts with `--!context sceneBuild sceneModule` in its leading comment block, the way these two do. A world's own module joins the same way, and its exports become globals in every build script beside the nouns. A name that starts with `_` stays inside its module. A module that exports `_beginRun` and `_finish` has them called around every run of a build. The `script_context` module's README covers contexts in full.
## Parts
- `Group(name)` holds other objects. `Mesh(geometry, material, name)` draws a geometry.
- `object.position`, `object.rotation` (Euler angles in radians, XYZ) and `object.scale` take `.x`, `.y`, `.z` and the vector methods `set`, `setScalar`, `copy`, `add`, `sub`, `multiplyScalar`, `clone` and `toArray`; calls chain.
- `parent:add(a, b, ...)` nests objects under another, and their poses are then in the parent's frame; an object added elsewhere moves. `parent:remove(a, ...)` takes them out, and a removed object is not drawn until it is added again. `object.parent` and `object.children` hold the tree.
- `object.visible = false` leaves the object and everything under it out of the scene. `object.userData` is a table for your own values.
- `object:lookAt(x, y, z)` or `object:lookAt(Vector3)` turns the object so its +Z axis points at a point in its parent's frame; the object's position and the point are numbers.
- `object:clone(recursive)` copies the object, its pose, components and (unless `recursive` is false) what is under it; the copy shares the geometry and material and is placed like a new `Mesh`. `object:traverse(fn)` calls `fn` on the object and everything under it, and `object:getObjectByName(name)` finds one.
- `object:addComponent(type, data)` puts an engine component on the entity a part becomes (`Physics`, a collider, a `Joint`). A part whose pose follows a formula is drawn as an instance and takes none.
- An object that never moves and carries a component becomes an entity named for it, with its parent and local pose; one that never moves and carries none is folded into the object above it. A moving object's leaves are drawn as instances.
## Geometry
| Constructor | Shape |
|-------------|-------|
| `BoxGeometry(width, height, depth)` | box |
| `CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded)` | cylinder; a cone when one radius is 0 |
| `ConeGeometry(radius, height, radialSegments, heightSegments, openEnded)` | cone with its apex up |
| `SphereGeometry(radius, widthSegments, heightSegments)` | UV sphere |
| `TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)` | torus |
| `TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q)` | torus knot |
| `CapsuleGeometry(radius, length, capSegments, radialSegments)` | capsule |
| `PlaneGeometry(width, height, widthSegments, heightSegments)` | flat rectangle |
| `CircleGeometry(radius, segments)` | flat disc |
| `RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength)` | flat annulus |
| `TetrahedronGeometry`, `OctahedronGeometry`, `IcosahedronGeometry`, `DodecahedronGeometry` `(radius, detail)` | regular polyhedra; `detail` above 0 rounds them toward a sphere |
| `LatheGeometry(points, segments)` | a profile of `{ x = radius, y }` points revolved around Y |
| `ExtrudeGeometry(shape, { depth, curveSegments })` | an outline extruded along +Z |
| `ShapeGeometry(shape, curveSegments)` | a flat, filled outline |
| `TubeGeometry(path, tubularSegments, radius, radialSegments, closed)` | a circle swept along a curve |
| `LoftGeometry(sections, { caps })` | a surface through cross-sections along Z |
| `BufferGeometry()` | a mesh from your own arrays |
| `mergeGeometries(list)` | several geometries as one |
Every geometry also takes `translate(x, y, z)`, `rotateX/Y/Z(angle)` and `scale(x, y, z)`, which move it.
### Outlines and curves
`Shape()` records an outline with `moveTo`, `lineTo`, `quadraticCurveTo`, `bezierCurveTo` and `absarc`. `EllipseShape(rx, ry, segments)` and `RoundedRectShape(width, height, radius, segments)` return ready outlines. `CatmullRomCurve3(points, closed)` and `HelixCurve(radius, turns, height)` return curves for `TubeGeometry`.
### Loft
`LoftGeometry` takes sections in order, each `{ shape, z, scale?, offset? }`: an outline, where along Z it stands, a scale (a number or `{ x, y }`) and a move (`{ x, y }`). `caps = false` leaves the ends open. A body, a hull, a fuselage or a bottle is a loft.
### Custom arrays
```luau
local triangle = BufferGeometry()
triangle:setAttribute("position", Float32BufferAttribute({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3))
```
`setAttribute` takes `position`, `normal` and `uv`; `setIndex(list)` gives triangle indices; without normals they are computed and shared across triangles (`computeVertexNormals()`).
## Modifiers
A modifier changes the shape in its own frame, before `translate`/`rotate`/`scale` move it, and modifiers stack in the order called.
| Modifier | Effect |
|----------|--------|
| `:round(radius, segments)` | round every edge with that radius |
| `:bevel(width, segments, angle)` | round only edges sharper than `angle` degrees; `width` is how far it reaches onto each face |
| `:subdivide(levels, mode)` | split every triangle into four, `levels` 1 to 3 times; `"loop"` (default) also smooths, `"linear"` only adds points |
| `:smooth()` | one round of Loop smoothing |
| `:taper(amount, axis)` | scale the cross-section by `1 - amount * d` at distance `d` along `axis` (`"y"` by default) |
| `:twist(angle, axis)` | turn the shape about `axis` by `angle` radians per metre along it |
| `:bend(curvature, axis)` | curve it along `axis`; `curvature` is 1 over the bend's radius in metres |
| `:subtract(other)`, `:union(other)`, `:intersect(other)` | combine with another closed solid, which stands where it was moved to |
`subtract`, `union` and `intersect` take one shape and one shape; merge parts after combining. Both must be closed solids (a box, cylinder, sphere, torus, capsule or polyhedron, or a bevelled or smoothed one).
## Materials
`MeshStandardMaterial({ color, roughness, metalness, emissive, emissiveIntensity, opacity, side })` and `MeshBasicMaterial({ color, opacity, side })`. A colour is a `Color`, a hex string (`"#a3141b"`), a number (`0xa3141b`), a name (`"red"`) or `{ r, g, b }`; hex colours are sRGB. `side = "double"` draws both faces; an `opacity` below 1 blends.
## Math
`Vector3`, `Color` and `MathUtils` come from the same module as the other nouns and are described in the [math](math.module/README.md) module's README: vector methods and operators, colours from hex, names and HSL, and clamp, lerp, smoothstep and a seeded random.
```luau
MathUtils.setSeed(3)
for i = 1, 12 do
local post = Mesh(CylinderGeometry(0.05, 0.05, 1):round(0.01),
MeshStandardMaterial({ color = Color():setHSL(i / 12, 0.5, 0.5) }), "post" .. i)
post.position:set(i * 0.5, 0.5, MathUtils.randFloatSpread(0.2))
end
```
## Motion
Write a pose as a formula of `Time` (seconds) and the `Expr` functions `sin`, `cos`, `sqrt`, `atan2`, `abs`, `min`, `max`, `mod` and `floor`, with `+ - * / ^`:
```luau
local angle = Time * 6.28
piston.position.y = 1.74 * Expr.cos(angle) + Expr.sqrt(32 - 3 * Expr.sin(angle) ^ 2)
crank.rotation.z = -angle
```
The formula is stored with the scene and runs on the device each frame; children follow their parent's motion.
## Lighting
```luau
Lighting({ background = "#0c0f12", environment = 1, sun = { color = "#fff1dc", intensity = 1.6, position = { 18, 30, 22 } } })
PostProcessing({ exposure = 0.9, toneMapping = "aces", bloom = { threshold = 1.05, intensity = 0.55 } })
```
A scene setup places a whole lighting composition as one asset. The V8Dyno scene places `studioLighting`, a studio backdrop, a warm key light and a sky light that lights the model from the backdrop:
```luau
asset.resolve("@builtin::systems.quickGeometry.studioLighting", "sceneSetup"):instantiate(nil, { name = "lighting" })
```
## Where it lives
Each build ends by spawning one entity named `model` with a `Generator` on the `ModelGraph` graph in this package. The tree is the Generator's `objects` and `channels` inputs, stored in `scene.json`; the shapes are made by the nodes of the `shape` nodebox and the modifiers by procgen's `geometry.*` nodes. Names that two parts share get a numeric suffix.
# postReference_colorChecker
The 24 patches of the ColorChecker Classic, each its published sRGB value read as linear reflectance.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# 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.
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.
·computeshader · born here
❒asset # hash_starts
Finishes a spatial hash: given each point's bucket and the permutation that
sorts the points by bucket, states for every bucket where its points start and
end in the sorted order. Each bucket finds its two places by binary search over
the sorted keys, so no bucket needs clearing and the answer is a function of the
keys alone. Exact.
Dispatch over the buckets. It reads `keys` (from `hash`), `order` (the sort's
permutation) and the param `points`, and writes `range`, two words a bucket: the
places `range[2k]` .. `range[2k + 1] - 1` hold bucket `k`'s points. `core.spatial`
finishes its index with it, and `hash_count`, `hash_gather`, `hash_nearest`,
`hash_repel` and `hash_hook` read `range`.
# Animated Color
An opaque, back-culled surface whose colour animates over time, driven by `@builtin::shaders.animate_shader`. Starts from a white base colour (`1.0, 1.0, 1.0`) with an `emissive` of `1.0` so the shifting colour reads brightly, at mid roughness (`0.5`) and fully non-metallic (`metallic 0.0`).
## Inputs
- `colors.base_color` — the starting colour the animation modulates.
- `floats.emissive` (`1.0`) — self-illumination strength of the animated colour.
- `floats.roughness` (`0.5`) — matte diffuse spread.
- `floats.metallic` (`0.0`) — dielectric, non-metallic surface.
·computeshader · born here
❒asset # billboard
Camera-facing billboard shader for textured quads — labels, sprites, and 3D
text. All four corners of the quad sit at the same anchor, so the vertex's world
position is the anchor under any entity or parent transform. Each corner carries
its in-plane offset in the vertex colour; the vertex stage offsets the corner in
world space facing whichever camera renders the pass, so the quad is visible and
correctly framed from the main viewport, an offscreen capture, and a
render-texture camera alike. Because the offset is applied in world space before
projection, the quad keeps real extent and stays drawn when the anchor leaves the
frustum. The horizontal axis stays world-level, so it tracks a pitching camera
without rolling.
The world size lives in the per-corner offset (resizing rebuilds the vertex
colours), so there are no size material properties, and the mesh declares its own
render bounds so frustum culling keeps it. The fragment mirrors `unlit`:
`base_color * base_color_texture` with masked-transparency cutoff.
# backdrop_sky
The sky material of the `example_own_shaders` example: `backdrop_sky.shader`
at its own default values. A sky-domain shader draws on the sky behind
everything, so its `preview.png`, rendered on the preview studio's sphere,
shows a flat colour; the look it gives is the sky the material backdrop draws.
# foliage.shader
Vegetation that sways with the scene's wind.
The motion comes from the engine's frame-global wind (`rendering.setWind`), so
every material reading it agrees on direction, speed and gust phase — a gust
crosses a whole field instead of each plant animating on its own clock.
`compliance` scales how far this material yields — 1 for a grass blade, 0.1 for
a trunk. The mesh's red vertex channel is how freely each vertex moves: 1 at a
blade's tip, 0 at its root, so a blade pivots from its base. A mesh with no
authored vertex colours reads white and sways as a whole.
The gust phase is a function of world position, so a gust travels across a field
rather than every instance of the same mesh swaying in unison.
With no wind set the sway is zero and the surface renders as a plain lit
material.
·computeshader · born here
❒asset # intersect_cuts
The segment each entry of `intersect_pairs` is cut along, one thread per entry. The thread reads the entry's
`a`, `b` and part and writes the part's two endpoints (`intersect_core` states the parts). An endpoint record
is 8 words: the position as f32 bits, the kind word (the kind in the low byte, which meshes the segment cuts
in bits 8 and 9), then `lo`, `hi`, `tri` and `extra`, which name the crossing; two endpoints, 16 words, an
entry. The endpoint slot `s = 2 * entry + e` names an endpoint to `intersect_unify` and `intersect_retri`.
A point on a shared edge writes the same record as both endpoints. Exact.
It binds `apts`, `atri`, `bpts`, `btri` and `pairs` and writes `cut`. Over a live count (`COUNT=device`, see the
abi README) an entry past the live ones is not read or written. `geometry.boolean` runs it.
·computeshader · born here
❒asset # intersect_unify
The first slot of every cut point. Endpoint slots whose records name the same crossing (the kind word, `lo`,
`hi`, `tri` and `extra`) are one point; `rep[s]` is the lowest slot among them, which is the point's
identity. A slot with `rep[s] == s` is a new point's first slot, so a compaction of those slots
numbers the cut points, and every endpoint reference maps through `rep`.
Three dispatches (`STAGE claim`, `fold`, `resolve`) over a hash table `table` of `cells` words (a power of two,
at least twice the slot count) and a second table `lowest` of the same size, both zero before the first stage.
`table`, `lowest` and `rep` (one word a slot) carry from stage to stage: each stage is bound the three the stage
before it wrote, so `fold` reads the claims and `resolve` the cells `fold` recorded in `rep`. Exact: the cell a key
takes depends on thread timing, the answer does not.
Over a live count (`COUNT=device`, see the abi README) a slot past the live ones is not read or written.
`geometry.boolean` numbers its cut points with it.
·computeshader · born here
❒asset # ray
Casts rays and segments against the triangles of a geometry through the
hierarchy the `bvh` kernel builds (closest hit, or any hit for occlusion), and
computes the generalized winding number of the geometry about each origin, which
is the inside test a boolean or a distance field needs. A hit is the parametric
t, the primitive index and the barycentric weights. The header of
`bindings.yaml` states the ray and hit layouts: a ray is 8 words of `rays`
(origin xyz, tmin, direction xyz, tmax); a miss writes t = -1 and `hit_prim`
0xffffffff. Exact: the same rays give the same hits, ties going to the lower
index.
`ray` binds `rays`, the geometry's `pts` (xyz a point), `vpt`, `vstart` and
`vcount`, and the `accel` node table the `bvh` kernel builds, with the `np` param
the number of primitives; the `STAGE` specialization picks `closest`, `any` or
`winding`. The winding stage sums over every primitive and reads only the origin
of each ray. `geometry.boolean` and `geometry.to_sdf` run the `winding`
stage for their inside test, and `sim.particles` runs `ray_shapes` for its
collisions.
`ray` is a family of three kernels, since one dispatch binds at most 8 storage
buffers a stage:
| Kernel | Answers |
|---|---|
| `ray` | `hit` (t, u, v, fan) and `hit_prim` (the primitive, the shape index of a mesh hit) for the `closest`, `any` and `winding` stages |
| `ray_surface` | for the `closest` hits `ray` found: `hit_normal` (unit triangle normal facing the ray's origin side) and `hit_end` (the hit point pushed out along the normal by the `skin` param; a miss answers the ray's end) |
| `ray_shapes` | the analytic shape table, bound as a `columns` binding (`shapeKind, center, extent, rotation, bounce, friction, index`; a plane's extent is its unit normal, a sphere's extent.x its radius): `hit`, `hit_prim` (the row of the shape table), `hit_normal`, `hit_end` |
Chain for a mesh: dispatch `ray` with `STAGE = closest`, then `ray_surface` with
the same `rays`, geometry bindings and the `hit` and `hit_prim` that `ray`
wrote.
# `lut` post-process shader
Colour grading through a lookup table. `pp.add(name, "lut", { texture = ... })`
registers it; `@builtin::modules.lut` builds, imports and installs the tables it
reads.
`lut_texture` is a LUT **strip**: an N-entry colour cube laid out as one row of N
square tiles, so the image measures `N*N` wide by `N` tall. Tile `b` holds the
plane of constant blue index, red runs across a tile and green runs down it. N
comes from the texture's own height, so this one shader serves a 16-, 32- or
64-entry cube.
The eight lattice entries around a colour are fetched with `textureLoad` at exact
texel coordinates and interpolated in the shader. That makes the result
independent of the texture's filter and wrap mode, and each blue plane is read
from its own tile.
A texture whose shape is not a strip — including the 1×1 fallback bound when the
effect has no table — returns the frame untouched, so adding the effect before
its table exists changes nothing.
| Property | Meaning |
|---|---|
| `amount` | 0 = the ungraded frame, 1 = the table's answer. |
| `lut_texture` | The strip. |
# luminance_grade
A post-process shader. It takes each pixel's luminance, subtracts
`black_point`, raises the result to `contrast`, adds a grain of strength
`grain` (offset by `seed`), darkens toward the corners by `vignette`, and
returns that single value multiplied by `tint`.
# Error Text
A 3D "ERROR" text model used as the visible fallback when an asset fails to
load — spawned in place of missing geometry so a broken reference is obvious
in-scene instead of silently invisible. Decomposed from `ERRORText.fbx` into
this bundle (mesh + material + texture + entity template).
## Composition
- Root `error_text` → `Sketchfab_model` → the `ERRORText.fbx` node hierarchy.
- Carries the extruded "ERROR" letter mesh, its material, and texture as
private subassets.
## Usage
Spawned automatically by the engine as the placeholder for an unresolved
asset; can also be spawned directly to test the fallback path.
# Plastic White
A clean white plastic — a non-metallic PBR surface with a pure white base colour (`1.0, 1.0, 1.0`) and mid roughness (`0.5`) for a soft dielectric sheen. Built on `@builtin::shaders.pbr`. Opaque, back-face culled, queue `2000`.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the white plastic tint.
- `floats.roughness` (`0.5`) — soft, semi-glossy highlight.
- `floats.metallic` (`0.0`) — dielectric (non-metal) response.
- `floats.emissive` (`0.0`) — no self-illumination.
# contactShadows system
Short screen-space shadow traces that supply the small-scale contact a shadow
map cannot resolve.
A shadow map has a texel size. Contact finer than that texel — a chair leg on a
floor, a prop on a table, fingers on a desk — falls between texels and is simply
not there, which is why small objects read as hovering slightly above the
surface they are resting on. No amount of shadow resolution fixes it, because
the missing detail is below the sampling scale.
This traces a short ray through the depth buffer from each shaded pixel toward
the light and darkens the pixel when the ray passes behind visible geometry. It
adds the contact term; the shadow map keeps doing everything else.
## Using it
```lua
local id = entity.spawn("contact_shadows").id
entity(id).component.add("ContactShadows", {
strength = 0.9, -- how dark a fully occluded contact goes, 0..1
length = 0.35, -- trace length in WORLD units
steps = 16, -- samples along the trace
})
```
Every field is live. Setting `strength` to 0 turns it off without losing the
rest. For runtime control (a quality slider, a cutscene) drive the module:
```lua
local contactShadows = require("@builtin::systems.contactShadows.contactShadows")
contactShadows.set({ strength = 0.9, length = 0.35 })
contactShadows.get()
contactShadows.active()
contactShadows.lights() -- the lights this frame's traces aim at
contactShadows.drawn() -- the newest frame the passes drew, and the lights they traced
contactShadows.clear()
```
## What the knobs do
| field | effect |
|---|---|
| `strength` | How dark a fully occluded contact goes, in [0, 1]. 0 turns it off and releases the pass. |
| `length` | Trace length in **world** units. This is the scale of contact supplied, so it scales with the scene rather than the screen. |
| `steps` | Samples along the trace. More resolves finer occluders, at linear cost. |
| `bias` | Normal offset before the march starts, so a surface does not read as its own occluder. |
| `thickness` | World-space thickness assumed for an occluder. Past it the ray has emerged out the far side and stops counting. |
| `localLights` | Whether the scene's point, spot and distant lights supply contact of their own alongside the sun. |
| `maxTracedLights` | How many of them a single pixel may trace toward — the heaviest contributors at that pixel. Each one costs that pixel another march, so this is the per-pixel ceiling. |
`lightDirection` tracks the scene's sun on its own, re-read every frame. Pin it
through `contactShadows.set` when a scene wants the sun's trace aimed
elsewhere; a later `set` that names no direction goes back to tracking the sun.
## Lights
A lamp on a desk grounds the props under it the same way the sun does, and the
same shadow-map texel that loses the sun's contact loses its. So with
`localLights` the point, spot and distant lights supply contact too, each
traced toward and each weighted by the share of the pixel's light it put there
— its intensity and colour luminance against the same distance attenuation and
cone the renderer shades it with. A pixel darkens by the share of its light the
traces found blocked, which is what keeps a lamp's contact out of the regions
that lamp does not reach.
A local light's ray also stops at the light itself rather than running the full
`length`: geometry past a lamp stands between nothing.
The pool holds point, spot and distant lights. An area light shades from a
surface rather than a point, and the trace takes a single direction per light,
so contact under one comes from the sun and whatever punctual lights share the
scene with it.
The module selects the pool once a frame — every distant light, then the local
lights whose sphere of influence touches the view, ranked by what each is worth
at the camera — and that rank is what a scene holding more lights than the pool
has rows spends them on. `contactShadows.lights()` reads back exactly what it
selected. The view it selects against is the main camera's, so an offscreen
camera looking somewhere else traces toward the lights the main view holds.
At each pixel the pass then weighs the whole pool — intensity and colour
luminance against that pixel's own N·L, distance attenuation and cone — and
marches toward the `maxTracedLights` heaviest. So a lamp across the room that
ranked into the pool does not spend the budget of a pixel the lamp beside it is
lighting.
## How it renders
`contactShadows.renderFeature` runs the sun's trace at the depth seam, before
anything shades, and the local lights' traces after lighting.
The sun's march (`contact_shadows_sun`) starts at each surface, its normal read
off this frame's depth, and steps toward the sun. Each sample along the ray is
projected back to the screen and compared, in world space, against what the
depth buffer holds there: the ray is blocked while it is behind visible
geometry and still within `thickness` of it. The march is jittered per pixel
so the step pattern lands as noise rather than visible stair-stepping, and a
surface facing away from the sun takes nothing: it is already unlit by it. The
pass writes `strength` times how blocked the ray is, `contact_sun_blur` smooths
it along the depth, and a fragment pass composes it into the scene's sun
occlusion channel (`@scene.sunOcclusion`) with the `union` blend
(`src + dst - src * dst`). The sun's term is the only one that reads that
channel, so the sun's contact darkens the sun's light and nothing else: the
sky, the probes, an emissive surface and the other lights keep theirs, and a
participating medium's shadow written into the same channel composes with it.
With `localLights`, the local march (`contact_shadows`) reads the deferred
G-buffer's normal, so it needs the deferred path (the default). Its blur
composites the result over the shaded colour scaled by how lit the pixel
already is (`@scene.material` against the shaded colour), so a region the
shadow map has already darkened takes little further darkening and the two
shadow sources do not stack.
The forward view-projection needed to project a sample back to the screen is
the one the frame provides, rather than one passed in from script, so an
offscreen capture or an RTT camera projects through its own matrix.
## Files
```
contactShadows.package/
ContactShadows.component/ -- the scene's contact shadows, authored and persisted
contactShadows.module/ -- .set / .get / .clear / .active / .lights / .drawn / .refresh
contactShadows.renderFeature/ -- the passes, and the settings they read
contact_shadows_sun.computeShader/ -- the sun's trace, at the depth seam
contact_sun_blur.computeShader/ -- the sun's share, smoothed
contact_shadows.computeShader/ -- the local lights' trace
contact_shadows_blur.computeShader/ -- the local lights' composite
```
## At lower quality levels
The settings that carry its cost scale with the device's quality level (`Field.scaled`): the values a setup authors are the high look, and `renderer.feature.resolved(handle)` states what each level draws. The `graphics-quality` guide lists the rules.
·computeshader · born here
❒asset # edges
The sides of a mesh as point pairs: the first stage of the edge table. It reads
`pt` (the point each vertex reads), and each primitive's `vstart` and `vcount`.
One invocation per primitive writes, for every vertex slot of its run, the side
leaving that vertex as `lo`, `hi` (its lower and higher point), `face` (the owning
primitive) and `rev` (1 when the side runs from the higher point to the lower).
The outputs hold `nv` slots, a bind of the vertex count. A slot with no side (the
last vertex of an open run, a side joining a point to itself, a primitive with
fewer than two vertices) holds `ZERO_NONE` (the largest i32) in `lo` and `hi`
and -1 in `face`, so a sort puts it last. Integers are 32-bit words, exact.
The edge table is this kernel, a stable sort of the slots by `hi` and then by
`lo`, and the `edges_runs` kernel (run heads, then the table). The sort and
the compaction between are the `sort` and `compact` kernels; `edges_runs` states the
whole sequence, and the `core.edges` node runs it. `closed_all` is 1 for a mesh of
faces, which wrap; with 0 the `closed` column decides per primitive, for curves.
`np` is the number of primitives in the plain variant. Over a live count
(`COUNT=device`, see the abi README) the live primitives are read from
`domain_count` and the dispatch covers their capacity; that variant wraps every
primitive and binds no `closed`, which keeps it at 8 storage buffers (8 in the
plain variant).
# postReference_darkRamp
A ramp of light from 0 at the left edge to 0.1 at the right: the dark gradient an undithered 8-bit display path bands on.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# pbr
The engine's standard physically-based material — the full glTF metallic-roughness
workflow lit by the shared `@builtin::shaderModules.pbr_shading` model. This is the default surface shader a
model uses when its material doesn't specify another, and it is also registered
under the legacy alias **`standard`** (the name many materials reference).
It is a `surface()` shader: it fills a `PbrSurface` and the engine generates every
pipeline entry point and lights it. Every parameter defaults to a neutral value, so
a material that sets nothing renders as a clean dielectric; the advanced lobes only
cost anything when a material opts into them.
## Properties
| Property | Type | Default | Meaning |
|---|---|---|---|
| `base_color` | color | `[1,1,1,1]` | Albedo tint, multiplied by `base_color_texture` and vertex colour. |
| `emissive` | color | `[0,0,0,1]` | Emissive tint, multiplied by `emissive_texture` and `emissive_intensity`. |
| `emissive_intensity` | float | `1.0` | HDR multiplier on the emissive output. |
| `roughness` | range | `0.5` | Perceptual roughness, multiplied by the green channel of `roughness_metallic_texture`. |
| `metallic` | range | `0.0` | Metalness, multiplied by the blue channel of `roughness_metallic_texture`. |
| `reflectance` | range | `0.5` | Dielectric reflectance knob (neutral 0.5 → 4% F0). |
| `ior` | float | `1.5` | Index of refraction → dielectric F0 and the refraction direction. |
| `normal_scale` | float | `1.0` | Strength of the tangent-space `normal_texture`. |
| `occlusion_strength` | range | `1.0` | Blend of the `occlusion_texture` (R) into the ambient term. |
| `clearcoat` | range | `0.0` | Strength of a second dielectric clearcoat specular lobe. |
| `clearcoat_roughness` | range | `0.0` | Roughness of the clearcoat lobe. |
| `anisotropy` | float | `0.0` | Anisotropic highlight stretch along the tangent ([-1,1]). |
| `sheen_color` | color | `[0,0,0,1]` | Tint of the sheen lobe — the retroreflective rim of velvet, satin and brushed fabric. Black leaves the base untouched. |
| `sheen_roughness` | range | `0.3` | Width of the sheen lobe. |
| `iridescence` | range | `0.0` | Blend toward the thin-film response, the hue that shifts with view angle. |
| `iridescence_thickness` | float | `400.0` | Film thickness in nanometres — which wavelengths cancel and which reinforce. |
| `iridescence_ior` | float | `1.3` | Index of refraction of the film. |
| `subsurface_color` | color | `[0,0,0,1]` | Tint of the light that entered the surface, scattered beneath it and left again. Black leaves the base untouched. |
| `subsurface_radius` | float | `0.5` | How far the diffuse falloff wraps past the terminator, taken per channel against `subsurface_color`. |
| `fibre_color` | color | `[0,0,0,1]` | Tint of the second of the two highlights a hair or fur strand gives. Black leaves the base untouched. |
| `fibre_specular` | range | `0.35` | Strength of the first strand highlight, in the light's own colour. |
| `fibre_shift` | float | `0.06` | How far apart the two strand highlights sit along the fibre. |
| `fibre_roughness` | range | `0.1` | Width of the first strand highlight. |
| `transmission` | range | `0.0` | Specular transmission — refracts the environment through the surface. |
| `thickness` | float | `0.0` | Volume thickness for Beer–Lambert transmission absorption. |
| `attenuation_color` | color | `[1,1,1,1]` | Transmission absorption tint. |
| `attenuation_distance` | float | large | Beer–Lambert absorption distance. |
| `uv_scale` | float2 | `[1,1]` | UV tiling applied before every texture sample. |
| `uv_offset` | float2 | `[0,0]` | UV offset applied before every texture sample. |
| `alpha_cutoff` | range | `0.0` | Mask threshold — fragments with `alpha <` this are discarded (0 = no cutoff). |
| `double_sided` | bool | `false` | Flip the shading normal on back faces. |
| `receives_fog` | bool | `true` | Whether the screen-space fog passes (height fog, aerial perspective) reach this surface. `false` leaves an opaque deferred draw at the colour it shaded to, however deep in the medium it stands — see below. |
| `instance_color_lane` | float | `-1` | Which of the instance's four shader-data lanes colours it (rgb colour, a coverage). `-1` reads none. See below. |
| `instance_emission` | float | `0` | How brightly the lane colour glows where it covers. |
| `parallax_depth_scale` | float | `0.0` | Depth of the relief `height_texture` describes, in UV units: the furthest the parallax march moves a UV. 0 draws the flat face. See below. |
| `max_parallax_layer_count` | float | `32` | The parallax march's steps at a grazing view; straight down takes 40% of them, the self-shadow half. |
| `parallax_fade_start` | float | `20` | World distance from the camera at which the relief starts to flatten. |
| `parallax_fade_end` | float | `40` | World distance past which the relief is flat and no march runs. |
| `height_map_is_depth` | bool | `false` | Which way `height_texture` runs: `false` reads R as height, white highest; `true` reads it as depth, white deepest. |
### Emissive authoring
The glow output is `emissive × emissive_intensity` (× the `emissive_texture`). The glow
**colour** is `emissive`, a vec; the **intensity** over it is `emissive_intensity`, a
scalar. So `{ emissive = {0.1, 0.9, 1, 1}, emissive_intensity = 5 }` is a cyan glow at 5×,
and it is these two names that `getProperties()` lists and `setProperty` writes.
A spelling another engine's convention uses for the same role — `emissive_color`,
`emission`, `emissive_tint` — is resolved onto `emissive` when the material is authored,
so content carried in from glTF, Unity or Godot reaches the property under the name this
shader declares. Where two such spellings meet on one of the two names, the shape of each
value says which of them it is: a vec is the colour and a number is the intensity, so
`{ emissive_color = {0.2, 0.8, 1, 1}, emissive = 5 }` is the same cyan glow at 5x. Two
values of one shape are one property's, and the one written under the name the shader
declares applies while the other is named in a warning.
A bare positive scalar `emissive` with no colour beside it is the "turn emission on"
shorthand and means a white glow at that intensity, so `emissive = 20` on a white material
lights up.
### Parallax occlusion
A material that binds a `height_texture` (the relief's height map, R channel)
and sets `parallax_depth_scale` above 0 draws the relief that height map
describes on the flat face. The map is read as **height, white highest** (the
stones white, the mortar black); a map authored as **depth, white deepest**
is read by setting `height_map_is_depth = true`, with no need to invert the
image. A relief that reads inside out (cobbles sunk below their gaps, carving
standing proud) is a map read the wrong way round: flip `height_map_is_depth`.
The module and `pbr_parallax_occlusion` state the same switch under the same
name. The view
is marched into it, every map is read where the view met the relief (through
the derivatives of the face's own UV, so the relief's edges pick no coarser
mip and the picture holds still under temporal anti-aliasing), and the relief
takes its own share of the sun, marched only on the fragments the sun lights.
The relief flattens with distance between `parallax_fade_start` and
`parallax_fade_end`, and toward a grazing view, so the silhouette of a curved
mesh keeps its shape. A UV that tiles (`uv_scale`) keeps every tile. The depth
the surface writes and the shadow it casts are those of the flat face.
The code is the `PBR_PARALLAX` feature, in a material's program only where
`parallax_depth_scale` stands above 0. A shader of your own gets the same
relief from `@builtin::shaderModules.parallax`, which this feature calls.
`guides { path = "topics/rendering-geometry" }` has the rendering guide's
section on relief.
```lua
asset.create("material", "cobbles", {
shader = "@builtin::shaders.pbr",
base_color_texture = { __ref = colour.guid, type = "texture" },
height_texture = { __ref = height.guid, type = "texture" }, -- white highest
parallax_depth_scale = 0.05,
uv_scale = { 6, 6 },
})
```
### The lobes over the base layer
Beyond metallic-roughness, the shading model carries six layers this material
declares. Each is gated on its own neutral value, so a material that sets none of
them shades as a plain dielectric and each one costs only where it is asked for.
| Layer | Turned on by | What it looks like |
|---|---|---|
| Clearcoat | `clearcoat > 0` | A second dielectric specular lobe on top — car paint, lacquer, a varnished surface. |
| Anisotropy | `anisotropy ~= 0` | The highlight stretches along the tangent — brushed metal, a vinyl record. |
| Sheen | `sheen_color` above black | A retroreflective rim that brightens toward grazing angles — velvet, satin, dusty cloth. |
| Iridescence | `iridescence > 0` | The specular hue shifts with view angle — an oil slick, a soap film, anodised metal, a beetle shell. Thickness picks the colours. |
| Subsurface | `subsurface_color` above black | Light wraps past the terminator and glows through thin geometry lit from behind — skin, wax, marble, a leaf. `thickness` gates how much reaches the far side. |
| Fibre | `fibre_color` above black | The two offset highlights a strand gives instead of the one a surface gives — hair, fur. Taken around the world tangent as the fibre axis. |
All six are evaluated inside the engine's own light loop, once for every light
that reaches the surface, so each one is shadowed, attenuated and cone-masked
with the base layer it sits over.
Each layer, and specular transmission beside them, is a shader feature its
gating property switches on (`features:` in `properties.yaml`: `PBR_CLEARCOAT`,
`PBR_ANISOTROPY`, `PBR_SHEEN`, `PBR_IRIDESCENCE`, `PBR_SUBSURFACE`, `PBR_FIBRE`,
`PBR_TRANSMISSION`; the per-instance colour below is `PBR_INSTANCE_COLOR`). A material that sets the property away from its neutral
value draws a program holding that layer; one that leaves every layer at rest
draws a program holding none of them, so the default material pays only for the
metallic-roughness model it shades as. Setting a property with
`renderer.material.setProperty` moves the material between the two programs, and
`renderer.shaderVariants()` lists the ones a scene has asked for.
An oil-slicked wet surface is `iridescence = 1`, an `iridescence_thickness`
around 300-500 nm and a low `roughness` over a dark `base_color`. Skin is a warm
`subsurface_color` with a `subsurface_radius` near 0.5. Velvet is a `sheen_color`
at the fabric's own hue over a dark base.
### Standing outside the fog
`receives_fog = 0` declares that the screen-space fog passes — `heightFog` and
`aerialPerspective` in `@builtin::systems.atmosphere` — leave this surface at the
colour it shaded to.
The declaration travels to those passes as a per-pixel surface flag written into
the alpha of the G-buffer normal (`@builtin::shaderModules.surface_flags`). Only
the deferred G-buffer fragment entry writes that channel, so the declaration
reaches the fog from an **opaque** draw on the **deferred** path. A draw the
renderer sends through the forward fragment entry — every draw on the forward
path, and the transparent phase on either path — writes no G-buffer channel to
carry it, and its pixels take the fog like any other.
### Per-instance colour
`instance_color_lane` names one of the four shader-data lanes every drawn
instance carries (`renderer.instanceData.set` for an entity, the
`instanceDataBuffer` of `renderer.mesh.drawInstanced` for a population). The
lane's `rgb` is this instance's colour and its `a` is how much of it covers the
material's own base colour and emission, 0 none through 1 all, so one material
draws every member of a structure, a crowd or a population in a colour of its
own: a stress map, a heat map, damage tints, team colours, a selection
highlight. A lane never written reads zero and leaves the material's own look.
```luau
local mat = renderer.material.create({ shader = "@builtin::shaders.pbr",
properties = { instance_color_lane = 2, roughness = 0.6 } }, "beams")
beam.component.add("Model", { model = "cube", material = mat }) -- the handle
renderer.instanceData.set(beam, 2, 1, 0.2, 0, 1) -- this beam orange-red
```
The colour replaces the base colour before lighting, so the surface still shades
and the `albedo` capture pass reads the lane colour. `instance_emission` adds
the lane colour as emission where it covers. Lanes 0 and 1 carry a baked
lightmap's rect and layer, so a lit material takes lane 2 or 3. The read is the
`PBR_INSTANCE_COLOR` feature, so a material that leaves `instance_color_lane` at
`-1` draws a program without it. `@builtin::materials.instance_color` is this
material ready made, reading lane 2.
A write is local to the engine that makes it and replicates nothing, which is
what makes it cheap enough to recolour hundreds of members every frame;
`Model.tint` is the synced tint every participant sees.
## Textures (glTF metallic-roughness set)
| Slot | Default | Channels |
|---|---|---|
| `base_color_texture` | white | RGBA albedo (sRGB). |
| `roughness_metallic_texture` | white | G = roughness, B = metallic (glTF packing). |
| `emissive_texture` | white | RGB emissive (sRGB). |
| `normal_texture` | flat-normal | Tangent-space normal map. |
| `occlusion_texture` | white | R = ambient occlusion. |
| `height_texture` | white | R = height of the relief, white highest (white deepest under `height_map_is_depth`). Read by parallax occlusion (`PBR_PARALLAX`, where `parallax_depth_scale` > 0). |
A program samples the maps its material binds and no other. Each slot is a
shader feature switched on by the material binding a texture there
(`PBR_BASE_COLOR_MAP`, `PBR_ROUGHNESS_METALLIC_MAP`, `PBR_NORMAL_MAP`,
`PBR_EMISSIVE_MAP`, `PBR_OCCLUSION_MAP`): a slot left unbound, or bound to its own
default (`default:white`, `default:normal`), reads as the value that default
stands for, times the slot's factor, with no texture sample, and an unbound
normal map leaves the geometric normal exactly as it is. A solid-colour material
takes no texture sample at all. A material binding one image as both
`roughness_metallic_texture` and `occlusion_texture` (glTF's packed
occlusion-roughness-metallic image) draws `PBR_OCCLUSION_IN_ROUGHNESS_METALLIC`,
which reads occlusion from the R of the metallic-roughness texel and samples the
image once.
Because the engine holds the full `PbrSurface`, the capture tool's debug passes
(albedo / roughness / metallic / AO / emissive / world-normal / shadow / depth /
motion) all read real material data.