❒
package · drop-in viewer
What it does
No description provided yet.
Interface
What this asset declares: the schema it conforms to, what it exposes, and the rendered structured payload.
This asset doesn't declare a schema or structured payload.
Sub-parts
Everything contained inside this part. Assets are composite children (clickable cards). Files are leaf payloads. Expand any row to view its source.
Showing the 199 items nearest this part. It holds more than this page lists.
199+items
# Generator
A live procedural generator: it binds a `.procGraph`, plays the graph's
timeline and stands each of the graph's outputs in the scene as children of
the entity it is on. Change a param and the output is made again in place; in
edit and in play alike, nothing it makes is written to the world's source.
```lua
local graph = asset.create("procGraph", "crate") -- a box with a `size` input; edit its init.luau
local e = entity.spawn("crate")
e.component.add("Generator", { graph = graph })
e.component.get("Generator").params = { size = 2 }
```
## Fields
| Field | What it does |
|---|---|
| `graph` | The `.procGraph` it plays. |
| `params` | Overrides for the graph's declared inputs, by name. |
| `output` | One declared output to stand; empty, the default, stands every output. A graph of the call form stands what its `io.output` calls show (the ones the named output reaches, when one is named); an output it names that no `io.output` of the graph shows is shown by the Generator itself, under the output's name, the way an `io.output` of it would show it. A graph of the older node form stands each output it declares, one root each. |
| `playOn` | What starts its clock in play mode: `"auto"` (default) plays a timeline with no end as soon as it binds and holds any other on its first frame; `"load"` plays on bind; `"manual"` waits for `play()`. In edit mode a Generator is not set to play, whatever `playOn` says: it shows the frame it is on until it is played. |
| `ending` | `"graph"` (default) does what the timeline declares; `"loop"` plays the range round and round; `"hold"` plays it once and stays on its last frame. |
| `speed` | How fast its clock runs: 1 (default) its own rate, 0 still, negative plays a timeline with an end backwards. |
| `diskCache` | Whether the outputs the graph caches load from, and are written to, the world's disk cache. On by default. |
| `bakedSnapshot` | The bundle an earlier engine stored with the scene for what the generator realized. In play it stands in place of cooking while the disk cache does not hold every output; the first commit that writes the disk cache for all of them clears it. Empty by default. |
| `cookBudgetMs` | Milliseconds of cook work a frame before a cook yields to the next frame. Unset by default: a cook then spends the part of each frame the frame's other work leaves. |
## Methods
`play()`, `pause()`, `seek(seconds)`, `seekFrame(frame)`, `loop()`, `hold()`,
`setFps(fps)`, `setRange(first, last)` and `setWallTime(on)` drive its clock,
on every peer. `getFrame()`, `getTime()`, `describeGraph()` and `playback()`
read it; `playback()` also says what running the graph costs and how each
output is drawn: `cost.cooks` counts the cooks it presented and `cost.cookMs`
the CPU milliseconds they ran, the frames they waited out apart, for a graph of
the call form as for one of the node form. `describeGraph()` describes the graph
bound, of either form. `cancelCook()` stops a cook in flight and leaves the last
output standing. `apply()` swaps the generator for the asset it makes: the
frame being presented becomes a bundle, and an `Asset` component standing it
takes the Generator's place; for a graph of the call form, the bundle holds what
its `io.output` calls show, each under the name it was shown under. The
`onFinished` event fires when a range played once reaches its end.
A timeline that runs in real time (`realTime = true`) has an end when its graph
states `frames` beside it (`g:timeline({ realTime = true, fps = 60, frames = 180 })`)
or when `setRange` gives it one; with neither it runs on and never finishes.
When the playhead of one with an end reaches its last frame, `ending` applies as
it does to any timeline: `"graph"` loops where the graph declares `loop` and
otherwise holds on the last frame and fires `onFinished` once; `"loop"` plays it
again from the start, a fresh simulation each time, without firing it; `"hold"`
stays on the last frame. `play()` plays a held one again from its start.
`playback().ends` is whether the timeline has an end, and `last` is its last
frame. A real-time timeline begins again, by `seek(0)`, a loop or `play()`, in
the runs its solvers hold on the device: a restart costs a rewrite like any
other present, and opens no cook.
## What it cooks again
A Generator cooks again, in edit mode and in play alike, when its graph's source is
edited, when its `graph`, `params`, `output` or `diskCache` change, and when anything
its graph was built from changes: a node the graph reaches (edited, or no longer
loading), a module the graph or one of those nodes requires while it builds, or a file
their builds read (`vfs.read` in a node or graph source, `proc.read` in a module they
call). A Generator that does not reach the change cooks nothing for it. Every node of
one cook is built from one version of each module and file.
A graph that does not build (its source, or a node it calls, raises while it is built)
leaves what the Generator stands standing: `playback().error` says why, the cook
history holds a cook of target `source` closed `failed` with the error, and once what
it failed on is fixed the Generator cooks again on its own.
## What it draws
An output drawn as instances (`drawn[output].as == "instances"`) is copies of one
mesh per piece, placed by a transform buffer: a forest is a trunk copy and a crown
copy per tree, a scatter one copy per item. A copy is no entity and holds no
collider, so the scene tree shows the Generator alone and `Physics.raycast` passes
through every copy. The renderer answers for them:
```lua
local id = generatorEntity.id
for _, pop in renderer.mesh.listInstanced() do
if pop.parent == id then
print(pop.meshGuid, pop.material, pop.instanceCount) -- one row per piece
end
end
local hit = renderer.raycast(eye, direction, 100) -- meets each copy's triangles
if hit and hit.instancedDraw then
print(hit.entityId, hit.instancedDraw.id, hit.instance) -- the Generator, the draw, which copy
end
```
`renderer.mesh.listInstanced()` lists every instanced draw with its `instanceCount`
and `parent` (the Generator's entity), each record itself the draw handle the
`renderer.mesh.instance*` calls take; `renderer.mesh.instanceWorlds(record)` reads
back where each copy stands. A ray hit's `instancedDraw.id` is the `handle` of the
record it met.
## What `playback()` answers
One table, typed `PlaybackState`. The tables in it keyed by name are maps,
read with `pairs`, never `ipairs`:
```lua
for output, d in pairs(generator:playback().drawn) do
print(output, d.as, d.count) -- "instances" or "entities", and how many
end
```
| Field | What it holds |
|---|---|
| `playing`, `heldByPause`, `held`, `realTime`, `wallTime` | The clock's state: running, held by a pause, held at the end of its range, a real-time timeline, wall time on. |
| `frame`, `time`, `first`, `last`, `frames`, `fps`, `loop`, `ends` | Where the playhead stands and the range it plays; `ends` is whether the timeline has an end. |
| `cookedThrough` | The last frame cooked ahead; reaching `last` means every frame is cooked. |
| `cooked`, `hits`, `steps`, `restarts`, `replacing` | Node cooks, cache hits, solver steps, solver restarts, and outputs built again whose earlier state still stands. |
| `error`, `cookError` | Why the graph's source does not load, and why its latest cook failed (led by the line of the call that failed, `path:line: g.<call> failed: <why>`), while they do. |
| `drawn` | By output name: `{ as, count, because?, pieces? }`, how the output's elements reach the screen. |
| `cost` | `{ frames, frameMs, cooks, cookMs, devicePresents, deviceMs, memoPresents, framePresents, realizeMs, drainMs, rewriteMs }`: `frameMs + cookMs` over `frames` is the script cost of a frame. |
| `nodes`, `ms` | By node id: how many times each node cooked, and its milliseconds. |
| `placement`, `placementByGraph` | By node id: where its cooks ran (`runs` "device", "cpu", "mixed" or "values"); and per node a graph used as a node stands as, the sums of its inner nodes. |
| `onDevice`, `offDevice`, `cpuNodes` | Whether a new time is presented on the device, what holds it to cooking when it is not, and how many nodes run on the CPU every frame. |
| `heldFrames`, `notHeldFrames` | Whether presents stand on the frames the engine holds, and why not. |
| `diskCache` | By output name: `{ key, frames, static, complete, hits }`, or `{ reason }` where the cache is not used. |
| `call` | For a graph in the call form, the report of its play. |
| `owner` | The name the generator's device runs are held under. |
`playback()` reads what the generator keeps as it runs, so it costs the same
however much its caches hold. `cookError()` answers its `cookError` alone, for
a caller that watches for a failed cook every frame. `heldBreakdown()` walks
everything the generator holds and states the Luau bytes: by field of its state
and of its play, `cacheBytes` for its node caches and `heaviestEntries` for the
largest entries of its play's node cache.
## What stands while it cooks again
What a Generator stands stays standing while it cooks again, and a present
replaces all of it at once: the shows a present makes stand together in the
frame its cook finishes, and what they replace goes in that frame. So no frame
stands nothing, and none stands part of one cook beside part of another. Each
output stands once: a param set it cooked before shows that set's output again,
and params set while a cook runs are cooked by the cook after it. A cook that
fails, or is cancelled, leaves what stood standing.
## Under an effect
An effect's play runs each graph of its entry on a Generator, a child of the
play's entity. `effectRef:play(entry, opts)` and the `Effect` component make
them and drive their clocks together, so a shot, an impact or a cast is a play
of an effect (`guides { path = "systems/effects/documentation/visual-effects" }`). The play's own
`playback()` adds its Generators' costs together.
Every play of one graph with the same params plays the frames the first one
cooked. A Generator of a graph with `playOn = "manual"` cooks every frame of the
timeline while it waits, and `playback().cookedThrough` reaching
`playback().last` says every frame is cooked.
## Related
- `guides { path = "systems/procgen/documentation/procgen" }`: graphs, ops,
timelines, effects and the live generator in full.
- The `procgen` toolbox: `spawn`, `adjust`, `apply`, `cancel`, `generators`,
`cooks`, `frames` and `onPresent` work on generators by entity, and `play`
plays a graph on the preview stage.
▲ 0↑ born
# abi
The ops every procgen node is built from. Each states where it runs in its `runs` field, and none calls another op.
## Ops
| Op | Runs | Does |
|---|---|---|
| `device.kernel` | `gpu` | Runs a `.computeShader` over a domain of elements and returns what it wrote as columns |
| `transfer.upload` | `cpu_to_gpu` | Turns CPU numbers, lists and tables into device columns |
| `transfer.readback` | `gpu_to_cpu` | Turns device columns and live counts into CPU values, a frame or more later |
| `cpu.call` | `cpu` | Calls a Luau function with declared return types and a time ceiling |
| `cpu.read` | `cpu` | A `cpu.call` over state outside the graph, with a digest of what it reads |
| `device.bound` | `gpu` | Answers a count as a live count that states the most it can reach |
| `device.live` | `gpu` | Answers a column carrying a count, so a reader of it takes the live elements only |
| `device.guard` | `gpu` | Holds a cook to a condition the device answers, checked a cook later when a recorded list replays |
## device.kernel
`kernel` (param) is the shader, a reference resolved from a literal where the node is written
(`asset.resolve("<identity>", "computeShader")`; a name is refused); `specialize` (param) gives each of its `specialize`
parameters one of its options. `bind` (input) gives every binding its value and `domain` (input) says how many
elements run. `uniforms` (input) gives the shader's params by name, each a Number or a Bool, and a name the shader does
not declare is refused; `step` (input) gives numbers the shader takes where it declares a param of the same name (`dt`,
`time`, ...) and leaves the others out; `columns` (input) is a table of Columns, or a class of a Geometry, whose
columns every read binding left unbound takes by its own name.
- A buffer binding takes a Column. A binding the shader writes and that is bound to a Column writes a copy, and the
copy comes back under the binding's name.
- A `columns` binding takes a table of Columns, packed on the device into one buffer in the order the binding's
`order` field states (`order: "shapeKind center extent"`; the table must hold exactly those columns), and in
sorted-name order where the binding states none. A kernel that reads its columns by slot number states `order`;
one that reads them by `NAME_col_<column>` needs none.
- `specialize` takes the table `fieldc.walkSpec(step, opts).specialize` states as it stands (the walk kernel's
`WALK_STEP`, `WALK_STEP_HI`, `WALK_DONE` and `WALK_PRELUDE`), and the resources the spec runs over come from
`fieldc.bindSpec(spec)`: its `cols` (a table of columns already packed on the device) binds to the kernel's `columns`
binding and its `u` (the numbers the chain carries, a device buffer) to its read `buffer` binding. The caller that made
them lets them go (`bound.release()`) once the kernel's outputs are no longer read.
- A Field bound to a binding is evaluated by the field compiler (`fieldc.evaluate`) in one fused dispatch over the
domain, and the column it lands in stands as long as the outputs of the kernel do. A Field that reads the clock
moves: the kernel then follows it with a registration of its own that lists the runs it reads that move as its
`deps`. At each present those runs are brought to the time first, and the kernel's casts, copies, counter resets and
dispatch are queued again over the same runs into the same output columns, recorded once and replayed. The outputs and
their counters are live, so a reader of a compaction's `indices` and `indices_count` reads them at that time.
- `bind.columns` is a domain (a record of Columns, or a class of a Geometry): every read binding the bind left
unnamed takes the column of the same name, and an unbound `columns` binding takes every column of it.
- An appended output bound to a column that an append returned writes a copy of it, and the copy keeps the live
count that column carries, so a later pass appends after what an earlier one appended.
- A param takes a Number or a Bool (1 or 0). A Vec spreads over `<param>_x` to `<param>_w`. `count`, `time` and
`frame` are names any node may give; a kernel that declares none of them leaves them out.
- A Texture binds its `texels` column, and sets `<name>_width` and `<name>_height` where the shader declares them.
- `domain` is a Number, a Column (its elements), or a live count: a count Column, an appended output, or the record
`{ count = <one-word Column>, capacity = <Number> }`. A live count dispatches over its capacity, and the shader reads
the count through a `buffer` binding named `domain_count`. A shader that declares `domain_count` over a plain number
gets the number in it. The live-count form is stated in "Over a live count" below.
- An output with `count` or `capacity` is allocated before the dispatch. An appended output comes back as a Column
(its `_capacity` and `_liveCount` set) and as `<name>_count`.
Output: `columns`, a Record holding every binding the shader wrote as a Column by binding name, and for an appended
output `<name>_count`, its live count.
Column elements are 32-bit words: an `Int` column holds `i32`, a `UInt` column `u32`, every other type `f32`
(`column:element()`). A kernel's `i32` and `u32` outputs are `Int` and `UInt` columns. The first run of a kernel
waits for its program to be built, so a readback asked for after the run sees what the dispatch wrote.
A column whose words are not the ones a binding reads is cast by value before the dispatch: a Float column meeting an
`i32` or `u32` binding (and an Int or UInt column meeting an `f32` one) is read as the numbers it holds, not as the bits
of its words. The cast covers read bindings and in-place bindings; what a kernel writes back through an in-place binding
is the column of the binding's type (`Int` for `i32`).
## Over a live count
A kernel runs over a plain number of elements (every slot live) or over a capacity whose live count sits in a
one-word device buffer. A node that deletes, welds, expands or pairs elements states the count it made on the device,
and the next kernel takes it as its domain, so the count never crosses to the CPU between them.
**What a node passes.** `domain` is the count and the capacity it is bounded by: `found.indices.count` (the count of an
appended output, whose capacity the output carries), an appended output Column itself, or the record
`{ count = <one-word Column>, capacity = <Number> }` for any other count held on the device (a scan's `total`, a
count made by `proc.device.count`; its words are read as u32). A Number is the plain form, as before.
**What a kernel declares.** In `bindings.yaml`, a count binding that exists only in the variant that reads a count, and
the specialization that picks the variant:
```yaml
bindings:
- { name: domain_count, kind: buffer, access: read, element: u32, when: "COUNT=device" }
specialize:
- { name: COUNT, options: [plain, device] }
```
`device.kernel` runs the `COUNT=device` variant when the domain is a live count, and the `plain` variant (the bindings
and the code the kernel always had) when it is a Number. A kernel that declares `domain_count` without `when` reads it
in every variant, and gets the number in it over a plain domain. A condition that names several options of the
specialization (`when: "COUNT=device|live"`, as `kernels/map` states) binds the count in the variant of each: over a
live count `device.kernel` runs the variant of the first option unless the caller names another, and over a Number it
binds the count only when the caller names one of them.
A count that is arithmetic over live counts (`geometry.point.count * 8`, `min(kept.count, room)`) is a domain too when
the arithmetic only grows with the counts it reads: the dispatch covers the most it can reach and the kernel reads the
count the arithmetic comes to, evaluated on the device. Arithmetic that takes a count away from something is read
back where the dispatch needs the number.
**An output sized by a live count.** An output whose `count` states a name that is no param (`count: "nv"`) takes its
size from the `bind` of that name. Bound to a number, the output holds that many elements. Bound to `{ live = <count> }`,
where the count is a count Column that carries its capacity or arithmetic over counts that only grows with them, the
output is allocated for the capacity and carries the count as its live count, with nothing read back.
**What the shader does.** The dispatch covers the capacity (`zero_n()`), outputs sized by `n` hold the capacity, and
the live count is `min(domain_count_get(0u), zero_n())`. The code that reads it sits in `// @when COUNT device` ...
`// @end` blocks (`compute_abi` removes a block from the variants it does not name). A slot at or past the live count
reads nothing and writes the inert value of each output it owns:
| Kernel | Inert value of a slot past the live count |
|---|---|
| `gather` | `dst` is zeros |
| `compact` | `inverse` is -1; `indices` is -1 past the kept ones |
| `scan` | `dst` is the total of the last group (0 for an empty run) |
| `jump` (rank, min) | `parent_out` is the slot itself, `value_out` is 0 |
| `loops` | stage clear writes every slot of the dispatch; stage link: `next` is the slot itself, `head` is 0 |
| `loops_cut` | `head` is 0, `cut` is the slot itself |
| `loops_place` | `ring` is -1, `pos` is 0 |
| `edges_runs` | `flag` is 0; `a` and `b` are -1, `fcount` is 0 |
| `expand` | `owner` and `local_index` are -1 past the sum of the counts |
| `hash_gather` | `items` past the count are left as allocated (0) |
| `hash_hook` | a slot past the live count reads and writes nothing |
| `scatter` (fold pass) | an index past the live count reaches no place |
| `reduce` | the last segment ends at the live count; a segment past `segment_count` is not written |
| `scan` (`SEGMENTS=device`) | a segment past `segment_count` is not scanned or written |
| `expand` (`ELEMENTS=device`) | `counts` and `offsets` hold `element_count` live elements, whatever the dispatch covers |
| `intersect_pairs` | a triangle of A past the live ones has no entries |
| `intersect_cuts`, `intersect_unify` | a slot past the live ones is not read or written |
| `intersect_retri` | a triangle past the live ones becomes no triangle |
**A new count.** A kernel that makes a count writes it to an appended output's counter, which the op returns as
`<output>_count` and as the live count of the output (`output.count`); it carries its capacity and is a domain as it is.
`compact` writes the kept count, `expand` the sum of the counts, `hash_gather` the number of points listed, and
`scan` states its total in `total` (an `i32` scan's total is a count: `{ count = scanned.total, capacity = ... }`).
**Capacity.** When the node does not know a count it allocates for the bound it can state, and the kernel never writes
past it. `compact`, `gather`, `scan`, `jump`, `loops*` and `edges_runs` write at most as many slots as the capacity
they run over. `expand` holds at most `n` slots (`n * k` when no count exceeds `k`). `hash_gather` holds at most its
`total` param, which is the bound the node states (a pair list has no smaller bound than points times queries). In
those two the count buffer states the true count whatever the capacity: a count above `.capacity` is an overflow, the
first `capacity` slots are written and the count minus the capacity is how many did not fit. A node that states a
bound checks `count <= capacity`.
**Storage buffers.** A stage binds at most 8 on the web. A `COUNT=device` variant binds one more than the plain one,
and the table counts the variants that exist:
| Kernel | plain | device |
|---|---|---|
| `gather` | 3 | 4 |
| `compact` | 4 | 5 |
| `scan` | 4 | 5 |
| `jump` | 7 | 8 |
| `loops`, `loops_cut`, `loops_place` | 6 | 7 |
| `edges_runs` | 8 | 5 (heads), 8 (table) |
| `expand` | 5 | 6 |
| `hash_gather` | 6 | 8 |
| `hash_hook` | 6 (hook, `MATCH=normal`), 1 (find) | 7, 2 |
`edges_runs` binds the buffers of its own stage in the device variant (`when: "COUNT=plain; COUNT=device STAGE=table"`),
which is how it stays at 8. `abi.directLimit` counts every `buffer` binding the schema declares, `domain_count`
included, and given the options of a variant it counts the bindings those options leave in (`device.kernel` gives it the
options its caller names), so a kernel with a `columns` binding that adopts the form has one direct column fewer in the
variant that binds the count; none of these eleven has one.
## device.bound, device.live, device.guard
`device.bound { value, capacity?, live? }` answers `value` as a live count: a count Column that carries the most it can
reach, so a kernel runs over it (`domain = count`), a geometry carries it (`class.count = count`) and nothing is read
back. `value` is a one-word Column, arithmetic over counts, or a number. A number is already known and stays the number
unless `live` is true, which writes it to the device as the count, allocated the next power of two at or above it (a
list recorded over it runs again for every number inside that room and is recorded again for a number outside it).
A count held on the device with no `capacity` stated is allocated the room a cook of it measures: twice its count, in
powers of two, and never less than an earlier recording of the same cook allocated. The cook reads the count once. A
recorded list runs the count on the device clamped to that room, and holds a guard: a word that is 1 when the count
outgrew the room. The count a node can bound by what it reads (a triangle count by the vertices, pairs by the pairs
there could be) states `capacity` and holds no guard.
`device.live { values, count }` answers `values` carrying `count` as its live count. A kernel output declared
`live: true` in `bindings.yaml` carries the count its dispatch ran over the same way.
`device.guard { value, flag, why, detail? }` answers `value` once `flag` (a number, a one-word Column or a Field over
one) is 0. A cook that finds it otherwise refuses with `why`, or with what the lazy input `detail` raises. A recording
of the cook holds the word of `flag`, and a replay of it reads that word without waiting for a frame
(`traffic().deferredReads`): the cook that follows finds out whether the replay before it ran past the guard, lets the
recording go and records again. The replay that ran past a guard has handed out its answer by then: a count clamped
to its room, or the result for an input that is no longer a solid. A count that outgrew its room is recorded again with
four times the room (`cookrun.counts().guarded` counts the replays found to have run past a guard).
## transfer.upload
`values` is a Record. A Number becomes a one-element Float column; a list of numbers a Float column; a list of
`{x,y,z}` a Vec column, a list of text (or `{ type = "String", values = {...} }`) a column of the values; `{ type = "Int", values = {...} }` a typed column (`Float`, `Int`, `UInt`, `Vec2`, `Vec3`,
`Vec4`, `Color`); a table of those a table of columns; a Column is held as the device run it has. `columns` (output)
holds the columns under the keys `values` gave them.
## transfer.readback
`columns` is a Record of Columns, live counts, plain values (numbers, booleans and text answer themselves) or tables
of them, a Field (evaluated over the elements of the column it reads, then read; a Field that reads no column has no
length and is refused naming the form to use), or a Geometry or a Part, which answers the copy holding what its columns
held. A live count answers a Number, and a column a read-only list held as the bytes the device wrote
(`proc.substrate.readList`): `list[i]` is a number for a Float, Int or UInt column and a `{x,y,z,w}` made for that
read for a vector column, `#list` is its count and `for i, v in list do` visits its elements, so a list costs the heap
about its bytes however many elements it holds. `readList.bytes(list)` answers the buffer, `readList.get(list, i,
lane)` one number, and `readList.flat` and `readList.toList` plain lists of the range asked for; `ipairs`, `pairs` and
the `table` library read only plain lists, so a list is read with the forms above or turned into a plain one with
`toList`. `values` (output) holds them under the keys `columns` gave them. The op waits across frames, and the play report names it as the point the plan waited. Anything
that waits on a readback value is a planning step.
## cpu.call
`fn` (input) is called with `args` (input), and `values` (output) is what it returned, as a list in order. `returns`
(param) lists the type name of each result (`Number`, `String`, `Bool`, `Function`, `List`, `Column`, `BufferRef`,
`Handle`, or a procgen type) and a call that returns anything else is refused; a Handle in the results is released when
the result is. `ceilingMs` (param) refuses a call that ran longer (5000 when it is 0 or left out), counting the CPU
time the call runs for on the thread that makes it, in every coroutine it resumes, and in every task it starts
(`task.spawn`, `task.defer`, `task.delay`) or component hook it sets off while the call lasts, so a task it starts and
waits for is charged to it and one it leaves running is charged only what it ran before the call returned: the time it
waits on a frame, a program build, a read-back or a task, and the time its thread waits for a core on a busy machine,
are not counted. A device Column reaches the function as a
`BufferRef { buffer, type, count, lanes, element }`, and its data does not move. A Geometry reaches it with its columns
read to the CPU, or, with `device` (param) on, as it stands on the device. `curves` (param)
on hands an animated value among `args` to the function as the curve it is, and the function answers with what follows
it; off, the function gets the value it holds at the cook's time. `pure` (param) on states that the results are a
function of the arguments alone and the call changes nothing: a call whose arguments the plan already knows is made
while the graph is planned, and its results stand in the plan as constants.
## cpu.read
`cpu.read` is `cpu.call` (`fn`, `args`, `returns`, `ceilingMs`, `device`, output `values`) for a function that reads
state the graph does not hold, such as entities in the scene. `digest` (input) is a function called with the same
values that answers a value standing for what `fn` reads; the graph's live digest folds it in, so a Generator cooks the
graph again when that state moves. It takes no `curves` or `pure`.
▲ 0↑ born
# procgen guide
Making things from rules, as graphs of nodes: geometry and meshes, scattering and
terrain, and visual effects — particles, sparks, embers, magic, debris, swarms,
flocks, trails, cracks and lightning — simulated and drawn live every frame,
with your own compute and surface shaders as nodes.
The procgen package's reference guide. Surfaced through
`guides { query: "procgen" }` and `guides { path: "systems/procgen/documentation/procgen" }`
(likewise `man`), and reachable from the `procgen` toolbox via `search_tools procgen`.
The content lives in `guide.md`; this README is the asset summary.
▲ 0↑ born
# Scatter
Strews copies of one shape over the surface of another, each with its own turn, lean and size.
Both the surface and the thing scattered are inputs, so this covers rocks on a hillside, crates on a deck, bushes
along a bank or rubble across a floor: wire it a different `source` and it is a different field.
It makes points on the surface (`points.on_surface`, area-weighted), gives every point its own random yaw, lean and
scale (`instances.randomize_transform`), and places the source on those points (`instances.on_points`). The transform
is read from the same point cloud the instances sit on, so each copy takes the pose of its own point.
## Inputs
| Input | Type | Default | What it does |
|-------|------|---------|--------------|
| `surface` | Geometry | none | What the copies land on. Points are area-weighted, so a bigger face gets proportionally more. |
| `source` | Geometry | none | The shape being copied. |
| `count` | Int | 200 | How many copies. |
| `seed` | Int | 1 | Changes the arrangement. The same seed always gives the same field. |
| `scaleMin` | Float | 0.8 | Smallest per-copy size multiplier. |
| `scaleMax` | Float | 1.4 | Largest per-copy size multiplier. Equal to `scaleMin` means uniform. |
| `tilt` | Float | 8.6 | Degrees of random lean off vertical, 0 to 90. `0` stands every copy upright. |
## Output
`instances`: a population, the points each carrying the source as its `Mesh`, with `orient` and `scale` from the
random transform. A Generator draws it as one hardware-instanced draw call per source; `instances.realize` merges it
into a single Geometry.
## Calling it
The graph is built with `proc.graph("Scatter")`, and its declared inputs are the inputs of a call. Through its asset
ref, `ref:eval("instances", { inputs = { ... } })` evaluates it with inputs given, and in a graph built with
`proc.graph`, `g:node("<id>", ref, inputs, params)` calls it as a node, with `inputs` the wired node ids and `params`
the rest:
```luau
local proc = require("@builtin::systems.procgen.proc")
local ref = asset.resolve("@builtin::systems.procgen.examples.Scatter", "procGraph")
local g = proc.graph("rockyField")
g:node("ground", "mesh.grid")
g:node("rock", "mesh.box")
g:output("instances", g:node("rocks", ref, { surface = "ground", source = "rock" }, { count = 20 }))
local rocks = proc.eval(g, "output:instances")
```
The name `Scatter` that `g:node("<id>", "Scatter", ...)` resolves is the node `examples/ops/Scatter.procNode`, which
declares the same name and holds the same graph.
▲ 0↑ born
# Scatter (node)
A scattering node: its `init.luau` holds the graph that does the work, so the declared inputs are this node's inputs
and the declared output is this node's output. The node is its pipeline, in one self-contained asset.
It makes points on the surface (`points.on_surface`, area-weighted), gives every point its own random yaw, lean and
scale (`instances.randomize_transform`), and places the source on those points (`instances.on_points`). The
transform is read from the same point cloud the instances sit on, so each copy takes the pose of its own point.
A node is findable by what it does: the `procgen` toolbox's `searchNodes` with the query `scatter` lists it as
`Scatter`. Editing this node's `init.luau` cooks again every graph that calls it.
## Inputs
- `surface` (Geometry): what the copies land on.
- `source` (Geometry): the shape being copied.
- `count` (Int, default 200): how many.
- `seed` (Int, default 1): changes the arrangement.
- `scaleMin` / `scaleMax` (Float, defaults 0.8 and 1.4): per-copy size range.
- `tilt` (Float, default 8.6, 0 to 90): degrees of random lean.
## Output
- `instances`: a population, the points each carrying the source as its `Mesh`, with `orient` and `scale`.
## Calling it
The node's graph is built with `proc.graph("Scatter")`, so a graph built the same way calls it by that name or by its
asset, with `inputs` the wired node ids and `params` the rest:
```luau
local proc = require("@builtin::systems.procgen.proc")
local g = proc.graph("rockyField")
g:node("ground", "mesh.grid")
g:node("rock", "mesh.box")
g:output("instances", g:node("rocks", "Scatter", { surface = "ground", source = "rock" }, { count = 20 }))
local rocks = proc.eval(g, "output:instances")
```
`asset.resolve("@builtin::systems.procgen.examples.ops.Scatter", "procNode")` in place of `"Scatter"` names the same
node.
## Authoring a node
A node is a graph returned from a `.procNode`'s `init.luau` (`proc.define`). `asset.create("procNode", name)`
scaffolds that shape, and `procNode.assetType/README.md` describes what a node states and how graphs call it.
▲ 0↑ born
# 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.
▲ 0↑ born
# generator
The parts of the `Generator` component (`@builtin::systems.procgen.Generator`).
The component makes one context table per instance, `gen`, holding its
`public` and `private` surface, and calls this module with it. Each part
installs its state and operations on `gen`:
- `realized`: What a Generator has realized and from which graph: the entities, populations, meshes, materials and volumes it stands, tracked per output, and the retirement that keeps an output's earlier realization standing until its replacement lands.
- `translated`: A Generator's translated outputs: the states they stand as, the bounds it publishes for them, the frames play of a held output, and the clock a translated output is presented at.
- `cook`: Cooking a Generator's graph: the outputs it resolves, the node and frame caches a cook reads and fills, the cook's own state and costs, the world values a graph follows, the pacing of a cook on a worker, the inputs a cook takes, the evaluation of one output, and the per-node placement the `playback` report reads.
- `realize`: Standing a cooked value as a Generator's children: a geometry, grid, bundle, population or asset reference realized under the generator, an output split into the pieces it realizes as, and the folding of outputs into the one bundle `apply` writes.
- `run`: Running a Generator's bound graph: the bound graph and its signatures, its timeline and the clock each frame is cooked at, the cook that runs ahead through the timeline, presenting a cooked frame on the device, and standing a frames play of a held output.
- `diskcache`: A Generator's disk cache and baked snapshot: the outputs a graph declares `diskCache` on, loaded from the world's cache, the writes a commit makes for them, and the snapshot an earlier engine stored with the scene.
- `play`: A Generator's play of its graph (`call`): loading, clocking, presenting, standing and advancing it; binding a graph to the generator (`regenerate`); and standing a baked snapshot in place of cooking.
- `clock`: A Generator's clock, frame by frame: the live sources it polls, the material clocks and live material values it writes, the playhead it presents, the transport its peers share, advancing time, cooking again once the device returns, and the tick each frame runs.
The component requires `stored` itself: a Generator's stored result, the records its cook stood written into the world and stood again from there with procgen not loaded. A Generator whose key has a stored result stands it, and installs the parts above only once it cooks.
▲ 0↑ born
# generator_inspector
The `Generator` component's card on an entity. It replaces the card's generic
`settings` section with one built from the bound graph: the graph it runs, as
an asset picker, and which of its outputs it realizes; then groups — Inputs,
one row per input the graph declares in the control its type takes, each able
to take an expression over the graph's own time; Timeline, the transport,
scrubber, range, frame rate, looping and wall time; Cook, what is cooking, what
cooking has cost and the frame budget — and the Flatten action. The
component's `inspector.luau` returns this module, so the editor's inspector
framework (`edui.inspector.componentSections`) shows it wherever the component
is on an entity. While the clock runs, or the range is still cooking, the card
asks the panel to follow it.
Editing an input row writes the value into the component's `params`, which
regenerates the live output in place. A write the input's type cannot hold is
refused, and the row says why.
`buildFieldSpecs(graph, params)` is the pure row mapping: one spec per declared
graph input, sorted by name, carrying its kind, its current value (the param
override when set, else the declared default), its declared range, the asset
kind a reference input picks from, and whether the value changes over time.
▲ 0↑ born
▲ 0↑ born
# grid
How a compute shader finds the points near a point: the walk over a spatial
hash grid `proc.device.gridInto` builds on the device. `zero_grid_cell`,
`zero_grid_bucket` (from `grid_cell`) and `zero_grid_range`.
The includer binds the grid's runs as three read bindings: `gcfg` (f32, the
settings `grid_cell` reads), `grange` (u32, each bucket's start and end in the
order) and `gorder` (u32, point indices ordered by bucket). A shader run by the
`shader.compute` or `sim.shader` op of the shader pack gets a grid over its
domain's `P` by declaring those three bindings and giving the op a
`neighborRadius`, the cell side
(`g:node("counted", "shader.compute", { domain = "pts" }, { shader = ref, neighborRadius = 0.7 })`).
The `g.sim.shader` node walks the `hash_walk` module's hash instead.
A point `j = gorder[s]` in the span of cell `cc` belongs to `cc` exactly when
`zero_grid_cell` of its own position is `cc`; two cells can share a bucket, so
the walk checks it:
```wgsl
#include "@builtin::systems.procgen.grid"
let c = zero_grid_cell(p);
for (var dz = -1; dz <= 1; dz = dz + 1) {
for (var dy = -1; dy <= 1; dy = dy + 1) {
for (var dx = -1; dx <= 1; dx = dx + 1) {
let cc = c + vec3<i32>(dx, dy, dz);
let span = zero_grid_range(cc);
for (var s = span.x; s < span.y; s = s + 1u) {
let j = gorder[s];
// skip j == i, and any j whose own cell is not cc
}
}
}
}
```
A complete shader that counts each point's neighbours within `radius` this way, run by the `shader.compute` op with
`neighborRadius` set to the same radius, declares:
```yaml
bindings:
- { name: P, kind: buffer, access: read, element: f32 }
- { name: nb, kind: buffer, access: read_write, element: f32 }
- { name: gcfg, kind: buffer, access: read, element: f32 }
- { name: grange, kind: buffer, access: read, element: u32 }
- { name: gorder, kind: buffer, access: read, element: u32 }
params:
- { name: radius, type: float, default: 1.0 }
- { name: count, type: int, default: 0 }
```
```wgsl
#include "@builtin::systems.procgen.grid"
fn at(j: u32) -> vec3<f32> {
return vec3<f32>(P[j * 3u], P[j * 3u + 1u], P[j * 3u + 2u]);
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let i = id.x;
if (i >= u32(params.count)) { return; }
let p = at(i);
let r2 = params.radius * params.radius;
let c = zero_grid_cell(p);
var n = 0.0;
for (var dz = -1; dz <= 1; dz = dz + 1) {
for (var dy = -1; dy <= 1; dy = dy + 1) {
for (var dx = -1; dx <= 1; dx = dx + 1) {
let cc = c + vec3<i32>(dx, dy, dz);
let span = zero_grid_range(cc);
for (var s = span.x; s < span.y; s = s + 1u) {
let j = gorder[s];
if (j == i) { continue; }
let q = at(j);
if (any(zero_grid_cell(q) != cc)) { continue; }
let e = q - p;
if (dot(e, e) < r2) { n = n + 1.0; }
}
}
}
}
nb[i] = n;
}
```
▲ 0↑ born
# grid_cell
The cell a point stands in (`zero_grid_cell`) and the bucket of a spatial hash
grid that cell hashes to (`zero_grid_bucket`), read against the grid settings
bound as `gcfg`. What a pass that only keys points by cell includes; a pass that
walks the grid includes `grid`, which includes this.
`gcfg` is an `array<f32>` the includer binds: `[0]` one over the cell side,
`[1]` the bucket mask (2^bits - 1), `[2]` the cell side. `proc.device.gridInto`
returns it as the grid's `cfg`.
```wgsl
#include "@builtin::systems.procgen.grid_cell"
```
▲ 0↑ born
# bvh
The tree of a bounding volume hierarchy over the primitives of a geometry (an
LBVH): a leaf per primitive in Morton order with its bounds, and the internal
nodes linked by the longest common prefix of the sorted codes, equal codes broken
by place. It reads the points (`pts`), the point each vertex reads (`vpt`), each
primitive's `vstart` and `vcount`, the `codes` of `bvh_codes` and the `order` the
`sort` kernel gives them, over the params `np` (the primitives) and `pyr_size`
(`np` rounded up to a power of two). It writes every leaf and every link of
`nodes` (`(2 * np - 1) * 8` words) and allocates `pyr` (`6 * pyr_size` words),
the pyramid `bvh_pyramid` fills. `bvh_pyramid` and `bvh_internal` then fill in
the internal bounds, and the `ray` and `intersect_pairs` kernels traverse the
finished table. The `geometry.bvh` node runs the whole build and answers the
table as its `tree`. `bindings.yaml` states the node layout and the order the
kernels run in. Dispatch over `np`. Exact: the same geometry gives the same tree.
▲ 0↑ born
# bvh_box
The boxes the bvh kernels fold: `ZeroBox` (`lo` and `hi` corners), the empty box
`zero_empty_box()` (minimum +3.4e38, maximum -3.4e38, `ZERO_EMPTY`, which any box
grows) and `zero_grow(a, b)`, the box holding two boxes. The module binds
nothing, so any shader includes it.
▲ 0↑ born
# 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.
▲ 0↑ born
# bvh_internal
The last step of a bounding volume hierarchy build: each internal node's bounds,
the fold of the leaves its run of sorted places covers, read from the pyramid
`bvh_pyramid` wrote. It reads `codes` and `order` (to find each node's run),
`pyr` and the leaves of `nodes`, over the params `np` and `pyr_size`, and writes
the bounds words of nodes `0 .. np - 2` of `nodes` in place, after which the
`ray` kernel can traverse it. The `geometry.bvh` node runs it last. Dispatch
over `np - 1`, one invocation per internal node. Exact.
▲ 0↑ born
# bvh_levels
How the bvh kernels read bounds: a node of the node table (`zero_node_box`), a
node of the pyramid of leaf bounds (`zero_pyr_box`) and a node of the segment
tree both form (`zero_tree_box`). The module header lists the buffers and params
the includer declares and the node layout.
▲ 0↑ born
# bvh_prim
`zero_prim_box(p)`, the bounds of one primitive over its vertices (the empty box
for a primitive with no vertices), and `zero_vertex_point(v)`, the position of
the point a vertex reads, with the box types of `bvh_box`. The module header
lists the buffers the includer binds.
▲ 0↑ born
# bvh_pyramid
One level of the pyramid of leaf bounds: each pyramid node folds the bounds of
two nodes of the level below (leaves at the first level). Dispatched once per
level, the levels let `bvh_internal` fold the bounds of any run of leaves in a
few reads. It reads the leaves of `nodes` and writes `pyr` (6 words a node,
minimum then maximum) in place, each level reading what the level before it
wrote. The params are `np`, `pyr_size` and `level` (1 .. log2(`pyr_size`)); a
dispatch covers `pyr_size >> level` nodes. The `geometry.bvh` node runs it once
per level, between `bvh` and `bvh_internal`. Exact.
▲ 0↑ born
# bvh_span
The binary radix tree over sorted Morton codes: for internal node `i`,
`zero_span_of(i)` gives the run of sorted places it covers and the place it
splits at, as a `ZeroSpan` (`lo`, `hi`, `split`: the left child covers
`lo .. split`, the right `split + 1 .. hi`), from the length of the common prefix
of the sorted codes (`zero_delta`, equal codes ordered by place). The module
header lists the buffers and the param the includer declares.
▲ 0↑ born
# color
Colour helpers a per-element template calls: `zero_color_srgb_to_linear`,
`zero_color_linear_to_srgb`, `zero_color_luminance`, `zero_color_hsv_to_rgb`,
`zero_color_rgb_to_hsv`, `zero_color_blackbody(kelvin)` (linear RGB of a
blackbody) and `zero_ramp_ease(f)`, the smooth ease a `ramp` blends keys with.
```wgsl
#include "@builtin::systems.procgen.kernels.color"
fn ember(heat: f32) -> vec3<f32> { return zero_color_blackbody(1000.0 + 2500.0 * heat); }
```
▲ 0↑ born
# 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, each invocation a stretch of `ceil(n / 256)` consecutive elements: the
stretches' kept counts are summed in order once, and each invocation stores its
kept elements from the count before its stretch, so a run of any length costs one
sum of 256 counts. 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. Each slot at or past the live count is written -1 by the invocation of the
dispatch that stands for it, so the slots past a short live count cost one write each
across the whole dispatch. `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).
▲ 0↑ born
# 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.
▲ 0↑ born
# 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.
▲ 0↑ born
# contour_core
The shared WGSL of the dual contouring kernels (`contour_cells`, `contour_crossings`,
`contour_solve`, `contour_quads`): `ZsGrid` (`samples` along x and y, `cells`
along x, y and z, `origin`, cell size `h`), the addressing of a grid of samples
and its cells (`zs_sample_index`, `zs_sample_ijk`, `zs_cell_index`,
`zs_cell_ijk`, x fastest), the corners of a cell (`zs_corner(n)`, corner `n` at
`(n & 1, (n >> 1) & 1, (n >> 2) & 1)`) and its twelve edges (`zs_edge_a(e)`,
`zs_edge_b(e)`: four along x, four along y, four along z), and the least-squares
solve (`ZsQef`, `zs_qef_add`, `zs_qef_solve`) that places a cell's vertex where
the surface normals around it agree.
```wgsl
#include "@builtin::systems.procgen.kernels.contour_core"
```
▲ 0↑ born
# contour_crossings
Where the surface crosses each of the twelve edges of every straddling cell:
the point (`cross_p`) and whether it crosses (`cross_w`, 1 or 0). The crossing
is the linear interpolation of the two corner samples to zero. An edge that does
not cross carries its cell's centre, a point any shape can be read at. Slot `s`
of the outputs is the `s`-th straddling cell, `cells[s]`, and edge `e` of it is
slot `s * 12 + e`. It reads `vals` and the grid params as `contour_cells` does,
`cells` (the list `compact` makes of the straddling cells) and `domain_count`
(the live count `compact` made, bound in every variant): a slot at or past it
holds the point (0, 0, 0) and weight 0. `contour_solve` reads the outputs.
Dispatch over the straddling cells, or the capacity of their list. Exact: each
slot has one writer.
▲ 0↑ born
# contour_quads
One quad per grid edge the surface crosses, spanning the four cells around it.
Edge `e` is the edge of sample `e / 3` along axis `e % 3`. `quad_flag[e]` is 1
for an edge that owns a quad and `quad_v[e]` holds its four vertex numbers, wound
so every face points away from the solid. An edge on the grid's boundary, or one
with a cell around it that owns no vertex, owns no quad.
`vertex_of[c]` is the number of the vertex cell `c` owns, or below 0 for a cell
that owns none: the inverse map `compact` writes beside the list of straddling
cells. It reads `vals` and the grid params as `contour_cells` does. The
`sdf.mesh` node compacts `quad_flag` into the kept quads `contour_triangles`
splits.
Dispatch over `3 * samples` edges. Exact: each edge has one writer.
▲ 0↑ born
# contour_solve
The vertex of each straddling cell, written to `pos`. With `PLACEMENT` `qef` the
vertex is the point nearest the planes the surface normals at the cell's
crossings describe (least squares, pulled back toward the mean of the crossings
by `lambda` per crossing, default 0.02), which puts the vertices on a box's
edges and close to its corners; with `centroid` it is the mean of the crossings.
A `qef` vertex is held just inside its own cell (a thousandth of the cell size
in from each wall), so two cells sharing a wall never land two vertices on one
point.
It reads the grid params as `contour_cells` does, `cells` and `domain_count`
(the list of straddling cells and the live count `compact` made; a slot at or
past the count takes the origin), `cross_p` and `cross_w` from
`contour_crossings`, and `cross_n`, the unit surface normal at each crossing,
read when `PLACEMENT` is `qef` (a crossing with a zero normal adds no plane and
still counts toward the mean). The `sdf.mesh` node runs it with the normals of the shape's
gradient and takes `pos` as the mesh's points.
Dispatch over the straddling cells, or the capacity of their list. Exact: each
vertex has one writer.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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).
▲ 0↑ born
# edges_runs
Turns the sorted sides of a mesh into the edge table. Two stages share one
dispatch shape, chosen by the `STAGE` specialization:
- `STAGE heads` flags, per sorted place, where a new edge starts;
- `STAGE table`, after the flags are compacted into `starts`, writes each edge's two
points (`a` < `b`) and the number of sides along it (`fcount`).
The whole sequence for a mesh with `nv` vertices: `edges` writes `lo`, `hi`,
`face`, `rev`; a stable sort by `hi` and then by `lo` gives `order`; `STAGE heads` flags
the heads; `compact` of the flags gives `starts` and the live edge count; `STAGE table`
writes the edges. An edge's faces are the primitives `face[order[starts[e] + j]]`
for j below `fcount[e]`, so `gather(face, order)` is the `faces` column the
`core.edges` node answers, with `starts` as its `faceStart` and `fcount` its
`faceCount`. An edge is open when `fcount` is 1 and manifold when it is at most
2. Integers are 32-bit words, exact.
In the plain variant the `n` param is the number of sorted places (the vertex
slots, also the most edges there can be); stage table runs over the edges, and an
invocation past the live edges writes values nothing reads.
Over a live count (`COUNT=device`, see the abi README) `domain_count` is the number
of live sorted places in both stages, and the `n` param is not read. Stage heads runs
over the capacity of places and holds 0 in `flag` past the live ones. Stage table
runs over the capacity of edges: an edge is live where `starts` holds a place below
the live places (the slots past the live edges hold -1 where `compact` over a live
count makes them), a run ends at the live places, and every other slot holds -1 and
-1 in `a` and `b` and 0 in `fcount`. The device variant binds the buffers of its own
stage only: 5 storage buffers in stage heads and 8 in stage table (8 in the plain
variant).
▲ 0↑ born
# 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.
▲ 0↑ born
# filter_weights
The reconstruction filters an image resample weighs source pixels with:
bilinear (triangle), lanczos3 and Catmull-Rom, each as `zf_weight(filter, x)`
over a distance in output-pixel units with its reach from `zf_support`. A filter
is named by the constants `ZF_BILINEAR` (0), `ZF_LANCZOS3` (1), `ZF_CATMULL_ROM`
(2) and `ZF_NEAREST` (3); `zf_weight` weighs `ZF_NEAREST` as bilinear and
`zf_support` gives it a reach of 1, so the includer picks the nearest pixel
itself. The `resample` kernel includes it.
```wgsl
#include "@builtin::systems.procgen.kernels.filter_weights"
```
▲ 0↑ born
# fx_compact
The keep mask to indices and the map back from every element to the place it holds among the kept ones, as the one
program of the fixed device program set (`proc.fx`) that runs every variant of `compact`. `kernels/compact` states the
algorithm; this program is its twin and answers the same words.
The count source is the one param, `flags` (`int`): bit 0 takes the elements as the first `domain_count` of the n slots.
A dispatch binds every buffer; a buffer the count source leaves unread is any one-word run. `indices` is an appended
output whose live count is the number kept.
▲ 0↑ born
# fx_eval
The element interpreter of the fixed device program set (`proc.fx`). A dispatch runs the jobs of a program run: each job
names an op list (SSA ops over a scalar bank of registers in workgroup memory and a vector bank), the column
descriptors its ops read, and the column the answer is written to. The pages the columns stand in bind as `P0` to
`P6`; the program run binds as `zjobs`; `zjob` is the word where the dispatch's header starts, and `zs0` to `zs15` are
the slot words ops read.
Variants by `FAMILY`: `core` holds the arithmetic, comparison, select, conversion, vector, column-read and field
operator ops; `rand` adds the unit hash; `noise` adds the flow noise. A dispatch takes the smallest family that holds
every op of its jobs. The same op list gives the same words on every family.
▲ 0↑ born
# fx_expand
The count per element turned into runs (element j appears counts[j] times, in element order), as the one program of the
fixed device program set (`proc.fx`) that runs every variant of `expand`. `kernels/expand` states the algorithm; this
program is its twin and answers the same words.
The count sources are the one param, `flags` (`int`): bit 0 takes the first `domain_count` elements as live and states
the live count of `owner` as the sum of their counts, above the capacity too; bit 1 takes the first `element_count`
elements as live. A dispatch binds every buffer; a buffer no count source reads is any one-word run. `owner` is an
appended output.
▲ 0↑ born
# fx_make
The fixed twin of `make`: one program of the fixed device program set (`proc.fx`) that runs every shape (`points`,
`strip`, `fan`, `grid`, `ring`) and both passes (`sizes`, `fill`) of the library kernel. It binds the buffers `make`
binds, under the same names, and answers the same words.
Its params are all integers: `across` (the grid's points along its second axis, at least 2), `shape` (0 points, 1 strip,
2 fan, 3 grid, 4 ring) and `stage` (0 sizes, 1 fill). `fx.module/make.luau` states them for a variant from its
specialization.
▲ 0↑ born
# fx_ray_shapes
The fixed twin of `ray_shapes`: one program of the fixed device program set (`proc.fx`) that casts the rays of every
variant (`words`, `segments`, `live`) against the shape table and answers the same words: `hit`, `hit_prim`,
`hit_normal` and `hit_end`.
A device stage binds at most eight storage buffers, so the program holds one run for each of the three ray inputs
(`ray_from`, `ray_to`, `ray_extra`) where the variants hold five: `fx.module/ray_shapes.luau` states which binding of a
variant each one takes. Its params are `skin` (a float: how far the corrected end stands off the surface) and `source`
(an integer: 0 the rays are 8 words of `ray_from`, 1 the segments of `ray_from` and `ray_to` cast by the f32 words of
`ray_extra`, 2 the segments of the first `ray_extra[0]` elements).
▲ 0↑ born
# fx_reduce
The fold of a run of elements to one element per group (the whole run, or each segment), as the one program of the
fixed device program set (`proc.fx`) that runs every variant of `reduce`. `kernels/reduce` states the algorithm; this
program is its twin and answers the same words.
The element, the fold and the count sources are params of one program: `lanes` words an element (1 to 4), `kind` 0 for
f32 words and 1 for i32 words, `fold` 0 add, 1 min, 2 max, 3 mean, 4 count, 5 argmin, 6 argmax, and `flags` bit 0 for a
live element count read from `domain_count`, bit 1 for a live segment count read from `segment_count`. A dispatch binds
every buffer; a buffer no count source reads is any one-word run. Params type: `int` (all five, plus `segments`).
▲ 0↑ born
▲ 0↑ born
▲ 0↑ born
# 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.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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).
▲ 0↑ born
# hash_cell
The cell a point stands in (`zero_hash_cell`) and the bucket a cell hashes to
(`zero_hash_bucket`). The `hash` kernel keys points with them and the
`hash_walk` module (which `hash_count`, `hash_gather`, `hash_nearest`,
`hash_repel` and `hash_hook` include) looks cells up with them, so one
definition decides every point's bucket.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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).
▲ 0↑ born
# 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.
▲ 0↑ born
# hash_nearest
The nearest indexed point of each query position, found through the spatial hash
the `hash` and `hash_starts` kernels build, with its squared distance. A query
walks the cells within a few shells of its own and, when that cannot prove its
answer, reads every point. The lower index wins of two points equally near.
Exact.
It writes `nearest` (the index, `0xffffffff` when no point is indexed) and `dist2`,
one each a query. The params are `points` (the indexed points), `buckets`,
`inv_cell`, `rings` (the shells walked before the search over every point,
default 2) and `skip_self` (1 leaves out the point whose index is the query's).
`core.neighbours` finds each point's nearest source and its distance with it.
Over a live number of indexed points (`POINTS=device`) `params.points` is the most points there can be, and the first
`point_count` of them are indexed: the search over every point stops at the live ones, and a query with none indexed
reports the none marker.
▲ 0↑ born
# hash_repel
For each query position, the push away from the indexed points within a radius of it, searched through the spatial
hash the `hash` and `hash_starts` kernels build. Each neighbour strictly inside the radius pushes along the unit
direction from itself to the query, scaled by `1 - distance / radius`; the query takes the mean over its neighbours.
With `skip_self` 1 the point whose index is the query's and every point standing on the query are left out. The walk
visits the points in the same order on every run. Exact.
It reads `pts`, `order` and `range` (the index), `qpts` (xyz a query) and `domain_count`, which it binds in every
variant: a slot at or past the live count takes a zero push. It writes `push`, one `vec3<f32>` a query.
`core.neighbours` computes its `repel` push with it when no cone is given.
▲ 0↑ born
# 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`.
▲ 0↑ born
# hash_walk
How a shader reads the spatial hash `hash` and `hash_starts` build: a walk over
the points within a radius of a query position (`zero_nb_begin`,
`zero_nb_next`, which answers `ZERO_NONE` when the walk is done), and the
nearest point of a query (`zero_hash_nearest`). The module header lists the
bindings and params the includer declares. The walk visits every cell within
`ceil(radius * inv_cell)` of the query's own, so any radius is answered in full;
it visits cells in a fixed order and, within a cell, points in sorted order, so a
shader that lists neighbours lists them in the same order on every run. It
includes `hash_cell`. `hash_count`, `hash_gather`, `hash_nearest`, `hash_repel`
and `hash_hook` include it.
▲ 0↑ born
# intersect_core
The triangle pair tests of the `intersect` kernels. A pair of triangles, `a` of mesh A and `b` of mesh B,
has a cut in parts; every part is a segment, and an endpoint is named by the edges or the corner it is made
of, and computed from nothing else, so the triangles that share an edge compute the same point to the bit.
The includer binds `apts`, `atri`, `bpts` and `btri`. `zi_part(a, b, part)` answers part `part` as a `ZiCut`
(`ok` when the part is present, and its endpoints `e0` and `e1`). `intersect_pairs` and `intersect_cuts` include it.
## Parts
| Part | What | Cuts |
|---|---|---|
| 0 | The ordinary cut of two triangles that are not coplanar: the segment with two endpoints, each an edge of one triangle crossing the other (`zi_pair`). A vertex exactly on a plane counts as on its positive side, so triangles that only touch cross consistently or not at all. | A and B |
| 1 to 3 | Coplanar triangles: edge `part - 1` of `b`, clipped to the closed triangle `a`. | A |
| 4 to 6 | Coplanar triangles: edge `part - 4` of `a`, clipped to the closed triangle `b`. | B |
| 7 to 15 | Edge `i` of `a` and edge `j` of `b` lie in one plane and cross strictly inside both: the crossing, part `7 + 3 i + j`. A segment of no length. | A and B |
| 16 to 24 | Corner `v` of `a` lies exactly strictly inside edge `j` of `b`: part `16 + 3 v + j`. A segment of no length. | A and B |
| 25 to 33 | Corner `v` of `b` lies exactly strictly inside edge `i` of `a`: part `25 + 3 v + i`. A segment of no length. | A and B |
Triangles are coplanar when neither is degenerate and every corner of each is exactly on the plane of the
other (the signed volume is 0). Coplanar triangles have parts 1 to 6 and no part 0; a part is present when
the clipped edge keeps a length. The clip is made in the projection along the axis the plane's normal points
along most, with every edge taken from its lower point id to its higher; an edge is cut where it leaves the
triangle by the line of an edge of the triangle.
Parts 7 to 33 split an edge: a cut point that lies on an edge is a point of every triangle that uses the
edge, whatever plane that triangle lies in, so every pair of a triangle of A and a triangle of B that share
the edges reaches it and reports the same point. A crossing is computed along the edge of A from the two
edges alone.
## Endpoint records
An endpoint is `ZiEnd`: its position, the kind word (the kind in the low byte, which meshes the segment
cuts in bits 8 and 9, 1 mesh A, 2 mesh B, 3 both), `lo`, `hi`, `tri` and `extra`.
| Kind | Endpoint | `lo`, `hi` | `tri`, `extra` |
|---|---|---|---|
| 0 | an edge of A through triangle `tri` of B | the edge | `tri`, 0 |
| 1 | an edge of B through triangle `tri` of A | the edge | `tri`, 0 |
| 3 | an edge of B crossing an edge of A in their plane | the edge of A | the edge of B |
| 4 | a point of B | its id, twice | 0, 0 |
| 5 | a point of A | its id, twice | 0, 0 |
Two endpoints with all of kind word, `lo`, `hi`, `tri` and `extra` equal are one point.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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).
▲ 0↑ born
# loops
Orders directed edges into rings and chains. This kernel links each edge to the
edge that follows it (`next`) and marks the edges a chain starts with (`head`);
the `jump` and `loops_cut` and `loops_place` kernels do the rest.
For the boundary of a mesh (`core.boundary` runs the sequence), the directed edges
are its open edges run the way their one face runs them (`tail` is `a` when the
`core.edges` table's `reversed` is 0, else `b`). The whole sequence over `m` edges
and `npts` points:
1. `loops` (`STAGE` clear, claim, link): `next`, `head`.
2. `jump` (`MODE` min), ceil(log2 m) rounds, starting from `parent` = `next` and
`value` = the edge index: every edge holds the smallest index within reach,
and `parent` holds the edge 2^k steps ahead.
3. `loops_cut` (`STAGE` head, cut): a ring (a cycle) starts at its smallest edge; a chain
starts at its head. The edge before each start becomes the end of its list.
4. `jump` (`MODE` rank) over the cut lists, starting with `value` 1 on every
non-end edge: each edge's end and its distance to it.
5. `loops_place` (`STAGE` claim, place): each edge's ring (the first edge of its list) and its
position along the ring.
A compaction of the first edges numbers the rings, and a prefix sum of ring
lengths (`rank` of the first edge plus 1) gives the ring starts; an edge's place in
the ordered listing is its ring's start plus its position.
Over a live count (`COUNT=device`, see the abi README) the stages claim and link run
over a capacity of edges whose live count is `domain_count`, and the `n` and `npts`
params are not read. Stage clear runs over the capacity of points and writes the
cleared value into every slot, which is the value a slot past the live points holds.
In stage link a slot past the live edges links to itself and is no head. It binds 7
storage buffers (6 in the plain variant).
▲ 0↑ born
# 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).
▲ 0↑ born
# loops_place
Gives every edge its ring and its position along it, from the ranked lists
`loops_cut` and `jump` produced. `ring` is the first edge of the edge's list, so
two edges are on one ring exactly when their `ring` values are equal; `pos`
counts along the ring from that first edge. `STAGE claim` records each list's
first edge in `headof` under the list's end (`root`); `STAGE place` reads it back
for every edge and writes `ring` and `pos` from `rank`. `core.boundary` lists its
loops by `ring` and `pos`. 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 has the ring -1 and the position 0. It binds 7 storage buffers (6 in
the plain variant).
▲ 0↑ born
# luau_noise
The Perlin noise of Luau's `math.noise`, for a field chain's kernel: `zero_luau_noise(x, y, z)` answers what
`math.noise(x, y, z)` answers on the CPU, from the same permutation table (`ZERO_LUAU_NOISE_HASH`) and gradient
table (`ZERO_LUAU_NOISE_GRADIENT`). The value is about -1 to 1, 0 at every whole-number point, and repeats every 256
units in each axis; the coordinates are wrapped into that period first.
```wgsl
#include "@builtin::systems.procgen.kernels.luau_noise"
fn ripple(p: vec3<f32>) -> f32 { return zero_luau_noise(p.x, p.y, p.z); }
```
The `math.noise` node of `nodes/math.nodebox` (the `noise` operation of `proc.fieldc.operators`) includes this module
in the chain it writes.
▲ 0↑ born
# 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.
▲ 0↑ born
# 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. Over a live count
`n` is the capacity and the first `domain_count` elements are the template's:
`COUNT=device` writes zero past them, and `COUNT=live` leaves the elements past
them as they stand.
```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; given a live count
(`live`) it runs the `COUNT=device` variant over that count, and the `COUNT=live` variant when it is asked to keep the
elements past the count (`rest = "keep"`). 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.
▲ 0↑ born
# noise
Lattice noise over the shared hash of `rand`: `zero_proc_value3(seed, p)` in
[0, 1), `zero_proc_gradient3(seed, p)` in [-1, 1], `zero_flow_worley(seed, p,
jitter)`, `zero_flow_simplex(seed, p)`, `zero_flow_curl(seed, p, freq, amp)`,
and the octave sums `zero_noise_fbm_value(seed, p, octaves)` /
`zero_noise_fbm_gradient(seed, p, octaves)` (octave o drawn from `seed + o`, at
doubling frequency and halving weight, normalised by the weights). The plane
forms `zero_proc_value2(seed, p)`, `zero_proc_gradient2(seed, p)`,
`zero_noise_fbm2(seed, p, octaves, lacunarity, gain, gradient)`,
`zero_noise_fbm_value2` and `zero_noise_fbm_gradient2` return the values of
`proc.noise` `value2`, `gradient2` and `fbm2`. The space forms return the values
of `proc.noise` `value3` and `gradient3`, and Worley, simplex and curl the values
the CPU forms of the `flow` pack's `field.worley`, `field.simplex` and
`field.curl` ops compute. Each agrees with its CPU form to f32 rounding of the
interpolation.
The nodes `field.noise`, `field.worley`, `field.simplex`, `field.curl` and
`texture.noise` call these functions through `field.call`, which reaches every function a
`kernels/` shader module defines.
```wgsl
#include "@builtin::systems.procgen.kernels.noise"
fn height(p: vec3<f32>) -> f32 { return zero_noise_fbm_gradient(7u, p * 0.1, 4u); }
```
▲ 0↑ born
# noise_angle
Gradient noise over a plane whose lattice gradients are unit vectors at a hashed angle, and the fractal sum of it.
- `zero_angle_gradient2(p, seed)`: gradient noise with quintic interpolation, roughly -0.7 to 0.7.
- `zero_angle_fbm2(p, octaves, lacunarity, gain, seed)`: `octaves` layers, each `lacunarity` times finer and `gain` times as strong as the one before, octave `i` (from 0) drawn from `seed + i * 7919`, summed and divided by the root of the sum of the squared strengths.
- `zero_angle_gradient2_d(p, seed)`: the same noise and its slope, a `vec3`: x the value, yz the derivative along each axis of `p`.
- `zero_angle_fbm_damped2(p, octaves, lacunarity, gain, seed, damping)`: `zero_angle_fbm2` with each octave's height divided by `1 + damping * |s|^2`, `s` the slope of the octaves below it in `p`'s units, so fine octaves fade where the coarser ones stand steep and keep their height on the flats between; a `damping` of 0 or less answers `zero_angle_fbm2`'s sum.
- `zero_angle_warped2(p, warp, feature, seed)`: `p` pushed by a second noise, two 4-octave sums from seeds of their own, scaled by `warp / feature` noise units; a `warp` of 0 or less leaves `p` where it is.
```wgsl
#include "@builtin::systems.procgen.kernels.noise_angle"
fn relief(p: vec2<f32>) -> f32 { return zero_angle_fbm2(p, 6u, 2.0, 0.5, 1u); }
```
▲ 0↑ born
# order_key
Maps the 32-bit word of a float or a signed integer to an unsigned key that
sorts the way the value does, and back. `zero_order_key(word, is_float)` and
`zero_order_word(key, is_float)` are inverses. A kernel that keeps the least or
the greatest of many contributions runs `atomicMin` or `atomicMax` on keys and
reads the same answer whatever order the contributions arrive in.
▲ 0↑ born
# rand
The lattice hash and the unit random draw the procgen kernels share:
`zero_proc_fnv_u32`, `zero_proc_avalanche`, `zero_proc_unit(prefix, element)`,
and the seeded forms `zero_rand(seed, element)`, `zero_rand_range`,
`zero_rand3`. The draw equals the CPU hash to the last bit, because it folds
the same bytes and mixes with the same decimal constants.
```wgsl
#include "@builtin::systems.procgen.kernels.rand"
fn jitter(id: u32) -> f32 { return zero_rand_range(7u, id, -0.5, 0.5); }
```
`rand.unit(seed, ...scope, id)` of the field nodes is `zero_proc_unit(prefix, id)`: the prefix is `hash.scopePrefix` of the seed and scope folded once on the CPU, so the draw equals `hash.unitFloat` to the bit.
▲ 0↑ born
# 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.
▲ 0↑ born
# ray_shapes
Casts rays and segments against a table of analytic shapes (plane, sphere, box,
capsule) and answers the closest hit of each. A ray is 8 words of `rays`: origin
xyz, tmin, direction xyz, tmax; the direction need not be unit length, so a
segment from a to b is origin a, direction b - a, tmin 0, tmax 1. A ray whose tmax is below
its tmin meets nothing and tests no shape. The `RAYS=segments` variant takes the
segments as columns instead: ray i runs from `ray_from[i]` to `ray_to[i]` (both
Vec3), and is cast when `ray_cast[i]` is above 0; a segment not cast meets nothing
and tests no shape. The table is one `columns`
binding named `shapes`, a row a shape, columns in this order:
`shapeKind` (Int: 0 plane, 1 sphere, 2 box, 3 capsule), `center` (Vec3),
`extent` (Vec3: a plane's unit normal, a sphere's radius in x, a box's half
size, a capsule's radius in x and half length in y), `rotation` (Vec4
quaternion x y z w; a capsule lies along its own y), `bounce`, `friction`
(Float, carried for the caller) and `index` (Int, the caller's id for the
shape).
Outputs, a value per ray: `hit` (t, then three zeros), `hit_prim` (the row of the
hit shape, `0xffffffff` for a miss), `hit_normal` (the unit surface normal,
turned to face the ray's origin side, zero for a miss) and `hit_end` (the hit
point pushed out along the normal by the `skin` param; for a miss the ray's end,
origin + direction * tmax). A shape is hit from outside at its entry and from
inside at its exit; of two hits at equal t the lower row wins. Exact.
The `RAYS=live` variant casts the segments of the first `domain_count` elements
of `ray_from` and `ray_to`: `n` is the capacity a live count bounds, and a ray at
or past the count leaves its outputs as they stand.
`sim.particles` runs the `RAYS=live` variant in its collision stage, a segment
for each slot up to the extent of the slots its particles hold, from where the
particle stands to where the step moves it, against the shape table of its
colliders.
▲ 0↑ born
# ray_surface
The normal and the corrected end of the closest triangle hits the `ray` kernel
found. Bind the same `rays`, `pts`, `vpt` and `vstart` the ray dispatch read,
and its `hit` and `hit_prim` outputs. Outputs, a value per ray: `hit_normal`
(the unit normal of the triangle hit, turned to face the ray's origin side,
zero for a miss) and `hit_end` (the hit point pushed out along the normal by the
`skin` param; for a miss the ray's end, origin + direction * tmax). The shape
index of a hit is `hit_prim`, the primitive. Exact.
▲ 0↑ born
# reduce
Folds a run of elements to one element per group: the sum, least, greatest,
mean, count, or the index of the least or greatest, of the whole run or of each
segment of it.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `T` | `f32`, `i32`, `vec2` to `vec4` of either | the element; a vector folds lane by lane |
| `FOLD` | `add`, `min`, `max`, `mean`, `count`, `argmin`, `argmax` | the fold |
The dispatch size `n` is the number of elements. One workgroup folds one group at
a time, so a segmented fold runs its segments side by side and an unsegmented
one is a single group; any workgroup count from 1 up folds every group.
`params.segments` above 0 makes `starts` partition the run into that many
segments: it holds where each segment begins (a segment ends where the next
begins, the last at `n`), and `dst` holds one element per segment. With
`segments` 0 the whole run is one group, `starts` is any one-word run, and `dst`
holds one element. An empty group answers 0 for every
fold. `argmin` and `argmax` write the lowest index among equal elements to
`picked` (for a vector element, the element that beats the best before it in
every lane); every other fold writes -1 there. The mean of an integer run is
the integer quotient. The bounds of a run are its `min` and its `max`.
Exact: every group folds its elements in a fixed order and combines the 256
partial results in a fixed tree, so the same run gives the same bits on every
dispatch, and an integer fold is the exact integer answer.
Over a live count (`COUNT=device`) `n` is the capacity and the first `domain_count` elements are the run: the last
segment ends at the live count. Over live segments (`SEGMENTS=device`) `params.segments` is the most segments there can
be, which sizes `dst` and `picked`, and the first `segment_count` of them are live; a group past them is not written, and
a run of no live segments folds nothing.
Nodes that fold columns run it, among them `core.reduce`, `core.select`, `core.arclength`, `core.normals.face`,
`attribute.promote` and `sim.particles`.
▲ 0↑ born
# resample
Image resample of one or more slices (a Texture's texels, a Grid layer, each
tile of a Raster) to a target size, with the `FILTER` specialization (`bilinear`, `lanczos3`, `catmull_rom`, `nearest`). Downscaling widens the filter by the shrink ratio so it
averages what it drops. `axis` resamples width (0), height (1) or both (2); width
then height gives the both-axes result up to float rounding.
`determinism: exact`.
`src` holds `slices` images of `sw` x `sh` pixels, `lanes` f32 values a pixel,
slice by slice with rows x fastest; `dst` holds the same layout at the output
size (`dw` x `sh`, `sw` x `dh` or `dw` x `dh`) and is bound by the caller. The
lanes `laneBase` to `laneBase + laneCount - 1` (at most 16) are resampled and
written; `clampRange` 1 holds each result to `lo` .. `hi`. One thread per
output pixel of every slice, numbered `gid.x + gid.y * num_workgroups.x * 64`,
so a dispatch past 65535 workgroups spreads over rows. The bindings are bound by
list position.
▲ 0↑ born
# run_sides
How many sides a primitive's run of vertices has (`zero_run_sides(vc, wrap)`),
which vertex the end of a side lands on (`zero_run_next(k, vc)`), and
`ZERO_NONE`, the value a slot holds when it names no edge or point (the largest
`i32`, so it orders after every real index). A run of `vc` vertices has `vc`
sides when it wraps and holds 3 or more, `vc - 1` otherwise, and none below 2;
side k joins vertex k to vertex `zero_run_next(k, vc)`, the run's first after
its last. The `edges`, `edges_runs`, `loops` and `topology` kernels walk runs
with them, so all of them agree on what a face's perimeter is.
▲ 0↑ born
# scan
The prefix fold of a run of elements, whole or per segment: running sums,
running least and greatest, running products. (The running product of 4x4
matrices is `scan_mat4`.)
| Specialize | Options | Meaning |
|------------|---------|---------|
| `T` | `f32`, `i32`, `vec2` to `vec4` of either | the element; a vector scans lane by lane |
| `OP` | `add`, `min`, `max`, `mul` | the operator |
`params.exclusive` picks the fold of the elements before each one or the fold up
to and including it. The first element of a group has nothing before it: an
exclusive scan holds 0 there for `add`, 1 for `mul`, and the element itself for
`min` and `max`. `total` holds the fold of each group, 0 for an empty group. A
segmented scan (`params.segments` above 0, the number of segments) restarts at
each start in `starts`; an unsegmented one binds any one-word run there.
One workgroup scans one group at a time, a tile of 128 elements at a time, with
the fold of everything before a tile carried into the next. The dispatch size
`n` is the number of elements; any workgroup count from 1 up scans every group.
Exact: the order of combination is fixed, so the same run gives the same bits on
every dispatch, and an integer scan is the exact integer answer.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` elements are the run. Every slot of `dst` at or past it holds the
total of the last group (the whole run, or the last segment; 0 for an empty one), which
is the scan of the run padded with the operator's identity. An `i32` scan's `total` is a count another kernel takes as its
domain (`{ count = total, capacity = ... }`). It binds 5 storage buffers (4 in the plain
variant).
Over live segments (`SEGMENTS=device`) `params.segments` is the most segments there can be, which sizes `total`, and the
first `segment_count` of them are live: a segment past them is not scanned, and a run of no live segments scans nothing.
It binds one storage buffer more than the variant it extends.
Nodes that need offsets, running totals or arc lengths run it, among them `core.make`, `core.select`, `core.edges`,
`core.arclength`, `core.realize`, `core.sample_curve`, `core.sample.surface`, `attribute.accumulate` and
`sim.particles`.
▲ 0↑ born
# 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.
▲ 0↑ born
# scatter
Folds the elements of a column into the places a run of indices names: element
`i` of `src` goes to place `index[i]` of the result, and elements that meet in
one place are combined by the `FOLD` specialization (`add`, `min`, `max`,
`mean`, `set`). `T` is the scalar a lane holds (`f32` or `i32`); an element is
`lanes` words. Alongside the result the kernel counts the elements folded into
each place (`hits`) and records one more than the greatest source index that
reached it (`last`, 0 when none), so a node can tell a place nothing reached from
one that holds zero. `set` keeps the element with the greatest source index, and
a place nothing reached holds zeros. An index outside `0` to `size - 1` is
skipped.
It runs as three passes of one shader, `init`, `fold` and `finish`, chosen by the
`PASS` specialization. Min, max, set and every integer fold give the same answer
whatever order the contributions arrive in. Float add and float mean sum in
arrival order, and the kernel declares `float_order` for them; with `EXACT` on,
each float is rounded to a multiple of `1 / scale` and summed as an integer,
which is the same on every run.
Over a live count (`COUNT=device`, see the abi README) the fold pass's `n` is the capacity of the indices and the first
`domain_count` of them are folded; an index past it reaches no place. The `init` and `finish` passes run over the places
(`size`) as they always do, and a node that sizes the places by a capacity states the live indices through the fold
pass alone. It binds 6 storage buffers (5 in the plain variant).
Over live places (`SIZE=device`) the places are the first `size_count` of the `size` the outputs are allocated for: the
node bound `size` as `{ live = count }`, and the `init` and `finish` passes leave the places past it alone while the `fold`
pass sends an index past it nowhere. The result carries the count as its live count. It binds one storage buffer more.
`core.scatter` runs the three passes.
▲ 0↑ born
# 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`.
▲ 0↑ born
# 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.
▲ 0↑ born
# shapes
The analytic shapes a ray is met against, shared by `fx_ray_shapes` and the particle solver's step kernel so both answer one
definition (`ray_shapes` holds the same functions in its own text, which the job form of a program takes whole): `plane_cand`, `sphere_cand`, `box_cand`, `capsule_cand`, and `shape_cand_of(kind, c, e, q, o, d,
tmin, tmax)` for one row of a table of shapes (kind 0 plane through `c` with unit normal `e`, 1 sphere of radius `e.x`, 2 box of
half size `e`, 3 capsule along y of radius `e.x` and caps at y = -`e.y` and `e.y`; boxes and capsules turned by the quaternion
`q` about `c`). A candidate is `Cand { t, n }`, `t` -1 for no hit and `n` outward. `shape_face(n, d)` turns the normal against the
move and `shape_hit_end(o, d, t, n, push)` is where the move stops, the hit pushed out by `push`.
```wgsl
#include "@builtin::systems.procgen.kernels.shapes"
fn floor_hit(o: vec3<f32>, d: vec3<f32>) -> Cand {
return shape_cand_of(0, vec3<f32>(0.0), vec3<f32>(0.0, 1.0, 0.0), vec4<f32>(0.0, 0.0, 0.0, 1.0), o, d, 0.0, 1.0);
}
```
▲ 0↑ born
# 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`.
▲ 0↑ born
# tile_layout
How a field of cells is stored as tiles: a tile holds its core cells plus an
apron of copies of its neighbours' cells, and a tile covering the whole field
with no apron is a plain grid with x fastest. The includer states the layout as
a `ZtLayout` (`cells`, `core` and `apron`, each a `vec3<i32>` per axis, and
`lanes`, the f32 values a cell holds) and uses `zt_decode` (stored cell number to
tile, local and field cell, a `ZtStored`), `zt_owner_index` (the core cell that
owns a field cell; a cell past the field reads the edge cell),
`zt_neighbour_index` (a stored neighbour held to the tile's edge) and
`zt_stored_total` (the stored cells of the whole field, apron copies included).
`zt_tiles`, `zt_stored`, `zt_tile_volume`, `zt_tile_count`, `zt_stored_index` and
`zt_inside` answer the sizes and indices those are built from. The `grid` kernel
includes it.
```wgsl
#include "@builtin::systems.procgen.kernels.tile_layout"
```
▲ 0↑ born
# 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`.
▲ 0↑ born
# 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.
▲ 0↑ born
# walk_advance
`zero_walk_advance(s)`: a walk state advanced by the constant vector (dx, dy, dz, dw), read from the includer's
params `dx`, `dy`, `dz` and `dw`. It is the default `WALK_STEP` of the `walk` kernel, which declares those params:
a walker's path is a straight line, and after k steps it stands at its start plus k times the vector.
▲ 0↑ born
# walk_core
The loop a walk kernel runs for one walker: load its state (up to 8 floats, held as two vec4), call
the step hooks for each of `steps` steps (stopping when the stop hook says so), write the state
after every step to the walker's path rows, and write the end state and the number of steps that
ran. The includer defines `zero_walk_lo`, `zero_walk_hi` and `zero_walk_stop`, and calls
`zero_walk_run` from its entry point; the module header lists the bindings and params the includer
declares.
▲ 0↑ born
# Nodebox (asset type)
A nodebox is a namespace folder that groups related `.procNode/` children, the way a toolbox groups
`.tool/` children. A node's name is its folder name inside its box: `points.nodebox/disc.procNode` is
called `points.disc`, and nothing inside the node states that name. Moving or renaming a node is a VFS
move that keeps its guid.
## Where it lives
- Source: `<anywhere>/<family>.nodebox/`, usually inside a `.package`, an effect or a world's content.
- Identity: the folders above it and `<family>` (`fx.points` for `fx/points.nodebox`; the `.nodebox`
suffix strips). A graph calls its nodes by `<family>.<node>` alone.
- Folder shape (open child set):
- `README.md`: what the family is for. Required.
- `.metadata`: description and tags. Required. It also states where the box's nodes work: `context` (one of
`proc.registry.contexts()`: `geometry`, `field`, `value`, `sim`, `raster`, `material`, `prefab`) and, when every
node of the box reads the scene or assets beside its inputs or writes them beside its outputs, `pulls` /
`pushes` (`scene` or `asset`). A node that works elsewhere states its own in its `.metadata`.
`procgen` `describeNode` and the `context`, `pulls` and `pushes` filters of `searchNodes` read them.
- `<node>.procNode/`: any number of nodes.
## How a graph reaches a node
`g.<family>.<node>(args)` resolves the node by its asset identity: the box and the folder name together
(`g.points.disc`), a path (`g["/zero/source/fx/ring.procNode"]`), `~` (the nearest enclosing package,
effect or world root: `g["~/ring"]`) or a short name the asset system resolves (`g.disc`). A name that
matches two nodes is an error naming both; a name that matches none is an error naming the closest nodes.
Each call is recorded in the graph's reference table by the node's guid.
## How to create one
```luau
asset.create("nodebox", "points", { folder = "fx" })
local box = asset.resolve("points.nodebox")
asset.create("procNode", "disc", { into = box })
```
## Discovery
- `asset.list("nodebox")`: every box.
- `asset.inspect("points")`: the nodes in it and what each does.
- `asset.list("procNode")`: every node, in or out of a box.
## In the Inspector
Nodes: how many nodes the box holds, each node's full name and what it does, and a link to each.
▲ 0↑ born
▲ 0↑ born
# component (nodebox)
component.set gives every element of a class a component with the fields given.
▲ 0↑ born
# core
The parts the other procgen nodes are built from: connectivity (edges, boundary, adjacency, islands, owner, corners), normals, weld, select, stitch, curve measure and resample, sampling, neighbours, realize, the raster set (`raster.new`, `raster.read`, `raster.stencil`, `raster.sample`, `raster.add_layer`, `raster.remove_layer`, `raster.reduce`, `raster.column`, `raster.resolve`, `raster.blend`, and `raster.cells` under them), `column`, and `entity.read`, which brings scene entities in (assets come in through `io.import`).
Each is a graph of the four ops, the kernels of `kernels/` and other core nodes. `join` holds the module that places the parts of a join, called by `concat` and `realize`.
A graph calls them as `g.core.<name>`, for instance `g.core.edges`. A node with several outputs answers a record: `local faces = g.core.normals.face(...)` then `faces.geometry`, `faces.scaled`. Every node's README states its inputs and outputs.
▲ 0↑ born
▲ 0↑ born
# debug (nodebox)
debug.dump summarizes any graph value into a record; debug.validate checks a Geometry's structure and reports every issue it finds.
▲ 0↑ born
▲ 0↑ born
# entity (nodebox)
entity.transform and entity.bounds read one entity's pose and bounds as values, entity.points reads a set of entities as points, and entity.geometry reads the mesh an entity's Model draws as a Geometry.
▲ 0↑ born
▲ 0↑ born
# geometry
Nodes that move, join, cut, round, thicken and sample meshes. A graph transforms a geometry (`geometry.transform`, `geometry.set_position`, `geometry.merge`), welds and shades it (`geometry.weld`, `geometry.smooth_normals`), models it (`geometry.extrude`, `geometry.solidify`, `geometry.bevel`, `geometry.subdivide`, `geometry.decimate`), builds surfaces from outlines (`geometry.sweep`, `geometry.revolve`, `geometry.loft`, `geometry.ribbon`) and reads it into volumes (`geometry.voxelize`, `geometry.to_sdf`). Each is built from the core nodes and the kernels of the library.
## Nodes
- `geometry.transform`, `geometry.set_position`, `geometry.set_material`, `geometry.merge`, `geometry.triangulate`, `geometry.measure`: the basic edits and the measurement of a geometry. `geometry.merge` also joins pieces into a piece set for `instances.to_points`; a part that lacks an attribute another part carries takes the value an element without it has: an instance attribute's identity, else zero (its README says exactly how).
- `geometry.weld` (with `match = "position+normal"` it keeps hard edges), `geometry.smooth_normals`: merging points and shading normals.
- `geometry.extrude`, `geometry.solidify`, `geometry.bevel`, `geometry.subdivide`, `geometry.decimate`: modelling.
- `geometry.sweep`, `geometry.revolve`, `geometry.loft`, `geometry.ribbon`: surfaces from outlines and paths.
- `geometry.voxelize`, `geometry.to_sdf`: a mesh as cells and as a distance field.
- `geometry.boolean`: union, subtract or intersect of two closed meshes, over the `intersect` kernels.
- `geometry.delete`, `geometry.separate`: the triangles a mask field or primitive attribute selects, taken away or split into two geometries (`elements.keep` on the primitives); `geometry.recalculate_normals`: `geometry.smooth_normals` at 180 degrees, area-weighted.
- `geometry.selected`, `geometry.flip`, `geometry.profile`, `geometry.tangents`, `geometry.sides`, `geometry.shared`, `geometry.bvh`, `geometry.rings`, `geometry.first`: the parts the nodes above are built from, each usable on its own.
- `geometry.unit`, `geometry.perpendicular`, `geometry.rotate`, `geometry.transport`, `geometry.split`: vector arithmetic over sockets that the nodes which orient points and normals share.
- `geometry.offsets`, `geometry.kept`, `geometry.following`, `geometry.trim`, `geometry.blank`: column arithmetic the nodes above share (a prefix sum of counts, the places a mask keeps, a ring read one place on, the primitives of no area dropped, a one-word column to bind).
## Conventions
- Each node's folder name is its call name inside the box: `geometry.<folder>`.
- Inputs and outputs carry the names of the op each node replaces.
- A node that answers a Data table from numbers read back off the device holds the Luau for it in a `readings.module` inside its own folder.
- A node with one output answers that output's value; a node with several answers a record by output name.
- A fold's index runs from 1: the first pass is 1, so a pass that works on level, chunk or step `n` reads `index - 1` when it counts from 0 (`geometry.bvh`, `geometry.to_sdf`, `geometry.sweep`, `geometry.loft`).
- A field bound to a kernel takes the length of that dispatch, so a node writes a value out as a column (a gather with an explicit `count`) before it binds one whose length differs from the dispatch's.
▲ 0↑ born
▲ 0↑ born
▲ 0↑ born
# instances (nodebox)
Instances: pack a geometry into a piece (instances.pack), place a piece set on target points (instances.to_points) and take a population or piece set apart (instances.unpack). A piece is one point whose `Mesh` holds a geometry whole, as the node that made it left it: a geometry whose elements are counted on the device (what `geometry.triangulate` makes) keeps its counts there, and draining the piece set (`Geometry.drain`) drains the geometries its records hold with it, so a CPU reader reads each piece's elements; `geometry.merge` with `pack` puts several together into a piece set. The copies `instances.to_points` makes are a population, which the output node draws as instanced draws, one per piece and material, and export saves as a population asset; any other points stand as one entity each. A piece keeps the material it was packed with: copies of a set of several pieces index the records `detail.labels.Mesh` lists, each record stating its piece's material as `material` and the most copies of the piece there can be as `capacity`, and a copy that carries a `Material` of its own (its target point's, or the one `to_points` was given) wears that instead. Each piece's draw reserves that many slots. With `match` on and the target points' values read where the node cooks, a piece's `capacity` is the number of target points holding its value, so the draws of a population of several pieces together reserve its matched copies' slots; target points the device rewrites as time moves state one per target point for every piece. Populations merged with `geometry.merge` stay one population: its copies draw as one instanced draw per distinct piece and material among them, the same as one `to_points` of all the pieces.
instances.pack, instances.to_points and instances.unpack are the nodes of that chain, with `points.pose` composing the instance attributes (`P`, `orient`, `scale`, `N`, `v`, `up`, `pscale`, `rot`, `trans`, `pivot`) the copies stand at. Target points merged from parts that did not all carry an instance attribute hold its identity on the points that lacked it (`geometry.merge`: `scale` and `pscale` 1, `orient` unrotated), so each part's points pose as they did alone.
instances.from_elements makes a piece set from elements: the entities `io.import` answers, or any points carrying `parent` and a pose. Every element that draws becomes a piece holding its mesh asset and material, posed through its parents, and the detail `bounds` is the box the pieces span. It is the inverse of `instances.unpack` with `op` "elements".
instances.cull keeps the instances a mask field or point attribute reads above a threshold (or, inverted, the rest), every attribute coming along.
Earlier nodes of the nodebox stand a source on points (instances.on_points), deal one of several sources to each point (instances.pick_random, instances.pick_by_attribute), vary and move the copies (instances.randomize_transform, instances.transform, instances.set_material) and merge them into one geometry (instances.realize). The points they make carry a `Mesh` and stand as entities through the output node.
instances.place, instances.variants, instances.turn and instances.sources are the parts the others are built from: a transform written onto points, a variant index written onto points, the product of two rotations, and the geometries a population stands (the ones given, else the ones its points carry).
▲ 0↑ born
# io
The ways in and out of a graph: `import` brings an asset in as the value its type states, `luau` runs a function of a Luau module on the CPU, `output` shows a value in the world and answers a Handle, `export` saves a value as an asset, and `engine` calls the engine bridge that `import`, `export` and the core reading nodes use. `output` holds `show.module` and `engine` holds `engine.module`, the functions they call.
▲ 0↑ born
# material (nodebox)
Materials as records: material.pbrMat is the standard metallic-roughness material made from its PBR maps (base colour, metallic-roughness, normal, occlusion, emissive) and their factors, and material.shader a material of any surface shader, holding every property and slot to what the shader declares. Each answers one element holding the record of the material kind (`records/material.procRecord`), which geometry.set_material, instances.set_material and the other inputs that take a material put on what draws; the output node shows it and the export node saves it as a `.material`.
▲ 0↑ born
# math
One node per operator and per function of Luau's `math` table that is a function of its numbers alone: add, sub, mul, div, mod, pow, neg, abs, min, max, floor, ceil, round, sqrt, sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, exp, log, log10, fmod, ldexp, frexp, modf, noise, map, sign, deg, rad, clamp, lerp, smoothstep, isnan, isinf, isfinite, length, normalize, dot, cross, vec2, vec3, vec4, the comparisons (lt, le, gt, ge, eq, ne, and `compare` over them), `where`, the integer functions (to_int, to_float, bor, bxor, shl, floordiv), and `concat` for text. `math.random` and `math.randomseed` have no node: they draw from state outside the graph, a graph that called one would cook differently each time, and a call of either in a graph is refused, naming `field.rand`, `field.random` and `rand.unit`, which draw from a seed.
Operators and `math.*` over sockets resolve to these nodes, and `vector.create` over sockets resolves to `math.vec2`, `math.vec3` or `math.vec4` by its component count; with plain numbers only, `math.*` and `vector.create` are Luau's own, and `vector.create` holds three components. Each node but `compare` (built from the comparisons) and `concat` (text) calls an operation of `proc.fieldc.operators`: over plain numbers and vectors it answers the plain result, over a Column or a Field it answers a Field (a fieldc template), so a chain of math nodes is one expression that the node consuming it evaluates in a single dispatch (`fieldc.evaluate`).
`math.min` and `math.max` over sockets take any number of operands, folded two at a time; `math.log(x, base)` is the `log` node with its `base`. Operands of different widths widen to the widest: a number applies to every component, and a shorter vector reads 0 for the components it lacks. Division, `floordiv`, `mod` and `fmod` by 0 answer 0, `sqrt`, `log` and `log10` of a value at or below 0 answer 0, `asin` and `acos` of a value past -1 or 1 read the nearest of the two, and `map` over an input range of no width answers its output minimum, so a chain keeps producing numbers. The orderings (`lt`, `le`, `gt`, `ge`) compare first components; `eq` and `ne` compare every component.
▲ 0↑ born
# mesh
The primitive solids and sheets a graph starts from: `mesh.box`, `mesh.sphere`, `mesh.cylinder`, `mesh.cone`, `mesh.capsule`, `mesh.octahedron`, `mesh.torus`, `mesh.rounded_box`, `mesh.plane` and `mesh.grid`. Each is made on the device from lattices and fans of the `make` kernel, with positions, normals and texture coordinates written as formulas over the lattice, and answers triangles centred on the origin that fill the box its parameters name.
## Conventions
- Each node's folder name is its call name inside the box: `mesh.<folder>`.
- Parameters keep the names and defaults of the op each node replaces.
- `mesh.lattice` makes the lattices and fans the presets share, `mesh.spherical` the point of a sphere and `mesh.cube_faces` the faces of a cube; a preset writes its positions, normals and texture coordinates as formulas over the lattice.
▲ 0↑ born
# part (nodebox)
part.merge packs several values into one part, each piece keeping what it is; part.unpack gives one piece back by its name.
▲ 0↑ born
▲ 0↑ born
# prefab (nodebox)
Prefabs: the entity records a spawned hierarchy is made of, as record and list values. prefab.empty makes a root, prefab.entity, prefab.parent, prefab.add_component and prefab.link shape the hierarchy (each calls prefab.edit, which holds the record-list edits and the name lookup that prefab.find answers), and prefab.from_geometry, prefab.from_geometries, prefab.from_instances, prefab.from_population and prefab.from_asset make prefabs from what a graph built. The output node shows a prefab and the export node saves it as a bundle.
prefab.record and prefab.find are the parts the others are built from: one entity record, and a lookup of an entity by name.
▲ 0↑ born
▲ 0↑ born
# scene (nodebox)
scene.query finds entity ids by name, component and hierarchy, scene.fetch brings entities in as points carrying their pose and components, scene.input is the entity the graph stands on, and scene.water is the water the scene holds.
▲ 0↑ born
# sdf (nodebox)
Signed distance field nodes: shapes, smooth combines, round and shell, space warps (transform, twist, bend, taper, elongate, mirror, repeat), displacement, grids and fields in and out, and sdf.mesh, which contours a shape into a closed mesh.
▲ 0↑ born
# shader (nodebox)
An author's own compute shaders as nodes. shader.compute runs a .computeShader over the elements of a geometry through the device.kernel op: each buffer binding is a column of the geometry, each param a knob of the node, and what the shader writes comes out as columns.
▲ 0↑ born
# sim (nodebox)
Simulation nodes: sim.spawn, sim.force, sim.collider, sim.scene_colliders, sim.particles and sim.shader, built on the runtime's g:state and g:step. sim.particles measures how far each source's points moved between presents, so a moving source births along its path and by the distance it travelled, and sim.flipbook writes the lanes a texture-sheet shader reads to play a sheet over each particle's age.
▲ 0↑ born
# texture (nodebox)
Textures: images drawn on the device as Texture values, a width, a height and one colour per texel. texture.noise and texture.gradient draw from a formula, texture.from_shader from an author's compute shader and texture.from_raster from the layers of a raster. A Texture is a record of `width`, `height`, `format` (`"rgba32f"`) and `texels`, one Vec4 colour per texel row by row from the top left, held on the device. A material takes a Texture in a slot, io.output shows one, and io.export saves one as a texture asset.
texture.cells is the part all four are built from: one point per texel carrying its column and row.
▲ 0↑ born
▲ 0↑ born
# value (nodebox)
Single values in a graph: value.math and value.compare do arithmetic and comparison with the operation picked by a parameter, value.expr follows a Luau expression over the graph's clock, value.get reads one field of a record by a dotted path, and value.switch picks one of two values by a Bool. value.present and value.fallback are how a graph used as a node handles an input its caller may leave unwired: present answers whether anything is wired, fallback takes the wired value or a fallback.
▲ 0↑ born
# proc
Code-authored, graph-backed procedural generation for the Zero engine.
A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by
family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`,
the returned table is the graph's outputs, and `io.output` is how the graph stands in the world.
`builder.module/README.md` holds every rule of that form.
This module owns the whole procedural model: the graph builder + data model,
the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op
implementations. Authored `.procGraph` graphs are persisted via
`procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in
`procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)`
from a script or an agent's `tool_exec` script, or `zero procgen preview` in the
shell. Generated
meshes/materials/textures/bundles are persisted through their own `.assetType`.
An op family can also come from outside this package: a `.procPack` asset
registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones
shipped here (`proc.registerPack(name, ops)` is what it registers through, and
what a test or a tool calls to hold a family for the life of one VM).
`terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/`
and covering a whole landscape; `guides { path =
"systems/terrainSystem/documentation/terrain" }` is its guide.
To find out what the registry holds, use the `procgen` toolbox: `searchNodes`
searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and
`proc.schema(id)` are the same answers in-process, for a graph builder looking
something up while it runs.
▲ 0↑ born
# procGraph (asset type)
A `.procGraph` asset is a **procedural graph**: a description of how to make
something, written as code, that can be evaluated over and over with different
numbers. Its `init.luau` returns `proc.define(...)` — that source IS the asset,
the way a `.procNode`'s `init.luau` is.
## Shape
A `<name>.procGraph/` folder containing:
- `init.luau`: the graph's definition. Returns `proc.define(function(g) … end)`, the graph named by its asset folder.
- `graph.json` — the compiled form (`proc.graph.v1`), written by this type from
`init.luau`. Generated, never hand-edited.
- `README.md`, `.metadata` — the universal asset files. The type writes the
graph's description and kind into `.metadata` on every compile.
- `layout.json` (optional) — where the Inspector's node editor draws each node.
- `preview.png` (optional) — the graph's rendered still, which search shows.
`asset.create("procGraph", name)` scaffolds `init.luau` (a box with a `size`
input, shown through `g.io.output` and returned as `mesh`), `README.md` and
`.metadata`, and the first compile writes `graph.json`.
## Authoring
Edit `init.luau`. The type recompiles on the write, rewrites `graph.json`, and
every live `Generator` bound to the asset re-cooks from it — there is no build
step between saving and seeing the result.
A graph is built from more than its `init.luau`: a module the source requires
while it builds (`onDependencyChange`), a file it reads with `vfs.read`, and a
file a module it calls reads with `proc.read` are part of it, and so is every
node it calls. When one of them changes, every `Generator` standing on the graph
builds it again and cooks it on its next frame; nothing is written to the world
for it.
A recompile is cheap however large the graph: node results are keyed by content,
so recompiling an unchanged node reuses its cooked output, and an edit
invalidates only that node and the ones downstream of it. Changing the last step
of a landscape does not re-run the erosion above it.
Two words worth keeping apart, because both happen here:
- **compile** — `init.luau` → `graph.json`. Produces the graph.
- **cook** — each node performing its operation to produce a value. Runs the
graph. Driven by a `Generator`, reported by `procgen.cooks`.
## Using one
Through the ref rather than a path string: `ref:eval("mesh")` evaluates an
output (`"output:mesh"` and `"node:<id>"` are targets too, and
`ref:eval("mesh", { inputs = { size = 3 } })` overrides inputs for the call),
`ref:inputs()` lists the knobs a Generator can override by name
(`{ [name] = { type, default, min?, max?, ... } }`), `ref:outputs()` the sorted
output names, `ref:validate()` type-checks it (an empty list when it is
well-typed), and `ref:asOp()` wraps it so another graph can composite it as a
node. `ref:graph()` builds the graph from `init.luau`; `ref:compile()` compiles
it now and answers `{ id?, nodes, out }`; `ref:instantiate(target?, { params?, output?, ... })`
puts it in the scene on a `Generator`; `ref:promote(opts?)` makes it a
`.procNode`; `ref:preview(opts?)` renders its still and `ref:stillTime()` names
the moment that still shows.
Generated outputs (meshes, materials, textures, bundles) are persisted through
their own asset types.
## Related
- `@builtin::systems.procgen.proc` — the authoring + evaluation model.
- `procgen.toolbox` — `preview`, `spawn`, `bake`, `validate`, `searchNodes`,
`describeNode` and the wider tool family.
## In the Inspector
The Inspector shows the graph as nodes and wires, and edits it there. Every graph input,
op, graph used as a node and output is a node; each input port that nothing is wired into
carries the value that drives it, and a click on a value edits it where it stands (typing,
dragging a number, flipping a switch, choosing from a list). Drag a node to move it, drag
from a port to another port to connect, drag a connected input away to take its wire off,
Delete removes the selection. A node is added from the op search under the graph, or from
the procGraph assets, which stand as nodes that open their own asset on a double click. The
graph's inputs and outputs are nodes too: their name, type, default and range, and an
output's domain, are values on them, and the Inputs and outputs section declares new ones.
Describes is the sentence search finds the graph by. The Graph section also carries
**Compile**, which compiles the graph now, and a link that opens `init.luau`.
Every edit is written into `init.luau` with `proc.saveSource` and compiled by the type, so a
live Generator re-cooks on it; the node positions are kept beside the graph in `layout.json`.
The Result section scrubs the timeline of a graph that has one and shows what the selected
node makes (`procgen.preview` with the target `node:<id>`), and the Preview section above it
shows what the graph makes, live. The Node section describes the selected node.
▲ 0↑ born
# procNode: one reusable step of procedural generation
A `.procNode` is a node authored as content: a folder whose `init.luau` is the node. It
returns `proc.define(function(g) ... end)`, the same function-of-`g` form a `.procGraph` is
written in, so a node is a small graph that other graphs call. Its `g:describe` text says
what it makes and when to use it, its `g:input` declarations are what a call passes, and
what it returns (or declares with `g:output`) is what the call gives back.
```
MyNode.procNode/
init.luau -- the node
README.md -- what it produces, its inputs, its outputs
.metadata -- description and tags
```
## What a node states
- **`g:describe(text)`**: what the node produces and when to use it. It is the text search,
the node catalogue and the Inspector show.
- **`g:input(name, default, opts)`**: one input of the node. The default types it (`Float`,
`String`, `Bool`, `Vec3`, `Color`, `List<T>`, `Record`); `opts` adds `type` (for a default
that does not state one, or none), `description`, `options`, `min`, `max` and `optional`. A
call names inputs in a table, or passes them in declaration order.
- **Outputs**: the returned table names them (`return { geometry = geometry }`), and
`g:output(name, value)` declares one as the node builds. A node with one output answers
that value to its caller; a node with several answers a record by output name; a node with
none answers nothing.
- **Written as literals.** What a node takes and gives is read from its source without running
it, the way search and description read it here and the way ZeroMind reads it, so each
declaration states its values as written: `g:describe` and each `g:input` once, at the top
level of the function, with a literal name, default and options (a file constant holding a
literal, or `asset.resolve("<identity>", "<type>")`, reads as one); outputs named by the table
the function returns, or by `g:output`, the same names on every branch of a condition and never
inside a loop. `asset.interface(node)` answers what the source declares, with each part it
cannot read as a problem, and a push refuses a node with such a problem
(`interface.unreadable`).
- **The body** is the node's work: calls to other nodes, arithmetic over sockets, `for`, folds,
steps and state, as the builder README (`proc.module/builder.module/README.md`) describes.
A node that uses another node is recorded in the graph that calls it, so a node can be built
from nodes.
## How a graph calls a node
A node inside a `<family>.nodebox` is called by its box and folder name:
`points.nodebox/disc.procNode` is `g.points.disc({ ... })`, and nothing inside the node states
that name. A node is also reached by:
- its path (`g["/zero/source/fx/ring.procNode"]`),
- `~`, the nearest enclosing package, effect or world root (`g["~/ring"]`),
- its guid,
- a short name only one node answers to (`g.disc`).
A name that matches two nodes and a name that matches none are errors that name the
candidates. Each call is recorded in the calling graph by the node's guid, so the node travels
with every graph that uses it, and a rename or a move keeps the reference. A `.procGraph` is
called the same way and answers what it returns.
## Nodeboxes
A nodebox is the family a node lives in: a namespace folder grouping related nodes (`points`,
`mesh`, `field`, `terrain`). `nodebox.assetType` describes it. A node placed in a box takes the
box's name as its prefix; a node outside any box is reached by path, `~` or guid.
`asset.create("nodebox", family)` makes a box and `asset.create("procNode", name, { into = box })`
makes a node in it.
## Finding nodes
`asset.list("procNode")` lists the nodes this world can reference. The `procgen` toolbox's `searchNodes` finds them by
meaning across every published node, and with no query lists the ones this engine holds grouped
by family; its `describeNode` answers one node's inputs, their types and defaults, and its
outputs. Both read what each node's source declares and run no node. The type's `indexing`
recipe embeds a node's README and its source, so a search by meaning finds a node by what its
description and README say it is for: write them in the words someone looking for the node
would use.
## Registration
Every node the asset index lists is known to the procgen registry by what its source declares,
read when it is asked for and read again when the source changes; nothing runs a node to list
it. Its code loads the first time a build runs it. After that, the lifecycle hooks keep it
current: `onChange` loads it again and hot-reloads on an edit, `onDelete` removes it. Editing
`init.luau` cooks again every graph that reaches the node, and only the nodes downstream of the
change do work. `init.luau` is compiled from its current source on each load, so a module it
pulls in uses an absolute require
(`require("@builtin::systems.procgen.proc")`).
What a node is built from is more than its own file. A module its `init.luau` requires while it
builds, at any depth of requires, is part of it: when that module changes, `onDependencyChange`
loads the node again from the module as it now stands. A file its `init.luau` reads with
`vfs.read` while it builds is part of it too, and so is a file a module it calls reads with
`proc.read` (a module's own `vfs.read` is its own and makes no dependency). Writing such a file
loads the node again (`proc.sourceChanged`). Either way the node's definition moves, so every
graph and Generator reaching it cooks again, from one version of everything it was built from.
`proc.builder.readsOf("<node>.procNode/init.luau")` lists the files its last build read. A graph that references a node which is not
registered errors at load, naming the missing guid. A graph that reaches itself, directly or
through other nodes, errors at cook.
## Content requirements
`README.md` carries real text: what the node produces, its inputs and its outputs. `.metadata`
carries a `description` (what the node computes and the value type it answers) and `tags` (the
family, so search finds it). It may state where the node works: `context`, `pulls` and `pushes`
(the values `proc.registry.contexts()`, `"scene"` and `"asset"` name). A node in a nodebox that
states none takes its box's; `procgen` `describeNode` and `searchNodes` answer them.
A node written with `proc.graph` and `g:node` (the `procNodes/` of the procgen package) is called only
by a `proc.graph` graph, through `g:node`. A graph built with `proc.define` does not call it: `g.op.<name>`
of it is refused where it is written, naming the node written in the call form that answers to the same name.
## In the Inspector
Operation: the node's id and what it does, its cost and caching when it declares them, and its
inputs and outputs, from the procgen registry's schema for it. A node that did not register says
so.
▲ 0↑ born
# field.distance (procNode)
How far each element's position is from a target, as a Float field. It makes the target the wired `b` field or,
when `b` is left unwired, the fixed `point` as a constant field (`value.fallback`, `field.constant`), then
measures with `field.vector_math` in `distance` mode from `a` to that target. The result compiles to the device with
the rest of the field chain.
## Inputs
- `a` (`Field<Vec3> | Vec3`): the positions being measured, one per element.
- `b` (`Field<Vec3> | Vec3`): what each element is measured to, per element, so the target can move with the
element. Wired, it stands in for `point`.
- `point` (`Vec3`, default `{ 0, 0, 0 }`): one fixed position every element is measured to when `b` is unwired. It is
how a radial falloff around a place is built.
## Outputs
- `field`: the distance, a Float field.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "field.distance", ...)`. A graph built with `proc.define` calls `g.field.distance` in its place, the node written in the call form; `g.op.field.distance` there is refused, naming it.
▲ 0↑ born
# field.ramp (procNode)
A ramp read at every element by a value it carries: a particle's colour, size or opacity following its age. It takes
the value each element reads by (the wired `t`, else the element's own `by` attribute, through `value.fallback` and
`field.attribute`), maps it from `range` onto 0..1 (`field.map_range`, the ends read off `range` by `value.get`), and
reads the ramp there with `ramp.sample`, compiled into the element's dispatch. A value past either end of `range` reads
that end of the ramp.
## Inputs
- `ramp` (`Ramp`): the ramp to read.
- `t` (`Field<Float> | Float`): where along the ramp each element reads. Unwired, it is the element's own `by`
attribute.
- `by` (`String`, default `"life"`): the Float attribute each element reads the ramp by when `t` is unwired. A particle
solver's particles carry `life`, 0 at birth to 1 at death.
- `range` (`Vec2`, default `{ 0, 1 }`): the values of `t` that land at 0 and at 1 on the ramp, so a speed from 0 to 20
or a temperature from 300 to 3000 reads the whole ramp.
## Outputs
- `field`: the ramp's value at each element.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "field.ramp", ...)`. A graph built with `proc.define` calls `g.field.ramp` in its place, the node written in the call form; `g.op.field.ramp` there is refused, naming it.
▲ 0↑ born
# geometry.delete (procNode)
Deletes the triangles a test selects. A triangle is selected when its value is strictly above `threshold`. The value
each triangle is tested by is the `mask` field when it is wired, else the named primitive `attribute`
(`field.attribute`), else 0. `invert` deletes the triangles the test did not select. `elements.keep` on the primitives
does the removal: every point stays, and the triangles that remain keep their corners and attributes, counted on the
device.
## Inputs
- `geometry` (`Curves | Surface`): whose triangles are thinned. Point and detail attributes carry over as they are;
primitive and vertex attributes stay with the triangles that survive.
- `mask` (`Field`): read once per triangle for whether it goes. Wired, it is what the selection reads, and `attribute`
is read only when this is empty.
- `threshold` (`Float`, default 0.5): a triangle is selected when its value is strictly above this. Raising it deletes
less.
- `attribute` (`String`): a primitive attribute on the geometry to read the selection from, instead of a wired mask. A
name the triangles do not carry is refused.
- `invert` (`Bool`, default false): true deletes every triangle the test did not select, so a mask naming what to keep
cuts away the rest.
## Outputs
- `geometry`: the geometry with the selected triangles removed.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "geometry.delete", ...)`. A graph built with `proc.define` calls `g.geometry.delete` in its place, the node written in the call form; `g.op.geometry.delete` there is refused, naming it.
▲ 0↑ born
# geometry.recalculate_normals (procNode)
Every vertex's normal averaged, by area, over the faces meeting it. The node is `geometry.smooth_normals` with a
crease angle of 180 degrees and area weighting, so no vertex splits: a vertex shared by two faces is smooth across
them, and one already split between two copies stays a hard edge.
## Inputs
- `geometry` (`Geometry`): whose surface the normals are read off. Attributes and material carry to the result.
## Outputs
- `geometry`: the geometry with recomputed per-vertex normals.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "geometry.recalculate_normals", ...)`. A graph built with `proc.define` calls `g.geometry.recalculate_normals` in its place, the node written in the call form; `g.op.geometry.recalculate_normals` there is refused, naming it.
▲ 0↑ born
# geometry.separate (procNode)
Splits a geometry's triangles in two by a test. The value each triangle is tested by is the `mask` field when it is
wired, else the named primitive `attribute` (`field.attribute`), else 0. Two comparisons against `threshold` follow
(`field.compare`): strictly above, and at or below. `elements.keep` on the primitives runs once for each, so `a` holds
the triangles above and `b` the rest. Both keep every point, and between them they hold every triangle once.
## Inputs
- `geometry` (`Curves | Surface`): whose triangles are divided. Point and detail attributes carry to both halves as they
are; primitive and vertex attributes stay with each half's own triangles.
- `mask` (`Field`): read once per triangle for which half it joins. Wired, it is what the split reads, and `attribute`
is read only when this is empty.
- `threshold` (`Float`, default 0.5): a triangle goes to `a` when its value is strictly above this, and to `b`
otherwise.
- `attribute` (`String`): a primitive attribute on the geometry to read the split from, instead of a wired mask. A name
the triangles do not carry is refused.
## Outputs
- `a`: the triangles whose value is strictly above `threshold`.
- `b`: the rest. A call answers both as a record by output name.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "geometry.separate", ...)`. A graph built with `proc.define` calls `g.geometry.separate` in its place, the node written in the call form; `g.op.geometry.separate` there is refused, naming it.
▲ 0↑ born
# instances.cull (procNode)
Keeps the instances a test says to. An instance survives when the value it is judged by is strictly above
`threshold`; `invert` keeps the rest instead. The value is the `mask` field when it is wired, else the named point
`attribute` (`field.attribute`). `elements.keep` on the points carries every attribute onto the instances that stay, so
a culled set realizes as the whole one would have. With nothing to judge by, every instance stays, and inverted, none
does.
## Inputs
- `instances` (`Points`): the set to thin out, points carrying a Mesh.
- `mask` (`Field`): the value each instance is judged by. Wired, it outranks `attribute`.
- `threshold` (`Float`, default 0.5): an instance survives when its value reads strictly above this. Raising it thins
the set, lowering it fills it back in.
- `attribute` (`String`): a point attribute on the set to judge by, read while `mask` is unwired. A name the points do
not carry is refused.
- `invert` (`Bool`, default false): true keeps the complement, every instance the test dropped.
## Outputs
- `instances`: the surviving instances.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "instances.cull", ...)`. A graph built with `proc.define` calls `g.instances.cull` in its place, the node written in the call form; `g.op.instances.cull` there is refused, naming it.
▲ 0↑ born
# points.box (procNode)
A 3D lattice of points filling a box centred on the origin. Each count is at least 1, and the box the cells fill is the
counts times `spacing` (`value.math`), so the points span (count - 1) times `spacing` on each axis. `grid.box` lays out the cells, x fastest, then y, then z, on the device,
and each cell's centre is one point. `attribute.remove` takes the cell layout off the detail so the lattice reads as
Points, and each point carries its own number as `id`.
## Inputs
- `countX` (`Int`, default 3): how many points along X. The lattice holds countX x countY x countZ points and stays
centred on the origin on every axis. Below 1 reads as 1.
- `countY` (`Int`, default 3): how many points along Y, the layers the lattice is stacked in. 1 collapses it to a single
flat sheet at y = 0. Below 1 reads as 1.
- `countZ` (`Int`, default 3): how many points along Z. Below 1 reads as 1.
- `spacing` (`Float`, default 1.0): distance between neighbouring points, the same on all three axes. The lattice spans
(count - 1) x spacing per axis.
## Outputs
- `points`: the lattice, with `id` numbering each point.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "points.box", ...)`. A graph built with `proc.define` calls `g.points.box` in its place, the node written in the call form; `g.op.points.box` there is refused, naming it.
▲ 0↑ born
# points.filter (procNode)
Keeps the points a test says to. The value each point is tested by is the `mask` field when it is wired, else the named
`attribute`'s values (`attribute.labels`). The test is a comparison (`field.compare`): above `threshold`, or, when
`equals` is given, equal to the index that value or label names. `elements.keep` on the points carries every attribute
and the detail onto the points that stay, counted on the device. Given neither a mask nor an attribute, the points come
back as they are.
## Inputs
- `points` (`Geometry`): the cloud to thin. Every point attribute and every detail value is carried onto the survivors,
so a colour or an index still belongs to the point it started on.
- `mask` (`Field`): the per-point value tested; a point stays when it is above `threshold`. Wired, it decides, and
`attribute` is read only when this is empty.
- `threshold` (`Float`, default 0.5): a point stays when its value is strictly above this. Raising it keeps fewer
points.
- `attribute` (`String`): a point attribute to test instead of wiring `mask`. A name the points do not carry is refused,
naming the ones they do.
- `equals` (`String | Float`): keeps the points whose `attribute` equals this instead of testing it against
`threshold`. It is a number, or a label: one of the texts a text attribute holds, or one of the names the points'
detail `labels` gives a numeric one (how one solver's particles are split back by the `stream` their source named).
## Outputs
- `points`: the points that stay.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "points.filter", ...)`. A graph built with `proc.define` calls `g.points.filter` in its place, the node written in the call form; `g.op.points.filter` there is refused, naming it.
▲ 0↑ born
# points.grid (procNode)
A flat lattice of points in the XZ plane, centred on the origin. Each count is at least 1, and the box the cells fill is the
counts times `spacing` (`value.math`), so the points span (count - 1) times `spacing` on each axis. `grid.box`, one cell thick at height `y`, lays out the cells, x
fastest, then z, on the device, and each cell's centre is one point. `attribute.remove` takes the cell layout off the
detail so the lattice reads as Points, and each point carries its own number as `id`.
## Inputs
- `countX` (`Int`, default 4): how many points along X. The grid holds countX x countZ points and stays centred on the
origin, so each one added widens it by `spacing`, half of that to either side. Below 1 reads as 1.
- `countZ` (`Int`, default 4): how many points along Z. A count of 1 leaves a single row running along X. Below 1 reads
as 1.
- `spacing` (`Float`, default 1.0): distance between neighbouring points, the same on both axes. The grid spans
(countX - 1) x spacing by (countZ - 1) x spacing.
- `y` (`Float`, default 0.0): the height the whole lattice sits at. Every point takes this as its y.
## Outputs
- `points`: the lattice, with `id` numbering each point.
## Which graph calls it
This node is built with `proc.graph` and `g:node`, and a `proc.graph` graph calls it as `g:node("<id>", "points.grid", ...)`. A graph built with `proc.define` calls `g.points.grid` in its place, the node written in the call form; `g.op.points.grid` there is refused, naming it.
▲ 0↑ born
# procPack — a family of procedural ops as content
A `.procPack` is a FAMILY of procedural operations authored as content: a
folder whose `init.luau` returns a **pack table**. When the asset registers,
every def in its `ops` map joins the proc op registry under the stable string
id the pack names it with, so a graph calls it by that id (`g.op.<id>`). Discover the
available packs with `asset.list("procPack")`, and the ops any of them
contributed with `procgen.searchNodes("", { pack = "<name>" })`.
This is the one path an op family reaches the registry through. Procgen's own
families are packs — `procPacks/` in this package holds one per family,
`abi.procPack` beside it holds the ops every node is built from, and
terrain's `terrain.procPack` sits in its own package the same way — so the
packs shipped here are worked examples of exactly what you are writing, not a
separate mechanism the built-ins are exempt from.
```
MyPack.procPack/
init.luau -- returns the pack table
README.md
.metadata
```
## The pack table
```lua
local proc = require("@builtin::systems.procgen.proc")
local function transformed(ctx: any, geometry: any, params: { [string]: any }): any
return proc.registry.get("geometry.transform").eval(ctx, { geometry = geometry }, params)
end
return {
name = "myPack", -- the asset's own name when omitted
description = "Moves and turns whole geometries.",
ops = {
["myPack.lift"] = {
description = "Lift a Geometry by a height.",
inputs = { geometry = { type = "Geometry" } },
params = { height = { type = "Float", default = 1.0 } },
outputs = { geometry = { type = "Geometry", default = true } },
eval = function(ctx, inputs, params)
return transformed(ctx, inputs.geometry, { translate = { x = 0, y = params.height, z = 0 } })
end,
},
["myPack.spin"] = {
description = "Turn a Geometry about the up axis.",
inputs = { geometry = { type = "Geometry" } },
params = { degrees = { type = "Float", default = 45 } },
outputs = { geometry = { type = "Geometry", default = true } },
eval = function(ctx, inputs, params)
return transformed(ctx, inputs.geometry, { rotate = { x = 0, y = params.degrees, z = 0 } })
end,
},
},
}
```
Each def is the same table every op in the registry is described by — typed
input sockets, params, typed output sockets, and an `eval(ctx, inputs, params)`
returning the outputs. `ctx` carries seed / nodeId / compositePath / hash /
checkpoint. Validation is the same for every pack, so a malformed socket or an
undeclared param type is refused here exactly as it is for the ones shipped in
this package.
Beside `name`, `description` and `ops`, the pack table takes:
- `context`: the context every op of the family works in (`"geometry"`,
`"field"`, `"sim"`, ...), for each def that states none of its own. A name
that is no registered context is refused.
- `aliases`: former op ids mapped onto current ones
(`{ ["myPack.raise"] = "myPack.lift" }`). A graph naming a former id cooks
the current op, while listings and schemas carry the current id. An alias
onto an id that is no registered op is refused, and so is an alias whose
former id is itself a registered op.
A graph calls a pack's op as `g.op.<id>`, with one table naming its inputs and
params:
```lua
return proc.define(function(g)
local box = g.mesh.box({})
local lifted = g.op.myPack.lift({ geometry = box, height = 2 })
return { mesh = g.op.myPack.spin({ geometry = lifted }) }
end)
```
## procPack or procNode
Both contribute nodes that a graph calls. They differ in how a node is written
and addressed:
| | `.procNode` | `.procPack` |
|---|---|---|
| contributes | one node, written as a graph (`proc.define(function(g) ... end)`) | a family of ops, each a def table |
| addressed by | the asset's identity (`g.points.disc`, a path, a guid or a short name), recorded in the graph by guid | the string id the pack names it with |
| a graph writes | `g.<family>.<name>({ ... })` | `g.op.myPack.lift({ ... })` |
Reach for a `.procPack` when the ops belong together and you want to read the
family's name at every call site; reach for a `.procNode` when one operation
stands on its own.
## Finding a pack's ops
Search embeds a pack's `README.md` and `init.luau` (the `indexing` block of `type.yaml`), so the README is
where a search by what an op does reaches it: list every op of the pack as a line of its own, the op's id and
what it does, and keep the line true when the op changes.
```
- `myPack.lift` — Lift a Geometry by a height.
- `myPack.spin` — Turn a Geometry about the up axis.
```
`procgen.searchNodes` asks for `.procNode` and `.procPack` assets together. A hit that is a pack is listed as the
ops of that pack that answer the query's words (`op.myPack.lift`, with `matched.pack` naming the pack), or as the
pack itself when none of them does.
## Registration lifecycle
`init.luau` is compiled from its own source on every registration rather than
`require`d, so an edit lands immediately. Another module is reached by its
absolute name (`@builtin::systems.procgen.proc`), and a file of the pack's own
by a relative require (`require(".helpers")`). Every op's `version` is derived
from the pack's source, unless its def declares a `version` of its own, so
editing the file re-keys the node caches of every graph that reaches any op in
the family — those graphs recook.
Editing the pack to REMOVE an op unregisters it. A graph built before the edit
that still names the op errors loudly at eval, naming the op that is not
registered, and a graph source that calls it fails to build, naming the ops
the pack still holds. Deleting the `.procPack` folder unregisters the whole
family the same way.
## In the Inspector
Operations: how many ops the pack registers, and each op's id, kind and what it does.
▲ 0↑ born
# asset
The one node an asset enters a graph through.
## Ops
- `asset` — an asset's content as a graph value, in the form its type states:
a mesh is a Surface, a texture is a Texture. The asset is read when the node
cooks.
An asset type states the conversion in the `graph` its `behavior.luau`
declares: `read(ref)` answers the value, and `write(value, name, place)`
persists a value as that asset again. The sinks that write a value back
(`mesh.write`, `texture.write`) go through the same `write`, so what enters a
graph and what leaves it are one conversion.
```lua
local rock = g:node("rock", "asset"):param("asset", "@builtin::meshes.sphere")
local heights = g:node("heights", "asset"):param("asset", "terrain_height")
```
`procgen.searchNodes("", { pack = "asset" })` lists the family and `procgen.describeNode("op.asset")`
describes it.
▲ 0↑ born
# attribute
Reading, writing and moving the per-element columns a mesh carries.
The definitions live in `proc.ops.attribute`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "attribute" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `attribute.set`
- `attribute.labels`
- `attribute.remove`
- `attribute.transfer`
- `attribute.statistics`
- `attribute.normalize`
▲ 0↑ born
# bevel
Rounding an edge or a corner into a chamfer of a chosen width and segment count.
The definitions live in `proc.ops.bevel`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "bevel" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.bevel`
▲ 0↑ born
# boolean
Union, intersection and difference between two solids.
The definitions live in `proc.ops.boolean`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "boolean" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.boolean`
▲ 0↑ born
# component
Components an element carries into the scene, their fields set from constants,
animated values or other nodes' outputs.
`procgen.searchNodes("", { pack = "component" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `component.set` — give every element of a class a component, native or
script, with its fields given by name: a constant, an animated value, or a
node's output wired in, such as the Material a `material.shader` node made.
▲ 0↑ born
# curve
Curves as geometry. A curve is a primitive of a Geometry: a run of its points,
in order, open or closed, that is a line rather than a surface. A mesh built
from the geometry draws its faces and not its curves. The curve's points are
points like any other, so every point and field op moves them. One geometry
holds any number of curves (the branches of a crack, the strands of a bolt),
and the ops that sample, sweep or grow along lines read every one.
The definitions live in `proc.ops.curves`; this pack is what puts them in the
op registry, so `procgen.searchNodes("", { pack = "curve" })` lists the family and
`procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `curve.line` — a straight curve from `start` to `finish`, in `segments`
spans.
- `curve.circle` — a closed circular curve in the XZ plane.
- `curve.bezier` — a cubic Bézier curve from four control points.
- `curve.from_points` — one curve through a geometry's points, in their order;
the points keep every attribute they carry.
- `curve.smooth` — every curve rounded into a Catmull-Rom spline through its
own points.
- `curve.resample` — every curve laid out again with points evenly spaced by
arc length, a set number per curve or as many as a spacing fits.
Move curves with `geometry.transform`, displace them with
`geometry.set_position` and a field, and join them with `geometry.append`.
`points.on_curve` samples points along them, and `geometry.sweep` carries a
cross-section along each one.
▲ 0↑ born
# data
The operations a new node is built from. Each one is a single pass over a
whole class of elements on the device. Processing data is a graph of these:
a field computes a value per element, and these ops move it, fold it, and keep
or reorder the elements.
`procgen.searchNodes("", { pack = "data" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `attribute.gather` — each element reads a column from the element its index
names, in this geometry or in a `source` geometry. Use it to read a
neighbour or a parent, or to copy values across by id.
- `attribute.scatter` — each element sends a column to the element its index
names. Every receiving element folds what reached it (sum, mean, min or
max), and an element nothing reached holds `fill`. Use it for deposits,
per-cell totals and group sizes.
- `attribute.promote` — moves a column between points, corners, faces and the
whole geometry (`detail`). Moving to fewer elements folds; moving to more
copies.
- `attribute.accumulate` — a running or total fold of a column, over the whole
class or within the groups that `by` names.
- `elements.keep` — keeps the points or faces whose value is not 0, with every
column they carry.
- `elements.sort` — puts the points or faces in the order of a value.
A threshold filter is `field.compare` into `elements.keep`:
```lua
local tall = g:node("tall", "field.compare", { a = height, b = 2 }, { op = "gt" })
g:node("kept", "elements.keep", { geometry = pts, keep = tall })
```
A total per group, standing on every member:
```lua
g:node("islandArea", "attribute.accumulate", { geometry = mesh, by = island },
{ name = "area", class = "primitive", mode = "total", as = "islandArea" })
```
▲ 0↑ born
# decimate
Reducing a mesh's triangle count while holding its silhouette.
The definitions live in `proc.ops.decimate`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "decimate" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.decimate`
▲ 0↑ born
# emit
Shapes particles are born from. Each op makes a point cloud, and each point
carries `N`, the direction pointing out of its shape. Wire the cloud into
`sim.spawn`: a particle is born on one of its points, and the source's `speed`
launches it along that point's `N`.
`procgen.searchNodes("", { pack = "emit" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `points.sphere` — points in a ball, or on its surface with `shell = 0`. `N`
points straight out from the centre.
- `points.cone` — points spread evenly across a cone's angle around an axis.
With no `length`, every point sits at the apex: a nozzle whose `N`s fan out
across the cone. A `length` fills the cone's volume out to that distance.
- `points.cylinder` — points in a cylinder, or on its side with `shell = 0`.
`N` points straight out from the axis.
- `points.on_mesh` — points scattered evenly by area over a mesh's faces. Each
point carries every attribute the mesh holds where it landed:
- point and vertex values are blended across the face;
- a face's own values come from that face;
- values that cannot be blended come from the nearest corner.
`N` is the mesh's normal there, or the face's own normal when the mesh
carries none. Particles born on a painted mesh take its colour with them.
```lua
local g = proc.graph("jet")
g:node("nozzle", "points.cone", nil, { count = 256, direction = { x = 0, y = 1, z = 0 }, angle = 12 })
g:node("src", "sim.spawn", { points = "nozzle" }, { rate = 400, speed = { x = 4, y = 7 } })
g:node("sim", "sim.particles", { sources = { "src" } })
```
▲ 0↑ born
# entity
Reading the live scene into a graph: an entity's transform, points, geometry and bounds.
The definitions live in `proc.ops.entity`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "entity" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `entity.transform` — one entity's pose, as a value.
- `entity.points` — a list of entities, or a parent's children, as ordered
points: `scene.fetch` in the world's space or under each parent, with each
entity's own `up` beside its pose.
- `entity.geometry` — the mesh one entity's Model draws.
- `entity.bounds` — one entity's bounds, or its hierarchy's.
`scene.query` and `scene.fetch` (the `scene` pack) read any number of entities,
with any of their components, in the graph's own space.
▲ 0↑ born
# extrude
Pushing faces out along their normals, and giving a surface thickness.
The definitions live in `proc.ops.extrude`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "extrude" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.extrude`
- `geometry.solidify`
▲ 0↑ born
# field
Fields: a value per element, built from position, attributes, noise and maths, sampled where an op needs it.
The definitions live in `proc.ops.field`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "field" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `field.constant`
- `field.index`
- `field.position`
- `field.normal`
- `field.attribute`
- `field.random`
- `field.noise`
- `field.math`
- `field.vector_math`
- `field.compare`
- `field.mix`
- `field.map_range`
- `field.distance`
- `field.swizzle`
- `field.combine`
▲ 0↑ born
# flow
Fields that push things around, and the noise they are made of. Each is a field
like any other: `sim.force` applies it to a solver's particles, `attribute.set`
writes it onto a geometry, and a field op combines it with others. Each also compiles to
the dispatch its CPU form computes, on the same lattice hash as `field.noise`,
so a solver evaluates it on the device at every step.
A `position` left unwired is where each element of the domain stands: the
particles a solver steps, or the points an `attribute.set` writes. Wire a
position to sample the field somewhere else.
`procgen.searchNodes("", { pack = "flow" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Fields that push
- `field.curl` — curl noise. It swirls with no sources or sinks, so what
follows it eddies without bunching up or thinning out. This is how smoke,
dust and sparks move in turbulent air.
- `field.vortex` — turning around an axis through a centre. It is strongest at
the axis and falls to half at `radius`.
- `field.attractor` — pulls toward a centre, fading to zero at `radius` when one
is given. A negative strength repels.
## Orientation
- `field.align` — the rotation turning an element's `axis` (+Y unless given)
onto a direction, as the quaternion `orient` takes. An unwired direction is
each element's own `v`, so written onto particles as `orient` it turns each
one onto its motion. A card drawn with `zero_billboard_streak` then streaks
along it.
## Noise
- `field.worley` — the distance to the nearest scattered feature point. Use it
for cells, cracks, scales and stone.
- `field.simplex` — smooth signed noise in [-1, 1].
```lua
local g = proc.graph("embers")
g:node("emit", "points.grid", nil, { countX = 1, countZ = 1 })
g:node("src", "sim.spawn", { points = "emit" }, { rate = 200, lifetime = { x = 2, y = 4 } })
g:node("curl", "field.curl", nil, { frequency = 0.6, amplitude = 5 })
g:node("swirl", "sim.force", { field = "curl" })
-- Air rising at 2 m/s: each ember is pulled toward that velocity, which is
-- wind and drag in one.
g:node("updraft", "field.constant", nil, { value = { x = 0, y = 2, z = 0 } })
g:node("air", "sim.force", { field = "updraft" }, { mode = "velocity", strength = 0.4 })
g:node("sim", "sim.particles", { sources = { "src" }, forces = { "swirl", "air" } })
```
▲ 0↑ born
# geometry
Composing and measuring meshes: transform, join, merge, triangulate, voxelize, delete, separate.
The definitions live in `proc.ops.geometry`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "geometry" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.transform`
- `geometry.append`
- `geometry.recalculate_normals`
- `geometry.triangulate`
- `geometry.merge`
- `geometry.measure`
- `geometry.voxelize`
- `geometry.set_material`
- `geometry.set_position`
- `geometry.delete`
- `geometry.separate`
▲ 0↑ born
# gpu
Field ops evaluated on the GPU: one dispatch over a whole field, matching the CPU result.
The definitions live in `proc.gpu`; this pack is what puts them in the op
registry, so `procgen.searchNodes("", { pack = "gpu" })` lists the family and
`procgen.describeNode("op.<id>")` describes either of them. `proc.gpu.eval` is a
convenience wrapper over the same registered ops.
## Ops
- `gpu.scale`
- `gpu.noise`
▲ 0↑ born
# grid
A grid is space cut into cells: a geometry whose points are the centres of its
cells, laid out x fastest, then y, then z, and whose point columns are its
channels (a density, a distance, a height, a colour). A grid one cell thick
along an axis is flat: the height over a ground, an image.
Because a grid is a geometry, everything that works on points works on its
cells. `attribute.set` writes a channel from any field, `attribute.accumulate`
totals one, `attribute.promote` folds one into a single value. These ops add
what knowing the layout gives:
- `grid.box`: a grid of cells filling a box. Give it a cell count per axis, or
a cell size.
- `grid.cell_index`: which cell each position falls in (-1 outside), as a
field.
- `grid.neighbor_index`: the cell a fixed step away from each cell, held to
the grid's edge, as a field.
- `grid.sample`: a channel read at every point of a geometry, blended between
the eight cell centres around it.
`procgen.searchNodes("", { pack = "grid" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
Particles deposited into cells, then read back by the particles:
```lua
local air = g:node("air", "grid.box", nil, { size = { x = 4, y = 3, z = 4 }, cells = { x = 32, y = 24, z = 32 } })
local cell = g:node("cell", "grid.cell_index", { grid = air })
local dense = g:node("dense", "attribute.scatter", { geometry = air, source = sparks, index = cell },
{ name = "mass", as = "density" })
g:node("felt", "grid.sample", { geometry = sparks, grid = dense }, { name = "density" })
```
A blur along x is two neighbours gathered and averaged:
```lua
local right = g:node("right", "grid.neighbor_index", { grid = dense }, { offset = { x = 1, y = 0, z = 0 } })
local left = g:node("left", "grid.neighbor_index", { grid = dense }, { offset = { x = -1, y = 0, z = 0 } })
local a = g:node("a", "attribute.gather", { geometry = dense, index = right }, { name = "density", as = "r" })
local b = g:node("b", "attribute.gather", { geometry = a, index = left }, { name = "density", as = "l" })
```
▲ 0↑ born
# group
Named selections over a mesh's points, vertices, edges or faces, for other ops to act on.
The definitions live in `proc.ops.groups`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "group" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `group.create`
- `group.by_normal`
- `group.by_bounds`
- `group.by_random`
- `group.by_island`
- `group.combine`
- `group.invert`
- `group.expand`
- `group.shrink`
- `group.list`
- `group.info`
- `group.remove`
▲ 0↑ born
# growth
Curves that grow from other curves. The result is a single geometry holding
every curve, starting curves included. Each point carries:
- `generation`: 0 on the starting curves, one more per fork;
- `u`: how far along its own curve, 0 to 1.
Because the result is geometry, every curve, point and field op works on it:
- roughen it with `geometry.set_position` and a noise field;
- sweep it into tubes with `geometry.sweep`;
- sample it with `points.on_curve`, for sparks along a crack;
- read `generation` through a ramp, so branches thin as they fork.
`procgen.searchNodes("", { pack = "growth" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `curve.branch` — branches sprout from each curve, generation after
generation. Each curve sends out `branches` children from along its length.
A child turns off its parent by up to `angle`, is `ratio` as long, and
wanders as it goes. A `normal` keeps the growth in one plane, the way a
crack keeps to the surface it crosses. Use it for cracks, lightning forks,
frost and coral.
- `curve.grow` — branches reach toward a cloud of attractor points (space
colonisation). A node grows a step toward the attractors that pull on it,
and an attractor a branch reaches is spent, so the growth fills the cloud's
shape. Use it for canopies, root balls and leaf veins.
```lua
g:node("impact", "curve.line", nil, { start = { x = -1, y = 0, z = 0 }, finish = { x = 1, y = 0, z = 0 }, segments = 8 })
g:node("cracks", "curve.branch", { curve = "impact" }, { generations = 4, branches = 2, angle = 45, wander = 25, normal = { x = 0, y = 1, z = 0 } })
g:node("here", "field.position")
g:node("jag", "field.curl", { position = "here" }, { frequency = 3, amplitude = 0.05 })
g:node("rough", "geometry.set_position", { geometry = "cracks", offset = "jag" })
```
▲ 0↑ born
# instances
Placing copies of a source on points, varying them, and realizing, drawing or spawning the result.
The definitions live in `proc.ops.instances`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "instances" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `instances.on_points`
- `instances.randomize_transform`
- `instances.pick_random`
- `instances.pick_by_attribute`
- `instances.realize`
- `instances.spawn`
- `instances.draw`
- `instances.cull`
- `instances.set_material`
- `instances.transform`
- `instances.from_bundle`
▲ 0↑ born
# material
Materials made from any surface shader, with every property the shader declares
set, animated or wired from the graph.
`procgen.searchNodes("", { pack = "material" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `material.shader`: a material from a surface `.shader`. Each property its
`properties.yaml` declares is set by name in `properties`, as a constant, an
animated value or a wired output, and each texture slot by name in
`textures`. `blend`, `cull` and `depthWrite` set how it draws. A shader that
declares a `buffer` property reads, through `elements`, one vec4 per live
element another part of the graph made.
`shader` is a reference, written `asset.resolve("<identity>", "shader")`; a
name alone is refused.
```lua
local ember = g.op.material.shader({ shader = asset.resolve("@builtin::shaders.unlit", "shader"),
properties = { base_color = { r = 1, g = 0.5, b = 0.1, a = 1 } }, blend = "additive", depthWrite = "false",
cull = "none" })
```
`material.pbr`, the metallic-roughness material, comes with the `texture` pack.
`g.material.shader` and `g.material.pbrMat`, nodes of the `material` nodebox, answer one element
holding the material record (`records/material.procRecord`), which any input taking a material takes,
`io.output` shows and `io.export` saves as a `.material`.
▲ 0↑ born
# mesh
The primitive solids a graph starts from. A `.mesh` asset enters a graph through
the `asset` node (`procPacks/asset.procPack`), as the Surface the mesh type
states.
The definitions live in `proc.ops.sources`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "mesh" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `mesh.box`
- `mesh.sphere`
- `mesh.cylinder`
- `mesh.cone`
- `mesh.plane`
- `mesh.capsule`
- `mesh.octahedron`
- `mesh.torus`
- `mesh.rounded_box`
- `mesh.grid`
▲ 0↑ born
# normals
Welding coincident points and smoothing the normals that shading reads.
The definitions live in `proc.ops.normals`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "normals" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.weld`
- `geometry.smooth_normals`
▲ 0↑ born
# points
Point clouds: grids, discs, poisson sets, points on a surface or a curve, and the ops that filter, relax and look around them.
The definitions live in `proc.ops.points`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "points" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `points.grid`
- `points.disc`
- `points.poisson`
- `points.box`
- `points.on_surface`
- `points.from_vertices`
- `points.filter`
- `points.on_curve`
- `points.relax`
- `points.neighbors`
- `points.count_neighbors`
▲ 0↑ born
# prefab
Entity prefabs and bundles: the records a spawned hierarchy is made of, and the asset they persist as.
The definitions live in `proc.ops.prefabs`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "prefab" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them. Each `prefab.*` op
also answers to the same id with `template` in place of `prefab`.
## Ops
- `prefab.empty`
- `prefab.add_component`
- `prefab.from_geometry`
- `prefab.from_geometries`
- `prefab.from_instances`
- `prefab.from_population`
- `prefab.from_asset`
- `bundle.from_population`
- `bundle.from_asset`
- `bundle.from_prefab`
- `bundle.from_instances`
- `bundle.join`
- `bundle.write`
- `bundle.spawn`
- `prefab.entity`
- `prefab.parent`
- `prefab.link`
- `scene_fragment.write`
- `part.merge`
- `part.unpack`
▲ 0↑ born
# ramp
A ramp is a value that changes over 0..1. It is how an effect makes one thing
follow another: colour over life, size over speed, opacity over height.
`procgen.searchNodes("", { pack = "ramp" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `ramp.keys` — a ramp built from keys. Each key is `{ t, value }`, and the
value can be a `Float`, `Color`, `Vec2`, `Vec3` or `Vec4`. Between keys the
value moves in one of three ways:
- `linear`: a straight line from key to key;
- `smooth`: eased into and out of each key;
- `constant`: each key's value held until the next key.
- `ramp.blackbody` — the colours a blackbody glows at across a temperature
range, as a Color ramp: red embers through orange flame to white. `glow`
makes the hotter keys brighter; 4 follows the fourth power of temperature
that real blackbody radiance does.
- `ramp.sample` — a ramp read at every element, at the position along it a
0..1 field names. The ramp compiles to the element's dispatch, so a
solver's particles read it on the device.
- `field.ramp` — a ramp read at every element by a value it carries: a graph
of `field.attribute`, `field.map_range` and `ramp.sample`. By default each
element reads it by its own `life` attribute, so particles change over their
lifetime. `by` names any other attribute, `range` maps that attribute's
values onto 0..1, and wiring `t` reads the ramp by any field.
A ramp is a graph value like any other. It can be wired, animated (its keys
are params) and cached.
```lua
g:node("fire", "ramp.blackbody", nil, { from = 900, to = 4000, glow = 1 })
g:node("tint", "field.ramp", { ramp = "fire" })
g:node("lit", "attribute.set", { domain = "sim", value = "tint" }, { name = "Cd" })
```
▲ 0↑ born
# scene
Reading the scene into a graph. These nodes pull from the scene; every other
node takes what they make as an input.
A graph is evaluated in its own space, whose origin is the entity it stands on
— a Generator's. An effect built at the origin therefore works wherever it is
played, with nothing wired, and a pose brought in from the scene lands in that
same space unless a node asks for the world's.
## Nodes
- `scene.query` — entity ids out of the scene: by Name or a glob over Names, by
a component they carry (native or script), as the children, descendants or
parent of other entities, or the camera the scene is seen through. Its `of`
and `within` take another query's ids, so queries compose. It outputs `ids`
and their `count`.
- `scene.fetch` — the entities `ids` names as points, one each, in that order.
Every point carries its entity's id as `entity`; `transform` brings the pose
as `P`, `orient` and `scale`, in the graph's space, the world's or each
entity's own under its parent (`space`); `components` brings any component
as an attribute named after it holding its record. Those are the attributes
`proc.translate` writes back to an entity, so what a graph fetches, edits and
outputs lands back on the same components. The pose follows the entities,
and the graph's origin, as they move, without a cook.
- `scene.input` — scene.fetch on the entity the graph stands on, always. Its
pose in the graph's space is the origin; `space = "world"` says where the
graph stands. A graph standing on no entity has no point here.
- `scene.water`: the water the scene holds, read as it stands each frame:
every surface a water system provides. Wired into `terrain.drape`'s `ground`,
it sets points on the water, each taking the surface's height and normal and
marked `wet`, and they follow the waves.
`procgen.searchNodes("", { pulls = "scene" })` lists every node that pulls from the scene,
these and the ones reading a particular part of it (`terrain.ground`,
`sim.scene_colliders`).
▲ 0↑ born
# sdf
Signed distance fields: shapes as distance, combined smoothly, and carried across to and from geometry.
The definitions live in `proc.ops.sdf`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "sdf" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `sdf.sphere`
- `sdf.box`
- `sdf.rounded_box`
- `sdf.torus`
- `sdf.capsule`
- `sdf.cylinder`
- `sdf.cone`
- `sdf.plane`
- `sdf.union`
- `sdf.subtract`
- `sdf.intersect`
- `sdf.transform`
- `sdf.twist`
- `sdf.bend`
- `sdf.taper`
- `sdf.elongate`
- `sdf.round`
- `sdf.shell`
- `sdf.mirror`
- `sdf.repeat`
- `sdf.position`
- `sdf.displace`
- `sdf.mesh`
- `geometry.to_sdf`
- `sdf.from_grid`
- `sdf.sample`
▲ 0↑ born
# shader
An author's own compute shaders as graph nodes. A `.computeShader` written for
anything else runs inside a graph unchanged: its bindings are the geometry's
columns, its `params:` are the node's knobs, and what it writes comes out as
columns every op after it reads.
`procgen.searchNodes("", { pack = "shader" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `shader.compute` — run a `.computeShader` over a geometry's elements, one
invocation per element. A buffer binding is the column of its own name, or the
one `bind` names: `access: read` reads it, `access: read_write` writes it and
makes it when the domain has none. The shader's `params:` take their values
from `uniforms`, where each can be animated or wired, and `count`, `time` and
`frame` are filled in when the shader declares them. `shader` is a reference,
written `asset.resolve("<identity>", "computeShader")`; a name alone is
refused. The same shader placed as two nodes reads each node's own columns
and values.
- `sim.shader` — a solver whose step is a `.computeShader`: the domain's
columns are its state, the shader runs once per element at every fixed step
writing its `read_write` bindings in place, and `dt`, `time` and `frame` are
the solver's own.
## Writing a shader for a graph
The element index is `global_invocation_id.x`. A column's lanes are packed
`f32`s: a Float column binds as `array<f32>`, a Vec3 column as `array<f32>` read
three to an element, and a Vec2 or Vec4 column as `array<vec2<f32>>` /
`array<vec4<f32>>`.
```yaml
bindings:
- { name: P, access: read_write, element: f32 }
- { name: weight, access: read, element: f32 }
params:
- { name: lift, type: float, default: 1.0 }
- { name: count, type: int, default: 0 }
```
```wgsl
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let i = id.x;
if (i >= u32(params.count)) { return; }
P[i * 3u + 1u] = P[i * 3u + 1u] + params.lift * weight[i];
}
```
```lua
local pts = g.op.attribute.set({ domain = g.points.grid({ countX = 4, countZ = 4 }), name = "weight", value = 1 })
local raised = g.op.shader.compute({ domain = pts, shader = asset.resolve("lift", "computeShader"),
uniforms = { lift = 2 } })
```
## Finding the points near a point
A shader that looks at its neighbours — separation in a flock, the car ahead in
traffic, a density — declares the three read bindings of a spatial grid and
includes the `grid` shader module; the node gets a `neighborRadius`, builds a
grid of the domain's points with cells that wide before it runs (and again at
every step of a `sim.shader`), and binds it. The shader then walks the 27 cells
around a point instead of every point.
```yaml
bindings:
- { name: P, access: read, element: f32 }
- { name: nb, access: read_write, element: f32 }
- { name: gcfg, access: read, element: f32 }
- { name: grange, access: read, element: u32 }
- { name: gorder, access: read, element: u32 }
```
```wgsl
#include "@builtin::systems.procgen.grid"
let c = zero_grid_cell(p);
for (var dz = -1; dz <= 1; dz = dz + 1) {
for (var dy = -1; dy <= 1; dy = dy + 1) {
for (var dx = -1; dx <= 1; dx = dx + 1) {
let cc = c + vec3<i32>(dx, dy, dz);
let span = zero_grid_range(cc);
for (var s = span.x; s < span.y; s = s + 1u) {
let j = gorder[s];
// j == i is the point itself; a j whose own cell is not cc
// shares a bucket with it and belongs to another cell
}
}
}
}
```
```lua
local birds = g.op.points.sphere({ count = 64, radius = 2 })
local flock = g.op.sim.shader({ domain = birds, shader = asset.resolve("flock_step", "computeShader"),
neighborRadius = 1.5 })
```
A node whose shader declares the grid's bindings and is given no
`neighborRadius` is refused, naming the input.
A step that reads its neighbours' state while every element writes its own
would read some of them half-updated. A read binding named `prev_<column>`
(`prev_P`, `prev_v`) is that column as it stood before the dispatch — a copy
`sim.shader` takes before every step — so each element reads the same
before-state and writes only its own:
```yaml
bindings:
- { name: P, access: read_write, element: f32 }
- { name: prev_P, access: read, element: f32 }
```
`points.neighbors` answers the common questions — how many neighbours, the
nearest, their centroid and their mean of an attribute — without a shader.
▲ 0↑ born
# sim
Simulation: what a solver's particles are born from, what pushes them and what
they bounce off, and `sim.particles`, the particle solver.
These are the sim context's nodes. What one of them makes is read by the
solver at every step, so it is wired into another sim node or into an input
that opens sim — `sim.particles`' `sources`, `forces` and `colliders`.
Wired anywhere else, `procgen.validate` reports it and the cook refuses it.
The definitions live in `proc.ops.sim`; this pack is what puts them in the node
registry, so `procgen.searchNodes("", { pack = "sim" })` lists the family and
`procgen.describeNode("op.<id>")` describes any one of them.
## Nodes
- `sim.spawn` — a spawn description: particles born on a set of points at a
rate and in bursts, with a starting velocity, a lifetime, a size and a stream
name.
- `sim.force` — a force the solver applies at every step, from any Vec3 field
evaluated where each particle is: as an acceleration (`mode =
"acceleration"`, scaled by `strength`), or as a velocity each particle is
pulled toward at `strength` a second (`mode = "velocity"`). Wind is a wind
field and drag is still air, both as velocities.
- `sim.collider` — a plane, a sphere or a box the particles bounce off.
- `sim.scene_colliders` — the scene's collision environment: every box, sphere
and capsule physics collider that is not a sensor, turned and moving with its
entity, solid from every side, and read where it stands in the graph's space
at every step. Its `within` takes only the colliders near its `center`; a
solver takes at most 128 shapes.
Every shape is met along the whole of each step's move, so a fast particle
does not pass through a thin one.
- `sim.particles` — the particle solver, a geometry node: every particle from
every spawn in one geometry on the GPU, stepped over the graph's timeline
under the forces and against the colliders, output as the particles alive
now.
```lua
local g = proc.graph("sparks")
g:node("emit", "points.sphere", nil, { radius = 0.1, count = 16 })
g:node("src", "sim.spawn", { points = "emit" }, { rate = 300, speed = { x = 3, y = 6 } })
g:node("curl", "field.curl", nil, { frequency = 0.8, amplitude = 4 })
g:node("swirl", "sim.force", { field = "curl" })
g:node("world", "sim.scene_colliders", nil, { bounce = 0.3 })
g:node("sim", "sim.particles", { sources = { "src" }, forces = { "swirl" }, colliders = { "world" } },
{ gravity = { x = 0, y = -9.8, z = 0 } })
g:output("points", "sim")
```
▲ 0↑ born
# sink
The sinks: a generated mesh, texture, material or population written out as a real asset.
The definitions live in `proc.ops.sinks`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "sink" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `mesh.write`
- `texture.write`
- `material.write`
- `population.write`
- `debug.dump`
- `debug.validate`
▲ 0↑ born
# strip
Surfaces laid along curves. `geometry.ribbon` lays a flat ribbon of a width
along every curve of a geometry, lying square to `up`. It is what a crack
glowing in the ground, a trail, a beam, a tyre mark or a road is drawn with.
Each edge of a ribbon carries every attribute of the curve point it was laid
from, so a field or a material reads `generation`, `heat` or anything the curve
carries across the ribbon. The mesh's uv is laid for a shader:
- `uv.x` runs 0 to 1 along each curve, by distance;
- `uv.y` runs 0 to 1 across it, so a hot core down the middle and a soft edge
come from `uv.y` alone.
Width can change along a ribbon:
- `taper` narrows each ribbon toward its end, the way a crack thins to its tip;
- `widthBy` names a Float point attribute that scales the width where the points
carry it — for example a branch's width from its `generation` through a ramp,
or a trail thinning with age.
`lift` raises the ribbon off its curve along `up`, so one laid on a surface
draws above it.
`procgen.searchNodes("", { pack = "strip" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
```lua
local g = proc.graph("fissure")
g:node("line", "curve.line", nil, { start = { x = -1, y = 0, z = 0 }, finish = { x = 1, y = 0, z = 0 }, segments = 8 })
g:node("cracks", "curve.branch", { curve = "line" }, { generations = 3, branches = 2, normal = { x = 0, y = 1, z = 0 } })
g:node("glow", "geometry.ribbon", { curve = "cracks" }, { width = 0.05, taper = 0.9, lift = 0.004 })
g:output("glow", "glow")
```
▲ 0↑ born
# subdivide
Catmull-Clark style subdivision: more faces where a surface needs to be smooth.
The definitions live in `proc.ops.subdivide`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "subdivide" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.subdivide`
▲ 0↑ born
# sweep
Building a surface from a curve: sweeping a profile along it, revolving it, lofting between them.
The definitions live in `proc.ops.sweep`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "sweep" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `geometry.sweep`
- `geometry.revolve`
- `geometry.loft`
▲ 0↑ born
# texture
Textures generated from noise and gradients, the PBR material that consumes them,
and textures made on the device from a raster's layers or an author's compute shader.
`texture.noise`, `texture.gradient` and `material.pbr` are defined in
`proc.ops.textures`; `texture.from_raster` and `texture.from_shader` are defined
in this pack's `init.luau`. This pack is what puts them in the op registry, so
`procgen.searchNodes("", { pack = "texture" })` lists the family and
`procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `texture.noise` — a noise texture (value or gradient noise) mapped between
two colours.
- `texture.gradient` — a two-colour gradient texture: horizontal, vertical or
radial.
- `texture.from_raster` — a texture of a raster's layers, made on the device:
up to four layers (`layers`, in channel order) become the red, green, blue
and alpha of one texel per cell. A channel no layer fills is 0, and alpha 1.
- `texture.from_shader` — a texture an author's `.computeShader` draws on the
device, one invocation per texel: the shader writes texel `i` (row-major,
x = i % width) of the one buffer it declares `read_write` with element
`vec4<f32>`. `width`, `height`, `count` (texels), `time` and `frame` are
filled into its `params:` when it declares them.
- `material.pbr` — a metallic-roughness material. `albedo` is the base colour,
as a Vec4 param or a Texture input.
The textures `texture.from_raster` and `texture.from_shader` make stay on the
device, where a material samples them with nothing read back.
▲ 0↑ born
# topology
What a mesh is connected to: edges, boundaries, islands, adjacency, and conversion between element classes.
The definitions live in `proc.ops.topology`; this pack is what puts them
in the op registry, so `procgen.searchNodes("", { pack = "topology" })` lists the family
and `procgen.describeNode("op.<id>")` describes any one of them.
## Ops
- `topology.edges`
- `topology.boundary`
- `topology.islands`
- `topology.adjacency`
- `topology.convert`
▲ 0↑ born
# value
Single values a graph computes with. A measurement turns into something a
loop stops on, a count another node takes, or anything a switch decides.
`procgen.searchNodes("", { pack = "value" })` lists the family and `procgen.describeNode("op.<id>")`
describes any one of them.
## Ops
- `value.get` — one field of a Data or record value, by a dotted path such
as `bounds.max.y`. When the path misses, the error names the fields that
are there.
- `value.math` — `a <op> b` for add, sub, mul, div, min, max or pow. `b` is
a wire or the `constant` param.
- `value.expr` — a number that follows an expression over the graph's time
(`t`, `frame`, the math functions) and the names `variables` gives it, each
a constant, a graph input or another node's number. A curve that depends on
graph inputs is this one node: `{ variables = { peak = peak, decay = decay } }`
with `expression = "peak * max(0, 1 - t / decay) ^ 2"`.
- `value.compare` — `a <op> b` for less, less_equal, greater, greater_equal,
equal or not_equal, answering a Bool.
- `value.switch`: `ifTrue` when `when` is true, `ifFalse` otherwise. Only the
one taken is cooked.
- `value.present`: whether anything is wired into `value`, as a Bool: what a
graph used as a node asks of an input its caller may leave unwired.
- `value.fallback`: the value wired into `value`, or `fallback` when nothing
is. `fallback` is cooked only when it is the one taken.
```lua
local stats = g:node("stats", "geometry.measure", { geometry = grown })
local top = g:node("top", "value.get", { data = stats }, { path = "bounds.max.y" })
local done = g:node("done", "value.compare", { a = top }, { op = "greater_equal", constant = 3 })
```
▲ 0↑ born
# procRecord: a kind of record a graph makes and saves
A `.procRecord` defines a kind of value a procedural graph moves that becomes an asset when it is saved: a material,
a mesh, a texture, or a kind a world defines for its own asset type. Its `init.luau` returns
`proc.record({ ... })`:
```
Glow.procRecord/
init.luau -- returns proc.record({ ... })
README.md -- what a record holds and the asset it saves as
.metadata -- description and tags
```
## What a kind states
- **`name`**: the kind's display name. A kind is identified by its guid, so two kinds may share a name.
- **`asset`**: the asset type a record saves as (`"material"`).
- **`applies`**: `{ component, field }`, the component a record stands in live and the field it feeds
(`{ component = "Material", field = "material" }`).
- **`fields`**: the record's own fields by name, each with a short description.
- **`live(record, key)`**: the runtime value the applied field takes, filed under `key`.
- **`release(value, key)`**: lets go of what a runtime value `live` answered holds. Left out, the kind holds nothing
to let go of.
- **`save(record, name, place)`**: writes the record as its asset and answers the reference. Left out, the asset type's
own `graph.write` writes it.
- **`load(ref, options)`**: the record an asset of the kind holds. Left out, the asset type's own `graph.read` reads it.
`name` and `asset` are required; a key outside these is refused, naming the keys a kind states.
## How records travel
A record carries its kind's guid as `kind`. The node that writes a record holds it on an element, in the attribute
named after the component the kind applies to (`Material = { material = <record> }`), and states the kind on the
geometry's detail attribute `records`: `{ [<kind guid>] = <reference to the .procRecord> }`. `io.output` stands the
element with the runtime value the kind's `live` answers, `io.export` saves the record through the kind, and
`io.import` reads an asset back as the same element: an asset type names the kind its assets load as in its `graph`
conversion (`graph.record`).
A node references a kind by a literal reference, `asset.resolve("<identity>", "procRecord")`, and
`proc.records.stamp(ref)` gives the `records` map that names it.
`io.import` of a `.procRecord` answers the kind itself, `{ kind, name, asset, applies }`: the guid a record of it
carries and what it saves as and applies to.
▲ 0↑ born
# procgen
The procedural-generation tool family: find the nodes a graph is built from,
edit a graph's code, preview it, try values for its inputs, inspect it, spawn a
live generator to iterate in the scene, and watch cooks as they run. A graph is
the code of its `init.luau` (`proc.define(function(g) ... end)`); the tools here
read that code, edit it, picture it and run it.
Each tool is called as `tools.use("procgen", "<tool>", ...)` from Luau, as
`zero procgen <tool>` in the engine shell (`zero procgen <tool> --help` gives its
arguments), and through `use_tool` over MCP. A tool's README and
`describe_tool` give its arguments and what it answers.
## Discovery
- `searchNodes`: find nodes by what they do, the counterpart of
`search_tools`: by meaning, through ZeroMind's search over every published
node and pack of ops (a pack's ops that answer the words are listed as
`op.<id>` rows), with this world's own unpublished nodes after the ranked rows.
A query needs the live session an engine bound to a world holds. With no query it
lists every node a graph calls here (`g.<family>.<name>`, and the ops of
packs as `g.op.<id>`) and names every family and the nodes in it.
- `describeNode`: one node in full, the counterpart of `describe_tool`: what
it does, its inputs in call order with their types, defaults, ranges and
options, its outputs, its family, the call a graph writes and, for an op of a
pack, what it costs.
- `search` — free-text search over the `.procGraph` graph library (name /
id / description / tag / category).
- `find` — discover graphs by what they *produce* (an output type or
producing-op substring, e.g. `{ produces = "Bundle" }`).
- `inspect` — one node's op, sockets, producers, and consumers.
- `coverage` — every current op with the new node that replaces it and its
parity state, and every library graph with the worst state among the ops it
names.
- `stats` — structural counts (nodes / composites / inputs / outputs),
plus evaluated-output stats when a `target` is given.
- `trace` — the dependency chain for a target, in evaluation order.
- `explain` — an agent-oriented natural-language summary of a graph.
- `diff` — a structural diff between two graphs (changed/added/removed
nodes, per-node deltas).
- `validate` — check a graph the way its cook will: that its source builds,
its connections (type mismatches, missing inputs, unknown nodes and params),
then what a cook of its first frame refuses (bounded by `timeoutMs`), and the
nodes that run on the CPU every frame.
- `generators` — survey every live procedural generator in the scene:
bound graph, params, realized child count, and cook state.
## Edit the code
These edit a graph's (or node's) `init.luau` as code and write it only once it
builds, so the graph stays valid. A section is a run of statements named by the
lines it spans; a call is named by the local it declares or a line it spans.
- `collapse`: lift a section (a few node calls doing one job) into a node of
its own: its inputs are the values the section reads, its outputs the values
the code after it reads, and the section becomes one call of the new node.
The graph cooks to the same result, and `searchNodes` finds the node.
- `flatten`: the inverse: write a node's body out in place of a call to it
(one call, every call of a node, or every call of a node outside the
built-in library).
- `reference`: put a call of an existing node in place of a section.
- `promote`: make a part (a `.procGraph` called by its path) a node found by
name, which stays the part's.
- `patch`: set and unset what one call is given.
- `modify`: structural edits as one change: add, remove and repoint calls,
rename locals, declare inputs and outputs.
## Try it
A tool that takes a graph to preview or run takes it by its VFS path or its
name, or as a graph object (what `proc.define`, `proc.graph` and `proc.load`
return); `spawn` and `play` take a saved graph, since a generator plays an asset.
- `tweak` — preview a graph with other values for its declared inputs, in a
single step, leaving its source as it is: the knob-tuning loop.
## See it / make it real
- `preview` — evaluate one target (an output or a node) of a graph and render
it for any output type (Geometry, points, Field heatmap, Material ball,
Texture, Bundle); the picture comes back in the result beside its stats.
- `spawn` — spawn a live procedural generator from a saved graph: an entity
with a Generator component bound to it, which cooks the graph on its own
runner and cooks again as its params change.
- `adjust` — adjust a live generator in place: merge param overrides or
select another output.
- `apply` — swap a live generator in place for the asset it makes: its
current output becomes a durable bundle, and an Asset component standing it
replaces the Generator, like applying a modifier.
- `bake` — evaluate one target of a graph and realize it straight into the
scene as durable content, without a live generator.
- `cook` — cook a `.terrainData` that names its graph: the graph runs with the
container's inputs and the ground it makes is written over the container's
children, on the background lane, so the engine keeps drawing and every
terrain standing on the container rebuilds once when the cook ends.
## Play it
- `play` — play a graph on the preview stage with nothing added to the scene: it
plays from its first frame with the inputs given (each a value or a path over
the play's time), for `seconds`, and answers the profile of that play and a
picture of what it draws at each time of `at`.
## Cook observability
- `cooks` — the scene-wide cook monitor: every in-flight cook, a bounded
history of recently finished ones, with progress (the nodes cooked so far and
the node running now), status, duration, and — on failure — the error and the node
that broke, and the frames generators presented most recently.
- `cancel` — cancel an entity's in-flight cook; it stops at its next
checkpoint and the previous output stays realized.
- `onPresent` — be told the moment a generator presents the frame you
describe (an output, a graph time or a time within a repeating cycle, an
element count), with the probe's own options beside the terms: `capture` a
picture of that frame (what the generator draws alone, framed to fit, over
the grey studio backdrop), `freeze` the generator and the world on it (the
generator plays on with `generator:play()`), a `when` and `run` of your
own. It arms a probe, so `probe.list`, `probe.hits` and `probe.cancel`
manage it.
- `frames` — see how an effect goes: a picture of the frame a generator
presents at each graph time you name (or `count` of them from `from` to
`to`), each of what it draws alone, framed to fit, over the grey studio
backdrop an asset preview is photographed in, with the frame, how it was
presented and each output's element count beside it. A time past the end
of a timeline shows its last frame, with a `note` saying so; a picture of
a frame that draws nothing, or one that holds the backdrop alone, says so in
its own `note`. A generator whose cook failed raises, naming the node and
the reason. The clock goes back where it stood after.
- `profile` — what evaluating graphs has cost, read from what was recorded as
the work ran: every graph's run and wait time, its nodes costliest first,
the verdicts on what was paid again, saved runs to compare against, and one
graph invoked once with what that invoke cost.
▲ 0↑ born
# material (procRecord)
The material record kind: a surface shader, its property values by name, its texture slots by name and, optionally,
render state (`blend`, `cull`, `depthWrite`) and a buffer property filled from elements. `material.pbrMat` and
`material.shader` answer one, held on one element as `Material = { material = <record> }`.
Live, a record becomes the runtime material the `Material` component's `material` field holds. Saved, it is a
`.material` asset, and a Texture record in one of its slots is written as a texture beside it. `io.import` of a
`.material` asset answers the same element, its record read from the asset.
▲ 0↑ born
# procgen.results
What procgen made, kept in the world by what it is, so a process that needs the same output reads it instead of making it. An author's engine makes an output once and writes it here; entering play, a later boot, a collaborator's engine and a player's engine read the bytes it wrote.
- A space is one kind of output (`pieces`: the meshes of quick-geometry pieces; `fxprogram`: the programs of effect entries). It lives under `/zero/source/_cache/procgen/<space>/`: `<key>.record` (JSON: what the output is, the version of the code that made it as `maker`, and the blobs it names by address) and `<sha256>.<ext>` (each blob, named by the SHA-256 of its bytes).
- `key(space, text)` names an output by what it is made from alone, so a record stays readable across versions of the code that makes it. `version(paths)` states the version of that code (the checksums of the library paths named).
- `writes()` answers whether this process makes outputs and keeps them: an engine that authors the world, in edit mode and in the play of an editor session (its writes go to the world's source past the play's shadow). A runtime engine, a player's, takes any record it finds; an author's engine makes the output again where a record's `maker` is not the version it runs.
- `read(space, key)`, `blob(space, address, ext)`, `put(space, bytes, ext)` (writes a blob once and answers its address) and `write(space, key, record)` (files a record, after the blobs it names).
A world keeps what is under `_cache` like any other content, so `zm add`, `zm commit` and `zm push` carry it to every engine that opens the world.
Part of `@builtin::systems.procgen`; required as `@builtin::systems.procgen.results`.
▲ 0↑ born
# Package (asset type)
A package is an asset — a `<Name>.package/` folder that bundles
components, modules, scenes, presets, tools, and any other typed
sub-assets under one identity, installed into a world as one unit.
Packages are how authoring sets get distributed across worlds.
A **library** is the addressable root scope content resolves under
(`@builtin`, `@<name>`) — a whole world mounted into this one under a
namespace, via `zeromind.installLib` / `world.installLibrary`. A package is
an asset that lives inside such a root, and one library holds as many
packages as its author put there. A package is installed by guid the
way every asset is (`zeromind.installAsset`).
## When to use one
- You're authoring a coherent feature suite (character controller
stack, voxel engine, UI kit, animation library) and want to ship
it as one install target.
- You want a stable identity worlds can install and resolve sub-assets
against (`@<lib>::pkg.sub_module`).
- You want versioning + a per-package metadata layer that travels with
the contents.
If you're authoring inside a single world and don't need a separate
install lifecycle, you don't need a package — drop your `.component`
/ `.module` / etc. directly in `/zero/source/`. Packages are for
cross-world distribution.
## Where it lives
- Source: `/zero/source/.../<Name>.package/` (or, for legacy
packages, a folder containing `package.yaml` at its root).
- Identity: `<Name>` (the `.package` suffix collapses in identity —
mirrors `.module`). A file at `<Name>.package/<sub>/init.luau`
resolves under the same identity it would at `<Name>/<sub>/init.luau`.
- Folder shape (container-style — open child set):
- `package.yaml`: metadata (name, version, description) and the
packages it depends on (`dependencies`). **Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- Sub-asset folders: any combination of `.component/`,
`.module/`, `.scene/`, `.preset/`, `.tool/`, `.toolbox/`,
`.material/`, `.shader/`, etc.
The validator permits unlisted children (`allow_unlisted: true`) by
design — packages are open containers.
## How to create one
```luau
asset.create("package", "<Name>")
-- Creates: /zero/source/<Name>.package/
-- package.yaml (metadata scaffold)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("package", "<Name>", { folder = "systems" })
```
Then scaffold sub-assets inside it:
```luau
local pkg = asset.resolve("<Name>.package")
asset.create("component", "Spinner", { into = pkg })
asset.create("module", "util", { into = pkg })
```
## `package.yaml`
```yaml
name: inkBlocks # optional; the folder stem when absent
version: "1.0.3"
description: "Ink and paper style blocks"
dependencies:
- styleKit # no version: the newest release
- { name: starterBlocks, version: ">=1.0.8" } # a floor
- name: uiKit
version: "=2.3.1" # an exact pin
reason: "2.4.0 renames the panel styles"
```
`dependencies` lists the packages this package needs. Each entry's `name` is
a reference the package records, the same kind of reference a `require` or an
asset name in a data file makes:
- **It resolves in the author's world.** Install the dependency here first
(`zeromind.installAsset`); the entry then names the copy this world holds.
A push refuses a package whose dependency resolves to nothing, naming it.
- **An install brings it along.** Installing the package installs every
dependency it lists, at the version this world holds when the package is
pushed, under `/source/deps/<owner world>/`, deduplicated against what the
installing world already holds. `zeromind.preview` lists each one before
anything is written, and the install's `deps` counts what it brought and
names each package among it (`detail = "full"` lists every dependency's
path and version).
Uninstalling the package leaves a dependency that another installed
package still uses.
- **`version` is a spec.** It names the releases of the dependency the
package works with. With no `version`, or `latest` / `*`, every release is
admitted, across major versions.
| Spec | Admits |
|---|---|
| `latest`, `*`, no version | every release |
| `">=1.4"` | 1.4.0 and every release above it |
| `"^1.4.10"` | `>=1.4.10 <2.0.0` (`^0.3.1` is `>=0.3.1 <0.4.0`) |
| `"~1.4.10"` | `>=1.4.10 <1.5.0` |
| `"1.4.*"` | `>=1.4.0 <1.5.0` |
| `"=1.4.10"` | exactly 1.4.10: the one form of an exact pin |
| `">=1.4 <1.6"` | what every part admits |
Quote a spec in YAML: `>`, `*` and `~` start other YAML forms. A
prerelease (`1.5.0-rc.1`) is admitted only by a spec naming a prerelease of
the same version (`">=1.5.0-rc.1"`). A bare number with no operator
(`version: 1.0.8`) reads as `latest`, and `asset.validate` warns that it
does: delete it to say latest, or write `"=1.0.8"` to pin. Give a pin or a
range a `reason`, which says why to whoever reads it.
`asset.validate` (and so the push) refuses a `version` that is not a spec,
and an explicit spec the dependency this world holds does not satisfy,
naming both; in a world the package is installed into, the package runs the
release the install placed, and the same finding is a warning.
`@builtin::modules.deps` parses specs and resolves a set of them to one
release of each package: the newest release every explicit spec naming it
admits, or a report naming the specs that exclude each other.
## How it operates
1. **Registration.** Writing `package.yaml` indexes the package with
the package registry.
2. **Install.** A package is read before it is installed: `zm ls-tree
@<guid>` in the shell lists what it contains, and `zm show
@<guid>:<path>` and `zm grep <pattern> @<guid>` read it, so candidates
are compared by what they do. The one that fits is installed by guid,
the way every asset is: `zeromind_install` over the engine's MCP, or
`tools.use("zeromind", "installAsset", <guid>)` inside the engine. The
install writes the package's files (and the deps its `.refs`
record, the packages its `package.yaml` lists under `dependencies`
included) into this world's source, so its sub-assets resolve here.
`tools.use("zeromind", "preview", <guid>)` reports what an install would
write before it writes anything.
3. **Sub-asset resolution.** Because `.package` collapses in
identity, sub-asset paths work whether the package folder is
suffixed (`<Name>.package/<sub>`) or not (`<Name>/<sub>`).
4. **Updates.** `tools.use("zeromind", "updates")` lists installed content
with upstream changes available; re-running the install pulls them.
5. **Metadata.** `package.yaml::name` overrides the folder stem if
present (rare); `version` + `description` are surfaced in the
package index.
6. **Hot reload.** Edits to sub-assets hot-reload as normal; edits to
`package.yaml` reload package metadata.
## Discovery
- `asset.list("package")` — every registered package.
- `asset.inspect("<name>")` — sub-asset catalog, source, this type
README.
- `ls /zero/source/<Name>.package` lists the files the folder holds.
- `library.list()` — the library assets registered in this world,
including the ones packages under an installed library contribute.
## Authoring conventions
- Name packages by their feature (`voxels`, `cameraRigs`,
`dialogSystem`), not by their owner — the host library is the
`@<lib>::` scope prefix.
- Cluster cohesive sub-assets together. A "character controller"
package should ship the controller component, its preset configs,
its supporting modules, and a demo scene — not just the component.
- Document the package's surface in `README.md` — what install
installs, what each sub-asset does, how they relate. Agents reading
`cat /zero/source/<Name>.package/README.md` get the full picture in one shot.
- Leave the release version to the push: `zm push` releases a changed
package under the next patch version and writes it into `package.yaml`.
A change that breaks the package's users is `zm push --major`, a new
capability `zm push --minor`. Anything else that names the package's
version reads it from `package.yaml` rather than keeping a copy.
## Common pitfalls
- **Missing `package.yaml`.** Without it the folder isn't recognized
as a package even if it has a `.package/` suffix.
- **A dependency named only by a string the code builds.** A package
whose files reach another package only through a name assembled at
runtime records no reference to it, so an install arrives without it.
List that package under `dependencies` in `package.yaml`.
- **Identity collapse.** Sub-asset paths skip the `.package` suffix.
Don't include `.package` in `require` strings.
## Referencing inside a package: the `~` rule
`~` means **this package**, resolved structurally from the referring file's own
location. It is the only package-specific syntax. It is rename-safe (no package
name is ever written) and library-agnostic (it never names the host library, so
it survives `@builtin` being renamed or the package being mounted elsewhere).
`~.tail` maps to `<pkg>.package/tail` from anywhere inside the package.
| Referencing from | Use | Example |
|---|---|---|
| An asset/module **inside this package** | `~.tail` | `require("~.modules.myThing")`, `shader: "~.shaders.myThingBlend"` |
| A **different package** under the same root | root-relative identity | `require("@root::systems.terrainSystem.modules.terrainOps")` |
| A **different library's** public API (a deliberate external dependency) | `@otherlib::…` | `require("@<otherlib>::<path>")` |
**Never write `@builtin::` (or any host-library name) to reference your own
package** — that couples the package to the library it currently lives in and
breaks if the library is renamed or the files move. Use `~.`. It works from
Luau `require()` and from asset-reference strings in data files (a material's
`mat.yaml` `shader:` field, a component's default asset ref); the engine
resolves it against the referring file's own package. `asset.resolve` takes a
`~.` name the same way, against the package of the file that calls it:
`asset.resolve("~.materials.myThingStandard", "material")`.
`~.` is the package-relative self-reference; `@root::` is the root-relative one
(the library root, or the world source tree for non-library content). The
`core/requiring-modules` guide covers the root model in full.
A package that ships substantial functionality should include a `.guide` asset
(a `<name>.guide/guide.md` folder anywhere under the package); the `guides` tool
discovers it live, so collaborators find the system the way they find built-in
guides. A package's test suite reaches the shared `Test` framework through its
enclosing asset: `local Test = asset.containing(__FILE__).modules.shared`
(`asset.containing` returns the deepest enclosing typed asset, the `.testSuite`,
not the outer `.package`).
## Related types
- Any of `.component`, `.module`, `.scene`, `.preset`, `.tool`,
`.toolbox`, `.material`, `.shader`, `.style`, `.service`,
`.importer` — packages bundle these.
## In the Inspector
Package: the name, version and description package.yaml declares, how many things the package holds and what they are, and **Open** for package.yaml. A package.yaml that does not decode is listed under Problems with the decoder's error.
▲ 0↑ born
# Component (asset type)
A component is code that runs on an entity. The component file
declares public fields, methods, and lifecycle hooks and callbacks; the
engine creates one per entity it is attached to and drives those hooks
(`start`, `update` every frame, `onDestroy`) and callbacks. Components
are the unit of per-entity gameplay code: movement, AI, animations, UI
panels, network sync, and per-entity state all live here.
## When to use one
- You need per-entity state that survives across frames.
- You need per-entity behavior driven by engine lifecycle hooks
(`start`, `update`, `onDestroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If the code does not run on an entity and needs no hooks or callbacks,
use a `.module`. If you
need to generate content declaratively, use a `.service`; compute work
belongs in a `.computeShader`.
## Where it lives
- Source: `/zero/source/.../<Name>.component/`
- Identity: `<Name>` (the `.component` suffix strips from the
identity, but the folder retains the suffix on disk).
- Folder shape:
- `init.luau` (or `init.lua`) — declares the component. **Required.**
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
The structural contract is enforced by `asset.validate` against this
type's `type.yaml`.
## How to create one
Always start with the scaffold — it guarantees the folder shape
matches `type.yaml` from the moment it's on disk:
```luau
asset.create("component", "<Name>")
-- Creates: /zero/source/<Name>.component/
-- init.luau (canonical declare + public block + hooks stubbed)
-- README.md (instance README template)
```
After scaffolding, edit `init.luau` to fill in the actual fields and
behaviour. The component registers as soon as the file is written —
hot-reload is automatic; no engine restart required.
## How it operates
1. **Registration.** Writing `init.luau` into a `.component/` folder
indexes the asset, mints a guid (in the `.meta` sidecar), and
surfaces the type to the engine's component registry. Same-frame
visible to `entity.component.add`.
2. **Attachment.** `entity(id).component.add(name, data)` (or the
batch form `tools.use("entityOps", "addComponents", targets,
{ [name] = data })`) attaches an instance.
The `data` table's fields override the component's declared
defaults; omitted fields take the declared default. The `data`
values are copied into `public.*` BEFORE `awake()` runs.
3. **Lifecycle.** The hooks run in this order:
- `awake()` — same frame as attach, immediately after the data
copy. Initialise state, set up native bridges, register with
other systems. Other components on the same entity may not have
awoken yet.
- `start()` — the next frame. Every component on the entity has
completed `awake()` by then, so cross-component setup is safe
here.
- `update(dt)` — same frame as `start()`, then every frame after,
for as long as the gameplay clock is running. `fixedUpdate(dt)`
runs once per physics step, straight after it, with the step's
`dt`, so a frame can run it several times or not at all;
`editorUpdate(dt)` runs
while the clock is held. Which of them ticks is decided by
`engine.mode` AND `engine.paused` together — see **Per-frame
hooks and the two axes** below, and `man modes`.
- `onDestroy()` — when the component is removed via
`component.remove` or when the owning entity is despawned.
Release resources, drop native ECS components.
For the full list (`onEnable`, `onDisable`, `fixedUpdate`,
`editorUpdate`, `onPropertyChanged`, `onAssetReload`,
`onModuleReload`,
`onBeforeSave`, …) and the timing details, **read `man components`
— that is the canonical lifecycle reference. Generic component
patterns (declare blocks, public fields, sync, ECS bindings,
typed methods) all live there.**
4. **Public surface.** Fields declared in `public` are inspectable,
editable in the inspector, and persist with the entity. Methods are
declared on that same table with a colon —
`typed function public:method(args)` — and every one of them takes
the component ref as `self`, so a caller invokes it with a colon
too: `entity(id).component.get(name):method(args)`. That is the one
calling convention a component ref answers to: the reflection
methods `ref:fields()` / `ref:getField(name)` /
`ref:setField(name, value)` take the same spelling. A function the
chunk declares at file scope (`function helper()`) is the
component's own, reachable from its hooks under its bare name;
`public` is what the ref carries.
5. **Settings and the Inspector card.** `type.yaml` names the component's
settings schema as `settings: { schema: { instance: "init.luau",
export: "public" } }`: the `public` table IS the schema, and its values
live on each entity the component is on, so `asset.schema(componentRef)`
answers the Field descriptors and no values file exists. On an entity
the Inspector shows the component as a card whose generic `settings`
section edits those fields as typed controls, each edit checked against
the schema and written to the live component as one undoable operation.
`type.yaml` also names `inspector: { instance: "inspector.luau" }`: a
component that ships an `inspector.luau` beside its `init.luau` shapes
its card — the file returns `{ sections, replace, order }` (see
`assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)`
reading `ctx.component` (the live component) and `ctx.selection.id` (the
entity). `SceneModule.component/inspector.luau` replaces `settings` with
the bound module's declared inputs.
6. **Events.** An `events` block declares typed moments the component
fires from inside — `events = { onHit = Event({ dmg =
Field.number(0, NoSync) }) }`. The owner fires with
`events.onHit:fire({ dmg = 10 })`; outside code subscribes through
the proxy's subscribe-only facade,
`entity(id).component.get(name).events.onHit:connect(fn)`
(`:once` / `:wait` too). Pass `Sync` as the event's second argument
to replicate a fire to other peers. Events let one component react
to another's moments without polling. Full reference: **`man
components`**, Events section.
7. **Hot reload.** Editing `init.luau` reloads the component
definition; live instances are reconciled with the new declaration
in-place, and each crosses one lifecycle boundary: `onDestroy()`
ends the running life, then `awake()` and `start()` construct the
one that replaces it, and `update()` resumes on the next frame.
`public` and `private` values carry across; module-level `local`s
belong to the chunk, so the new life starts with them at their
initial values and its `awake`/`start` are what fill them in.
Whatever the old life handed elsewhere — a subscription, a shared
registration, a spawned entity — is released in `onDestroy`, the
call that pairs with the construction about to run. An edit that
leaves the source byte-identical crosses no boundary at all.
A field carries its value across when something stated it: a key of
the `data` table the instance was attached with (a scene record's
data is that table), or a write made since. Every other field takes
the edited source's declared default, so changing a default reaches
every instance that left the field to it. An instance that states
its own value for a field whose default the edit changed keeps that
value, and the reload logs a `[HotReload]` warning naming the field,
the entity, the value kept and both defaults.
## Discovery
- `asset.list("component")` — every registered component (engine +
world + libraries).
- `asset.inspect("<name>")` — identity, scope, public fields,
lifecycle methods, source path, and this type README. `detail`
carries the component's declared `fields`, `methods`, and `events`,
parsed from its source — `tools.use("assets","describe", "<name>")`
renders it as markdown, so a component's events are visible without
opening its source.
- `ls /zero/source/<Name>.component` lists the files the folder holds.
- `entity(id).component.list()` — components attached to an entity.
## Per-frame hooks and the two axes
`engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay
clock) are independent, and the per-frame hooks read them separately:
- `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is
running** — whichever mode the engine is in.
- `editorUpdate(dt)` ticks while **the clock is held** — because the
mode is `edit`, or because play is paused — and also alongside
`update` whenever edit is running.
Which gives four states, and this table is the contract:
| `engine.mode` | `engine.paused` | hooks that tick |
|---|---|---|
| `edit` | `true` | `editorUpdate` |
| `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` |
| `play` | `false` | `update`, `fixedUpdate` |
| `play` | `true` | `editorUpdate` |
Entering edit sets `paused = true` and entering play sets it back to
`false`, so a session that never writes `engine.paused` only ever sees
rows 1 and 3 — which is where the shorthand "`update` is the play tick,
`editorUpdate` is the edit tick" comes from. It is the two default rows
of a four-row table, not the rule.
**Row 2 is the one that surprises.** With `engine.paused = false` in
edit — set by hand, or by a tool that advances the gameplay clock to
sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate`
both fire, once each, every frame. A component that declares both and
routes them to one body therefore runs that body **twice per frame**:
```luau
local function drive(dt) ... end
function update(dt) drive(dt) end
function editorUpdate(dt) drive(dt) end -- twice per frame in row 2
```
Nothing reports the doubling; it reads as an animation running at twice
its intended speed. To get exactly one tick per frame in every row, ask
which axis you meant and answer it in the body:
```luau
function update(dt) drive(dt) end
function editorUpdate(dt) if engine.paused then drive(dt) end end
```
A scene `entrypoint.luau` declaring the same two hook names is dispatched
by the scene loader, not by this table: there `update` needs play AND
running, `editorUpdate` needs edit, and play-paused ticks neither. Read
`man scenes` before carrying a component's rule to an entrypoint.
## Authoring conventions
- Annotate public fields with `--!desc` so the inspector + LSP show
documentation alongside the field name.
- Declare lifecycle hooks (`start`, `update`, `onDestroy`) explicitly
rather than relying on engine defaults — readers can see at a glance
what runs when.
- Keep `update(dt)` cheap — it runs every frame per instance. Move
heavy work to `start`, to a `.computeShader`, or behind a job (`man jobs`).
- For multi-entity batching, prefer
`tools.use("entityOps", "addComponents", targets, components)` over
a loop of `entity(id).component.add` — it takes many targets and
many components in one call.
## Common pitfalls
- **Naming.** The component identity is the folder stem with
`.component` stripped (e.g. `<Spinner>.component/` → identity
`Spinner`). Don't repeat the suffix in the identity passed to
`component.add`.
- **`init.lua` vs `init.luau`.** Either is accepted (it's a
`one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both
in one folder is invalid.
- **`update` in edit mode.** It runs whenever the gameplay clock is
running, and entering edit stops that clock — so `update` is idle in
a freshly-entered edit session and ticks again the moment anything
sets `engine.paused = false`. Use `tools.use("wld", "play")` to test
update logic under the mode it ships in; `tools.use("wld", "edit")`
to return. See **Per-frame hooks and the two axes** above.
- **Renaming.** Renaming the folder changes the identity. References
to the component are recorded against the component itself, so
renaming or moving it does not break them.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service`: a declarative content generator, no per-entity state.
- `.preset` — a captured component configuration, replayable into
`component.add` without re-typing fields.
- `.bundle` — entity hierarchies that may carry component attachments
as part of the bundle.
## In the Inspector
Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
▲ 0↑ born
# guide
A guide is a single-file documentation asset: a `<name>.guide/` folder whose body is `guide.md`, surfaced through the `guides` MCP tool, the `man` shell builtin and the Docs panel. Drop one anywhere under `/zero/source/`, a `.package` included, and it shows beside the built-in guides.
## Linking guides together
A markdown link in a guide is followed when it is clicked in the Docs panel: `[Bindings](controls-guide)` opens another guide by any name `guides read` takes, `[Slots](#save-slots)` a heading of the same guide (its text in lower case, punctuation removed, spaces turned into `-`), `[Slots](save-kit#save-slots)` a heading of another, and `[the module](../saveKit.module)` a file or asset, relative to the guide's own folder. A link the panel cannot follow says why above the guide.
## In the Inspector
Guide: the guide's word count, its headings, and **Open in Docs**, which opens it in the Docs panel.
▲ 0↑ born
# generator.clock
A Generator's clock, frame by frame: the live sources it polls, the material clocks and live material values it writes, the playhead it presents, the transport its peers share, advancing time, cooking again once the device returns, building the graph again once something it was built from moved (`followBuild`), and the tick each frame runs.
One part of the `Generator` component. `~.generator` installs it on a
Generator instance's context table, `gen`, which the component makes
once per instance: the part keeps its shared state and the operations
other parts call as fields of `gen`, and what only it reads as locals of
its install function, so every instance holds its own.
▲ 0↑ born
# generator.cook
Cooking a Generator's graph: the outputs it resolves, the node and frame caches a cook reads and fills, the cook's own state and costs, the world values a graph follows, the pacing of a cook on a worker, the inputs a cook takes, the evaluation of one output, and the per-node placement the `playback` report reads.
One part of the `Generator` component. `~.generator` installs it on a
Generator instance's context table, `gen`, which the component makes
once per instance: the part keeps its shared state and the operations
other parts call as fields of `gen`, and what only it reads as locals of
its install function, so every instance holds its own.
▲ 0↑ born
# generator.diskcache
A Generator's disk cache and baked snapshot: the outputs a graph declares `diskCache` on, loaded from the world's cache, the writes a commit makes for them, and the snapshot an earlier engine stored with the scene.
One part of the `Generator` component. `~.generator` installs it on a
Generator instance's context table, `gen`, which the component makes
once per instance: the part keeps its shared state and the operations
other parts call as fields of `gen`, and what only it reads as locals of
its install function, so every instance holds its own.
▲ 0↑ born
# Shader (asset type)
A shader is a WGSL program that runs on the GPU. Materials reference shaders and
supply property values; renderable entities reference materials, not shaders
directly. This README is the canonical reference for writing **every** kind of
shader — it covers all domains, the surface authoring contract, the material
property schema, the engine library functions you can call, and how a shader
registers and compiles.
> New to how shaders, materials, meshes, and textures relate as assets and live
> GPU resources? Read `core/resource-model` first.
## Folder shape
A `.shader` is a folder asset:
```
<name>.shader/
shader.wgsl # the WGSL body (required)
properties.yaml # the material property schema (optional; surface shaders)
README.md # a one-paragraph description of THIS shader (required)
.metadata # asset metadata
```
Each file carries a committed `.meta` sidecar pinning its stable guid. The
identity is `<name>` (the `.shader` suffix strips).
A shader's material properties are exactly the ones its `properties.yaml`
declares: a shader with no `properties.yaml` declares none, and the engine
reads no property from the WGSL body. A `.wgsl` file standing on its own,
outside a `.shader` folder, is WGSL source rather than a shader: a material
draws with the `.shader` folder that holds it as `shader.wgsl`. Materials and other assets
reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw
string.
## Domains
The first line of `shader.wgsl` declares the domain:
```wgsl
// @domain: surface
```
| Domain | What it is | You write |
|---|---|---|
| `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. |
| `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `compute` | GPU data processing, no rasterization. | An `@compute @workgroup_size(...)` entry over storage buffers; you write the `@group/@binding` lines yourself. For compute work, the `.computeShader` assetType (see below) generates them for you. |
`// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui`
as further spellings of `post-process` and `screen`. A body carrying no
`@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body
declares, a further spelling as the domain it names. Any other name is refused where the shader
registers, with an error naming the spellings that resolve, so a shader reaches
the renderer only under a domain the compiler scaffolds.
Particles are drawn and simulated through these domains like anything else: the
particle package's `particle_sprite` and `particle_mesh` are `surface` shaders,
and its simulation, culling and sorting steps are `.computeShader` assets.
## Texture coordinate space
A shader that samples a texture through a coordinate it builds itself declares
which space that coordinate lives in, on a line beside `@domain:`:
```wgsl
// @domain: surface
// @uv_space: world
```
| Value | The coordinate | A material's `uv_scale` means |
|---|---|---|
| `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. |
| `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. |
Texture residency reads the declaration to work out how finely a frame samples
each texture: a material laying eight copies of its texture across a surface
samples each copy at an eighth of the surface's size, and the mip level that
serves it is three levels coarser than the surface's own footprint implies.
Leaving the line out puts the shader in mesh space, which is what sampling
`input.uv` is. `renderer.textureStreaming().textures` reads back the span each
texture was measured at and the level that span asked for.
**Compute shaders have their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`.
**Surface**, **sky**, **post-process**, and **screen** shaders all get
engine-generated scaffolding — you write only `fragment()` and declare properties in
`properties.yaml`; the engine generates the entry points and the group(1) material
interface. (Each domain's `fragment` takes a domain-specific input instead of
`FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and
"Post-process & screen shaders" below.) Compute shaders get the same treatment via
the separate `.computeShader` assetType (write only `@compute fn main`, declare
bindings in `bindings.yaml`). The `compute` domain here writes its own
entry points directly — see `man compute`.
## Surface shaders
A surface shader writes **only** the parts that are unique to it. The engine owns
all the scaffolding — the vertex stage, every render-mode entry point
(`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights,
shadows, and the material rows), and the material interface generated from
`properties.yaml` (`material` and your texture slots). Adding a render path never
touches your shader.
Inside `fragment()` you have access to exactly four things — nothing is hidden:
1. **`input: FragmentData`** — the interpolated per-fragment surface data the
engine hands you: world position, world normal, uv, view direction, vertex
colour, and more. Every field is in the `FragmentData` table below.
2. **`material.*` and your textures** — the material inputs **you** declare in
`properties.yaml`. The mapping is mechanical: a scalar property named `foo`
becomes `material.foo`; a texture property named `bar` becomes `bar` (the
texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields
your `properties.yaml` declares and no others — to add an input, add a property.
List what a shader exposes with `shaderRef:getProperties()` or
`asset.inspect("<name>")`.
3. **Engine state** — the scene's camera, lights, time, and shadows that the
renderer binds for every surface shader. In a surface shader `uniforms.*`
(sun direction/colour, ambient, `camera_pos`, `time`) and the punctual
lights (`zero_point_light(i)`) are always in scope (a post-process shader
has neither; its section below names what it reads instead); the shadow functions come from `#include "@builtin::shaderModules.shadows"`,
and the light of the sky, the reflection probes and the light-probe volumes
from `zero_pbr_surroundings_light` in `@builtin::shaderModules.pbr_shading`. This is how
you light a surface **without** the prebuilt PBR — see "Engine state" and
"Writing your own shading" below.
4. **Library functions** you `#include` (see "Library includes").
A shader and its property schema go together. The two files below are a complete
surface shader:
`properties.yaml` — declares the material inputs:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: base_color_texture, type: texture, default: white }
```
`shader.wgsl`; those declarations are read as `material.base_color`,
`material.roughness`, `material.metallic`, and the `base_color_texture` /
`base_color_texture_sampler` pair:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes"
fn fragment(input: FragmentData) -> vec4<f32> {
var s = zero_pbr_default_surface(input);
s.albedo = material.base_color.rgb
* textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb;
s.perceptual_roughness = material.roughness;
s.metallic = material.metallic;
return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a);
}
```
`fragment()` returns the final colour. The engine forces no lighting model on
you — flat, toon, PS1, dithered, or PBR are all just different `fragment()`
bodies. Calling `zero_pbr_shade` is opt-in.
### The two surface bodies, and what each gives up
A surface shader exposes one of two entry points, and which one decides how
much of the shader the engine can see:
| Body | The engine gets | PBR debug passes and the G-buffer read |
|---|---|---|
| `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the surface behind it where the body hands one over: `zero_pbr_shade` hands over the `PbrSurface` it lights, and a body that lights itself hands over its own with `zero_publish_shaded_surface` | the surface the body handed over; where it handed none, the debug passes draw magenta, the "no data here" marker |
| `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the surface |
Both are first-class: `fragment()` is what you want when the shader owns its
own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }`
(and `roughness` / `metallic` / `ao` / `emissive`) answers about your material
for either body wherever the engine has the surface — writing the same
`PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives
one answer per channel. `pbr.shader` exposes `surface()`.
#### Handing the engine the surface a self-lit body draws
A `fragment()` body that lights itself by its own math (toon, cel, flat, PS1,
dithered) states the surface it draws with one call, always in scope in a
surface shader:
```wgsl
zero_publish_shaded_surface(albedo, normal, emissive, perceptual_roughness, metallic, occlusion);
```
| Argument | Type | What it states |
|---|---|---|
| `albedo` | `vec3<f32>` | the colour the surface reflects, linear, in [0, 1] |
| `normal` | `vec3<f32>` | the world-space normal the body shades with (normal map applied) |
| `emissive` | `vec3<f32>` | the light the surface gives off, linear |
| `perceptual_roughness` | `f32` | 0 a mirror, 1 fully rough |
| `metallic` | `f32` | 0 a dielectric, 1 a metal |
| `occlusion` | `f32` | the material's own ambient occlusion, 1 none |
The call changes nothing about the pixel the body returns; it states what that
pixel is a picture of. The last call before `fragment()` returns is the one
the engine reads, and it reads it into:
- **The debug passes**: `albedo`, `roughness`, `metallic`, `ao`, `emissive` and
`reflection` answer with the stated surface instead of magenta, and `normal`,
`shadow` and `shadow_depth` read the stated normal.
- **The G-buffer**, on the deferred render path: its normal (`@scene.normal`,
`zero_scene_normal`) carries the stated normal, and its material
(`@scene.material`, `zero_scene_material`) the stated albedo, metallic and
roughness. Every screen-space feature and full-frame pass that reads the
surfaces reads these, among them screen-space reflections, contact shadows,
capsule occlusion, area lights, the environment lighting and radiance cache
passes, surface weather, temporal antialiasing's surface restate, and a
post-process effect or render feature reading the surface helpers.
A `fragment()` body that hands over nothing leaves the G-buffer holding the
triangle's interpolated normal, a base colour equal to the colour it returned
brought into [0, 1] by its largest component, metallic 0 and roughness 1, so
a pass that reads roughness takes it for a fully rough dielectric.
The emissive argument reaches the `emissive` debug pass. The light a surface
gives off is already in the colour its body returns, so it adds nothing to the
frame; `@scene.emissive` holds the light a later pass stamps onto the surface.
A cel-shaded body, its surface handed over:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = zero_take_scene_decal(material.base_color.rgb);
let sun = normalize(-input.light_direction);
// The sun's N·L rounded to the nearest third: 0 on a face turned from the sun.
let band = round(max(dot(n, sun), 0.0) * 3.0) / 3.0;
let lit = input.light_color * input.light_intensity * band / ZPBR_PI
+ zero_pbr_surroundings_light(input, n, albedo);
zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0);
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
`capture { pass = "normal" }` is a geometry read rather than a material one, so
it answers for every shader: the normal of the surface where one was handed
over, and the interpolated normal of the triangle where none was. It is the same
normal the frame's normal buffer carries, which is what a screen-space pass
reading `@scene.normal` sees.
`shaderRef:shadingModel()` reports which one a shader ended up with —
`"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`.
#### Decals on a self-lit body
A decal projector stamps its colour over the opaque surfaces before anything
shades (`@scene.decal`). `zero_pbr_shade` lays it over the base colour it
lights, so a `surface()` material and a `fragment()` body lighting through
`zero_pbr_shade` show the decal lit and shadowed like the rest of the surface.
A body that lights itself takes the decal the same way by passing its base
colour through one call before its lighting:
```wgsl
let albedo = zero_take_scene_decal(material.base_color.rgb);
```
A body that takes none gets the decal laid over the colour it returned, unlit,
and over the albedo it published.
### Optional vertex hooks
```wgsl
// Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the
// already-skinned, morph-applied local position). Return the modified vertex.
// The `v` parameter is immutable (WGSL function params are), so copy it into a
// `var` first and modify that.
fn vertex(v: VertexData) -> VertexData {
var out = v;
out.position += out.normal * sin(out.time) * 0.1;
return out;
}
// Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two
// things you can do here, separately or together:
// * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering;
// * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its
// world_normal + the light context and the engine forwards the result into the
// interpolated `vertex_color` the fragment reads.
fn vertex_clip(v: ClipVertex) -> ClipVertex {
var out = v;
// Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading).
let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0);
let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l;
out.color = vec4<f32>(v.color.rgb * lit, v.color.a);
out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap
return out;
}
```
#### Geometry built per instance: grass, kelp, hair cards, debris
`vertex()` knows which vertex of which instance it places:
`VertexData.vertex_index` is the vertex's index in its mesh and
`VertexData.instance_id` the instance's slot, whose lanes
`zero_object_data(v.instance_id, lane)` reads. A hook can therefore build its
geometry rather than displace it: a strip mesh drawn thousands of times by
`renderer.mesh.drawInstanced`, each copy shaped, sized and bent from the lanes
of its `instanceDataBuffer`, becomes a field of grass blades, kelp fronds or
hair cards that sway with `v.time`. Being a surface shader, it is lit,
shadowed (it casts the shape the hook built), motion-vectored and fogged like
the rest of the scene. The rendering-instance-data guide
(`guides { path = "topics/rendering-instance-data" }`) has a worked blade
field; a render feature's raster pass (`types/rasterShader`) is the
hand-written alternative, a vertex and fragment program with its own pipeline.
#### Declaring how far a hook moves geometry: `vertexBoundsDilation`
Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges:
```yaml
properties:
- { name: sway, type: float, default: 0.5, min: 0, max: 4 }
# 0.4 x sway, at sway's largest value.
- { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 }
```
Each material sets its own value (a material that sways less can set less, one moved farther sets more), and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; no camera view culls its geometry, by frustum, screen size or occlusion, so every camera draws it wherever it stands.
### Structs the engine passes you
`FragmentData` (input to `fragment()`):
| Field | Type | Meaning |
|---|---|---|
| `world_position` | `vec3<f32>` | fragment world-space position |
| `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) |
| `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) |
| `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) |
| `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping |
| `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) |
| `view_position` | `vec3<f32>` | camera world position |
| `view_direction` | `vec3<f32>` | normalized world-space direction the camera sees this point from: toward the camera's position under a perspective projection, against its forward axis (the same for every point) under an orthographic one |
| `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down |
| `light_color` | `vec3<f32>` | sun colour |
| `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera |
| `ambient_color` | `vec3<f32>` | the colour of the scene's flat ambient term, one colour for every direction. The light of the reflection probes and the light-probe volumes along a normal, which a PBR surface takes as well, is `zero_pbr_surroundings_light`; a sky light adds the sky's light to the surface the G-buffer holds on the deferred path, and `zero_pbr_surroundings_light` holds it on the forward path (see "Engine state") |
| `ambient_intensity` | `f32` | the flat ambient term's intensity as it reaches this pixel: the scene's ambient occlusion is already in it (times `ambient_visibility`), so a crease darkens under the ambient with no work in the shader |
| `ambient_visibility` | `f32` | the share of the light of its surroundings that reaches this pixel: 1 minus the scene's ambient occlusion here, 1 where nothing occludes it. Multiply it into any light of the surroundings you gather yourself (a sky colour, a reflection-probe or environment sample); `ambient_intensity` already carries it. `zero_scene_bent_normal(input.frag_coord.xy, n)` names the direction the open part of the hemisphere faces, `n` where no pass wrote one |
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither |
| `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows |
| `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name |
| `instance_id` | `u32` | per-instance: the instance's slot, the value `VertexData.instance_id` carries. `zero_normal_matrix(input.instance_id)` is the transform that turns an object-space normal into a world normal |
| `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes |
| `front_facing` | `bool` | true for front faces (double-sided shading) |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
`shader_data` is the per-instance channel, and it is what lets ONE material serve
many entities that differ in a value — a dissolve at its own progress per subject,
a hit flash at its own age, a fill level per instance. The alternative is a
material per entity, which is a separate pipeline binding and a separate row in
the material table for every one of them.
```wgsl
const DISSOLVE_LANE: u32 = 0u;
fn fragment(input: FragmentData) -> vec4<f32> {
let progress = input.shader_data[DISSOLVE_LANE].x;
...
}
```
```lua
-- one material on twenty entities, each at its own progress
renderer.instanceData.set(subject, 0, progress)
renderer.instanceData.clear(subject) -- back to zero lanes
```
The engine attaches no meaning to a lane: a shader and whatever writes it agree
what each one carries. Name the indices in the module that writes them.
`renderer.instanceData.laneCount()` is how many there are. The same lanes reach a
hardware-instanced population through `renderer.mesh.drawInstanced`'s
`instanceDataBuffer`, on slots no entity owns.
`VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph
applied; on a skinned mesh, where this frame's pose holds it), `rest_position`
(object-local, where the vertex stands at rest: before its morph targets and its
pose, the same place every frame, so a pattern or a placed image laid in it stays
on the skin however the skeleton moves it; on a mesh no skin poses, the position
as the mesh stores it; in a depth view, the position), `normal`, `uv`, `color`,
`time`, and which vertex of which instance it
is: `instance_id` (`u32`, the instance's slot — `zero_object_data(v.instance_id,
lane)` reads the lanes the fragment gets as `shader_data`) and `vertex_index`
(`u32`, the vertex's index in its mesh). Both hold the same values in the colour
pass, the depth views, every shadow page and the previous-frame evaluation, so
geometry a hook builds from them — a blade placed and bent by its instance's
lanes, a strip shaped by its vertex's index — lands in the same place in each.
The rendering-instance-data guide has a worked blade field.
`ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context:
`clip_position`, `world_position`, `world_normal`, `uv`, `view_position`,
`view_direction`, `light_direction`, `light_color`, `light_intensity`,
`ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of
the frame being evaluated), and where the vertex stands on its instance:
`local_position` (its position in the mesh, after `vertex()` and before the
instance's world transform), `object_origin` (the world position of the instance's
origin), `object_scale` (the world length of the instance's x, y and z axes) and
`object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) —
what a camera-facing card, a shard grown about its own base, or anything placed
per instance is built from. **Writable:** `clip_position` (snap /
jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the
engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's
own vertex colour passes through).
`vertex()` and `vertex_clip()` run in the vertex stage, which reads the frame
uniforms (`uniforms.*`, and the `ClipVertex` members built from them), the scene
buffer (`zero_object_data`, `zero_object_visuals`, the node transforms), the
material interface and a `read` buffer property. The point, spot and area lights
(`zero_point_light`, `zero_punctual_projection`), the shadow maps, the
environment and light probes, the feature textures, the scene depth, colour and
reflection copies and a `@group(2)` buffer the shader declares `read_write` are
visible to the fragment stage alone: read them in `fragment()` or `surface()`. A
shader whose vertex hook reaches one fails to compile, and the error names the
stage, the binding and the calls that reach it.
### Each hook runs twice: this frame and the one before it
A vertex hook decides where the surface IS, so it also decides where the surface
WAS. The engine runs every hook a shader declares a second time, over the same
vertex standing one frame back — the previous-frame position stream, with
`time` = the clock that frame was drawn at and (for `vertex_clip()`)
`view_proj` = the view-projection it was drawn with. The motion vector the
renderer publishes is taken between the two results, so a displacement that
moves with time reports the velocity of the displaced surface, and a
displacement that does not move reports the motion of the transform alone
because the identical offset appears on both evaluations and cancels.
What that asks of a hook:
- **Take the frame from the argument.** `v.time` is the clock of the evaluation
being run; `uniforms.time` is always this frame's. A displacement built on
`uniforms.time` is identical on both evaluations, so its motion vector cancels
to exactly zero. The same holds for `v.view_proj` against
`uniforms.view_proj`: a clip hook that rebuilds its position from world space
through `uniforms.view_proj` reprojects the previous frame with this frame's
camera, and reports no camera motion at all. The wind helpers come in both
shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)`
inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one.
- **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously
— a falling drop that restarts at the top, a looping offset — differences its
jump as velocity on whichever frame it wraps. Compute the wrap COUNT from
`uniforms.time` and the position within the cycle from `v.time`, and both
evaluations share the same cycle, so the surface reports the speed it fell at.
`@builtin::shaders.rain_material` and `snow_material` do exactly that.
The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and
camera-position context are this frame's on both evaluations, so a hook that
displaces along its normal reports the motion of the transform plus this frame's
displacement.
## Engine state — point lights & shadows
This is what the renderer binds for a **surface** shader. A post-process
shader reads none of it: its engine state is `PostEngineData` (see
"Post-process & screen shaders"), and a full-frame effect driven by the scene's
lights takes the render-feature route that section names.
The common lighting state — the sun (`input.light_direction` / `light_color` /
`light_intensity`), the scene's flat ambient term (`input.ambient_color` /
`ambient_intensity`), the camera (`input.view_position` / `view_direction`), and
`input.time` — is already on `FragmentData`, so most shaders never touch the raw
engine state. The flat ambient term is one colour for every direction; the
light the reflection probes and the baked light-probe volumes hand a surface
along its normal comes from `zero_pbr_surroundings_light(input, n, albedo)`
(`@builtin::shaderModules.pbr_shading`), which holds the flat term as well and is
the ambient light a PBR surface is lit by. The sky's light reaches a surface
through a sky light (`@builtin::systems.sky.skyLight`). On the deferred path it
adds that light to every lit pixel by the surface the G-buffer holds there: a
self-lit body's is the one it publishes (see "Handing the engine the surface a
self-lit body draws"), so a body that publishes its surface takes the sky's
light a PBR surface takes. On the forward path, and for every surface the
G-buffer pass does not draw (transparent, water), the sky light fills the
environment's sky slot and `zero_pbr_surroundings_light` holds its diffuse
light. The one thing not
on `FragmentData` is the punctual-light array (its length varies), which is always
in scope. A scene can hold up to 1024 lights, so a fragment walks the ones the
light grid lists where it stands, which hold every light that can reach it:
| Expression | Type | Meaning |
|---|---|---|
| `zero_lights_near(world_pos)` | `ZeroLightsNear` | the lights that can reach a fragment at `world_pos`; `.count` of them |
| `zero_light_near(near, k)` | `u32` | the index of the `k`th of them, for `zero_point_light` |
| `uniforms.point_light_count` | `u32` | number of lights the frame shades under, every one of them |
| `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) |
| `zero_punctual_projection(i)` | `PunctualProjection` | a spot or area light's projection: `view_proj`, the frustum its cookie and shadow are placed by, and `cookie_layer` |
`PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`,
`cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot).
Shadows come from `#include "@builtin::shaderModules.shadows"`:
- `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed.
- `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each.
- `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch.
- `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing.
## Writing your own shading
The engine forces no lighting model — `zero_pbr_shade` is just one option. You can
light a surface yourself from the state above. Here is a complete custom-lit
(Lambert diffuse) surface that takes the engine's lights and surroundings and
no PBR BRDF:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light; brings in the shadow functions
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = material.base_color.rgb;
// Directional (sun) light: Lambert N·L, attenuated by its shadow.
let sun = normalize(-input.light_direction); // surface -> sun
let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction);
var direct = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow;
// Point + spot lights: the ones that can reach this fragment.
let near = zero_lights_near(input.world_position);
for (var k = 0u; k < near.count; k = k + 1u) {
let pl = zero_point_light(zero_light_near(near, k));
let to_light = pl.position - input.world_position;
let dist = length(to_light);
let l = to_light / max(dist, 1e-4);
let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0);
direct += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten;
}
// A Lambert surface sends back albedo / π of the direct light on it,
// the diffuse lobe of the PBR model.
var lit = direct / ZPBR_PI;
// The light of the surroundings: the flat ambient, the reflection probes
// and the baked light-probe volumes, with the scene's ambient occlusion in
// it — the ambient light a PBR surface takes. It is irradiance already
// weighed for a diffuse surface, so it takes no π.
lit += zero_pbr_surroundings_light(input, n, albedo);
// The surface this pixel draws, for the debug passes and the G-buffer; a
// sky light adds the sky's light to the surface stated here.
zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0);
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
The example declares `base_color` in its `properties.yaml`:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
```
- **Unlit:** skip the lights and return your colour directly.
- **Toon / PS1 / custom:** start from the body above and band, quantize, or warp
it however you like. Keep the direct light over π and `zero_pbr_surroundings_light`
as the ambient term, and the surface stands at the brightness of the PBR
materials around it; the flat
ambient (`input.ambient_color * input.ambient_intensity`) alone leaves out the
reflection probes and the light-probe volumes.
- **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes")
instead of writing the BRDF by hand. It hands the engine the surface itself.
## Material properties — `properties.yaml`
A surface shader declares its material properties in a sibling `properties.yaml`.
The engine GENERATES the entire group(1) interface from it — the uniform struct
(`material.<name>`) plus a texture/sampler pair per declared texture. You write
no `@group`/`@binding` lines.
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: emissive, type: color, default: [0, 0, 0, 1] }
- { name: base_color_texture, type: texture, default: white }
- { name: normal_texture, type: texture, default: flat_normal }
```
| `type` | WGSL field type | Notes |
|---|---|---|
| `float` | `f32` | optional `min`/`max` for editor sliders |
| `float2`/`float3`/`float4` | `vec2/3/4<f32>` | |
| `color` | `vec4<f32>` | linear RGB colour and alpha, default is `[r,g,b,a]`; the shader reads it as written |
| `int` | `i32` | |
| `bool` | `u32` | |
| `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) |
A `color` holds linear RGB, the space lighting is computed in, the way `base_color` multiplies a colour texture's
linear sample. A colour picked from a picture or written as a hex code is sRGB, and written as it is it reads paler
and less saturated than picked: convert it first, `color.toLinear(assert(color.hex("#ff8800")))` (`{ r, g, b, a }`:
`#ff8800` is `{ r = 1, g = 0.246, b = 0, a = 1 }`), and write that.
In the shader you read scalars as `material.<name>` and sample textures as
`textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture
samples its default, so a shader can always sample — no presence flag needed.
`vertex()` reads the same material interface, so a height or deformation map
drives displacement from the slot it was bound to. A vertex stage has no implicit
derivatives, so sample it at an explicit mip there:
`textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`.
## Sky shaders
A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only**
`fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each
pixel — and declare tunables in `properties.yaml` exactly like a surface shader
(read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`).
The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface,
and reconstructs the world-space ray; there is no separate sky renderer — a sky
material runs through the same material pipeline, just on a fullscreen triangle.
A sky pipeline binds group(0) and the group(1) interface alone, so a sky that
reads a `buffer` property or any other `@group(2)` binding fails to compile, and
the error names the binding and the calls that reach it.
`SkyInput` (the only argument) carries:
| Field | Type | Meaning |
|---|---|---|
| `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel |
| `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` |
| `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) |
| `camera_pos` | `vec3<f32>` | world-space camera position |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `constants` | `SkyConstants` | what the shader's `sky_constants()` returned for this draw (zeros when it declares none) |
```wgsl
// @domain: sky
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up);
return vec4<f32>(col * material.exposure, 1.0);
}
```
Day/night comes from `sun_direction.y` (the directional light's elevation), so a
sky shader never needs a time-of-day uniform — orient the light and the sky
follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`,
`equirect_sky`) are all authored this way; author a custom sky material and point
a `Skybox` component at it.
`fragment()` runs once for every pixel of the view and every texel of each
environment-capture face. A value that holds for the whole draw (a colour mixed
from the material and the sun's elevation, a `cos` of an angular size, an
exponent derived from a property) goes in an optional
`fn sky_constants(in: SkyConstantsInput) -> SkyConstants`, which the generated
vertex stage evaluates once per draw. `fragment()` reads its result as
`in.constants`. `SkyConstantsInput` carries `sun_direction`, `camera_pos` and
`time` (the same values `SkyInput` holds), `sky_constants()` reads the material
as `material.<name>` like `fragment()`, and `SkyConstants` is eight `vec4<f32>`
slots, `v0` to `v7`, packed however the sky likes:
```wgsl
// @domain: sky
fn sky_constants(in: SkyConstantsInput) -> SkyConstants {
let day = clamp(in.sun_direction.y * 2.0, 0.0, 1.0);
var c: SkyConstants;
c.v0 = vec4<f32>(mix(vec3<f32>(0.02), material.zenith_color.rgb, day), day);
c.v1 = vec4<f32>(mix(vec3<f32>(0.01), material.horizon_color.rgb, day), 0.0);
return c;
}
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
return vec4<f32>(mix(in.constants.v1.rgb, in.constants.v0.rgb, up), 1.0);
}
```
A branch on an `in.constants` value is taken or skipped by every pixel of the
draw together, so a term that only contributes some of the time (stars at
night) costs nothing while it is off. The vertex stage has no implicit
derivatives, so a texture read in `sky_constants()` is `textureSampleLevel`.
## Post-process & screen shaders
`// @domain: post-process` and `// @domain: screen` shaders are authored exactly
like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>`
(post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables
in `properties.yaml` (read as `material.<name>`, textures via
`textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen
`vs_main`/`fs_main` and the group(1) material interface. **There are no
`uniforms.params[i]` slots** — that convention is retired; every input is a named
property.
A **post-process** shader's `properties.yaml` carries one further, top-level key
beside `properties:` — `space`, either `light` (the default) or `display`:
```yaml
space: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
`light` is the scene's linear radiance — what every surface, the sky and every
`afterLighting` feature write, unbounded above 1.0. `display` is the code values
the `__display__` pass leaves behind after applying exposure and its tone curve
— the 0-1 range a colourist's tool and a dithered or quantized effect expect.
`postprocess.add`'s `opts.space` overrides what the asset declares for one
registration. The chain converts at both ends of an effect that runs on a
segment in the other space, so a light-space vignette still darkens a frame
graded after `__display__`, and a lookup table built from a `.cube` export
always sees the code values it was authored against, wherever the chain
runs it.
`space` also decides which layer a registration that names none lands on: a
`light` shader grades `scene`, the segment holding the scene's own light, and a
`display` shader grades `display`, the picture after `__display__` and before
the UI lands on it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom",
"shader"))` thresholds highlights that still stand above 1.0, and a lookup
table registered the same way reads the code values it was built for and leaves
every screen in the colours it declares. `opts.layer` names one explicitly —
`"all"`, after the UI, is what an effect that must grade the interface says.
A post-process shader may also declare the post stage of the frame it runs in,
`stage:` — `optics` (the `scene` layer), `display` (the `display` layer) or
`ui` (the `all` layer); `renderer.post.stages()` lists every stage with the
colour space and resolution its picture is held in. A registration takes the
declared stage unless `opts.stage` or `opts.layer` names another seam, and a
stage the frame does not have, or one only render features run in, is refused
naming the stages there are:
```yaml
space: display
stage: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
A **post-process** shader's `properties.yaml` carries a further, optional
top-level key — `passes:`, the pass list the frame draws through, in order:
```yaml
space: light
passes:
- { name: bright, entry: bright, scale: 0.5, inputs: [scene] }
- { name: down1, entry: downsample, scale: 0.25, inputs: [bright] }
- { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] }
- { name: composite, entry: composite, inputs: [scene, up0] }
```
Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the
one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the
view a pass draws at; the LAST pass takes none, since it draws at the view's
size and writes the chain's output. `lines`, optional, is a frame height the
pass's size is measured against: a pass declaring `lines: 1080` draws at the
size it has in a 1080-line view of the same shape, `scale` times 1080 texels
tall and as wide as the view's shape makes it, so each of its texels spans
the same share of the view's height at every output resolution and a filter
measured in its texels covers the same share of the picture on a phone, a
monitor and a 4K screen. A pass that would draw larger than the view draws
at the view's own size. `maxLines`, optional, is the tallest view the pass's
size is measured against: a pass declaring `scale: 0.5, maxLines: 1080` draws
at half of a view 1080 lines tall or shorter, and at the size it has in a
1080-line view of the same shape on a taller one, 540 texels tall at 1440 and
at 2160 lines, so it costs a 4K screen no more texels than a 1080p one while a
smaller view draws it at its own half. A pass declares one of `lines` and
`maxLines`. `inputs` names what a pass reads —
`"scene"`, the chain's input for this effect, or the name of an EARLIER pass —
and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body;
every input, `inputs[0]` included, is also reachable by index through
`zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place
the two reads of `inputs[0]` disagree: in an effect whose declared space
differs from the segment it draws on, `zero_sample_scene` converts a `scene`
input into that space while `zero_pass_input(0, uv)` hands back the segment's
own, unconverted value. A shader declaring no `passes:` is one pass whose
entry is `fragment`, and its generated WGSL is byte-identical to what it is
without the key.
A pass that is not the last writes a scratch target the effect owns — in the
space the shader declared, at the size its `scale` and `lines` or `maxLines` give it —
allocated on the first draw and replaced whenever the size changes. `engine.params`, below,
carries the drawing pass's own index, the fraction of the view it draws at
(its `lines` or `maxLines` applied), and its first input's texel size, so one shader body serves every
level of a chain built this way.
The worked example is the bloom: `@builtin::shaders.post.bloom` declares
sixteen passes — a threshold pass, seven downsamples, seven tent upsamples and
a composite — out of four entries, since the seven downsamples share one and
the seven upsamples share another, each level reading the one below it through
`zero_pass_input`, telling itself apart by its own size (`engine.resolution`)
and its inputs' (`zero_pass_input_size`), and weighing itself by the share of
the frame's height its texel spans. Its own README
walks the declaration.
A declaration is refused at compile time — reported through `compileStatus()`,
`postprocess.add`'s second return value, or a live effect's
`status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does
not define; an input naming a later pass, or naming neither `scene` nor an
earlier pass; a `scale` outside `(0, 1]`; a `scale`, a `lines` or a `maxLines` declared
on the last pass; a negative or non-finite `lines` or `maxLines`; a pass declaring both
`lines` and `maxLines`;
a `buffer` property (group(2) carries the pass inputs); or a shader whose
group(0) plus declared texture slots plus widest pass's inputs ask for more
than the 16 FRAGMENT sampled textures one shader stage has.
A **post-process** shader runs as a full-screen pass over the already-rendered
frame. Its `fragment` argument and framework helpers:
`PostInput`:
| Field | Type | Meaning |
|---|---|---|
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) |
| `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right |
Framework helpers (always in scope — no include needed):
| Call | Returns | Meaning |
|---|---|---|
| `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) |
| `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" |
| `zero_linear_depth_through(d, engine.view_proj, zero_camera_position())` | `f32` | that sample as a distance in metres along the camera's view axis, read through the camera that drew it: its near and far planes and its kind of projection — the one inversion of the reversed range (`zero_linear_depth(d, near, far)` is the perspective inversion given the planes themselves) |
| `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` |
| `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads |
| `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain |
| `zero_view_size()` | `vec2<f32>` | the size in pixels of the view the pass draws for: the frame the chain delivers, whatever fraction of it the pass draws at. A filter measured against it (a fraction of the frame's height) holds one look at every output resolution |
| `zero_camera_position()` | `vec3<f32>` | the world position of the camera the render being drawn looks from — the camera `engine.view_proj` belongs to, so on a capture or a render-to-texture camera it is that camera's. With a world position reconstructed from `zero_scene_depth(uv)` and `engine.inv_view_proj`, `normalize(world - zero_camera_position())` is the view ray |
| `zero_scene_surfaces_drawn()` | `bool` | whether the scene's surface channels (the helpers below) hold the surfaces of the render being drawn: true on the deferred path from `afterOpaque` on, false on the forward path, which draws no G-buffer |
| `zero_scene_normal(uv)` | `vec3<f32>` | the world-space normal of the surface at `uv` (`@scene.normal`), unit length; +Z where no surface stands, (0, 0, 0) where `zero_scene_surfaces_drawn()` is false |
| `zero_scene_surface_flags(uv)` | `u32` | the surface flags the geometry pass wrote at `uv` (`@builtin::shaderModules.surface_flags`' `ZERO_SURFACE_FLAG_*`, in scope with the helper); 0 where `zero_scene_surfaces_drawn()` is false |
| `zero_scene_material(uv)` | `ZeroGbufferMaterial` | what the surface at `uv` IS (`@scene.material`): `.base_color`, `.metallic`, `.perceptual_roughness`, each in [0, 1], unpacked by `@builtin::shaderModules.gbuffer_material`, which the surface group includes |
| `zero_scene_shaded(uv)` | `vec4<f32>` | what the surface at `uv` SENT (`@scene.shaded`): its shaded colour, linear, with its coverage in alpha |
| `zero_scene_emissive(uv)` | `vec4<f32>` | the radiance passes stamped on the surface at `uv` (`@scene.emissive`) |
| `zero_display_exposure()` | `f32` | the exposure in force: the gain `__display__` multiplies the scene's light by before its curve, the value this frame's display pass draws with (1 where the chain carries none). Light times it is light in the units the picture shows it at, so a threshold judged against `light * zero_display_exposure()` picks the same highlights at every exposure |
| `zero_middle_grey()` | `f32` | for an effect in light: the light `zero_sample_scene` reads that the picture shows as middle grey, 0.18 over the exposure in force on a segment holding the scene's light and 0.18 on a segment `__display__` already drew. What a grade pivots its contrast on, so middle grey holds where the picture shows it at every exposure |
| `zero_picture_white()` | `f32` | for an effect in light: the light the picture's white stands at, the peak a grade holds. 1 (the white an SDR picture peaks at) on a segment `__display__` already drew, and 0 on a segment holding the scene's light, which has no peak |
Engine data uniform `engine` (a `PostEngineData`):
| Field | Type | Meaning |
|---|---|---|
| `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height |
| `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index |
| `view_proj` | `mat4x4<f32>` | this frame's view-projection |
| `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) |
| `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) |
| `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. |
| `exposure` | `vec4<f32>` | `x`=the exposure in force (what `zero_display_exposure()` reads) |
| `camera_position` | `vec4<f32>` | `xyz`=the world position of the camera being drawn (what `zero_camera_position()` reads) |
| `surfaces` | `vec4<f32>` | `x`=1 where the surface helpers read the render's own surfaces (what `zero_scene_surfaces_drawn()` reads) |
| `view` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height of the view the pass draws for (what `zero_view_size()` reads); the same as `resolution` on a pass drawn at the view's size |
The engine fills all of it **per render target**. A registered effect runs over
the live viewport's frame AND over every offscreen one — a `capture` from a
world-space station or orbiting an entity, a capture of a named camera, a
render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj`
and `inv_view_proj` are the camera THAT render was drawn from, while
`resolution` is that target's own pixel size. So a pass reconstructing world
space from `zero_scene_depth(uv)` reconstructs against the station and lens the
capture asked for, and an offscreen frame is a picture of the effect as it
stands at that station. (A render feature's passes reach an offscreen render the
same way, against the same camera — the `renderFeature` assetType README carries
that half, including `@frame.camera`, its own per-target camera input.)
**The scene's surfaces.** The surface helpers above read the deferred path's
G-buffer, the same channels a render feature names as `@scene.normal`,
`@scene.material`, `@scene.shaded` and `@scene.emissive`, by screen uv at the
exact texel (the channels are at the scene's raster size, so a pass at a
`scale`, or after an upscale, reads the surface that stands at that point of
the picture). A shader that names any of them compiles with the surface group,
`group(3)`, which spends four of the stage's sampled textures beside its own
slots and pass inputs; the render keeps a channel only while a running effect,
or a render-feature pass's shader, reads it; a channel counts as read when an
entry point of the compiled shader reaches its helper, so a helper in an
included function nothing calls reads nothing. They hold this frame's surfaces
at every layer of the chain and at every render-feature phase from
`afterOpaque` on. With temporal antialiasing running, every layer of the chain
reads the normal and the material restated at each pixel's centre, with no
sub-pixel offset, so an outline found in the normals holds still under a still
camera; `zero_scene_shaded` and
`zero_scene_emissive` read the raster's own, with its sub-pixel offset. The
renderFeature type README states the whole contract by stage and path.
The forward path draws no G-buffer, so there every helper reads zero and
`zero_scene_surfaces_drawn()` false: a look that needs the surfaces draws a
picture of its own there (from depth, say) instead of reading a wrong one, and
`postprocess.status()` names the channels the effect `reads` and, after a frame
it drew with the substitute, the `substituteReason`.
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let c = zero_sample_scene(in.uv);
if !zero_scene_surfaces_drawn() || zero_scene_depth(in.uv) <= 0.0 { return c; }
let n = zero_scene_normal(in.uv);
let m = zero_scene_material(in.uv);
let rim = pow(1.0 - abs(n.y), 4.0);
return vec4<f32>(mix(c.rgb, m.base_color, rim * material.amount), c.a);
}
```
**Lights.** A post-process shader reads no light data: `uniforms`,
`zero_point_light(i)` and the light grid are the surface framework's, and a
post shader naming them does not compile. An effect driven by the scene's
lights (light shafts, a glow around each lamp, a scatter through fog) is a
render feature pass at a scene phase (`afterDepthPrepass` through
`afterLighting`) that binds `@scene.lights`, the punctual-light buffer (the
renderFeature type README states its layout), with `@frame.camera` for the
camera; the beams lights throw through the air are already the built-in
`VolumetricLighting` component, whose `lightScattering` render feature
(`@builtin::systems.volumetrics`) marches the view rays through the scene's own
lights.
An offscreen render keeps no view history of its own, so `prev_view_proj` there
holds that same matrix rather than the frame before it, and a pass taking camera
motion from the two reads none. On the viewport the pair is a frame apart, so
camera motion is the one reading a capture answers differently from the screen.
`postProcessing = false` on a capture is the one control that takes the chain
off the frame it returns; it names the camera property the ephemeral capture
camera is built with, so it scopes to that one capture. What a capture opts out
of is the registered effects; `__display__` still runs on it, so the exposure
and tone curve that turn the scene's light into a picture are on what a capture
returns.
A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses
`__display__` itself, since a channel like that is a reading of the scene
rather than a graded picture of it. The environment-cube capture bypasses it
too, and for the same reason: a probe face carries radiance into the cube
array, and `__display__` would fit that radiance to a display's code values —
a picture of it rather than the value the PBR indirect term multiplies into
its lighting.
A complete post-process effect — a vignette via `fragment()` + `properties.yaml`:
`properties.yaml`:
```yaml
properties:
- { name: intensity, type: float, default: 0.5, min: 0, max: 1 }
- { name: radius, type: float, default: 0.75, min: 0, max: 1 }
- { name: softness, type: float, default: 0.45, min: 0, max: 1 }
```
`shader.wgsl`:
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let color = zero_sample_scene(in.uv);
let intensity = max(material.intensity, 0.01);
let radius = max(material.radius, 0.01);
let softness = max(material.softness, 0.01);
let center = in.uv - vec2<f32>(0.5);
let dist = length(center);
let vignette = smoothstep(radius, radius - softness, dist);
let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity);
return vec4<f32>(darkened, color.a);
}
```
The asset above **defines** the effect. It enters the frame when something
registers it:
```luau
postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 })
```
The registration names no layer, so the effect grades the layer its `space`
belongs to: this vignette reads light, so it runs on `scene`, over the picture
before the UI reaches it. Registering it is the one step that makes it render,
so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards
recompiles every effect registered from it, in place — the pass keeps its enabled
state, priority, layer, tuned property values and bound textures, and draws the
new pixels on the next frame. `postprocess.remove(name)` takes it back out of the
chain and leaves the asset alone.
Drive the named properties at runtime with `postprocess.setProperty(name, prop,
value)` and bind texture properties with `postprocess.setTexture(name, prop, path)`
(both keyed by the **property name**, never a slot index — see the post-process
section of `man shaders` / the `postprocess.*` API).
Read them back with `postprocess.describe(name)`: it carries the chain state
`postprocess.status()` lists for that effect, the `properties` schema it was
registered with, and the `values` each of those properties currently holds. Before
the effect exists, `shaderRef:getProperties()` on the asset names the same schema,
so what a pass takes is answerable either side of the registration.
A **screen** shader is a standalone full-screen visual (UI background, procedural
pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene
to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a
`ScreenEngineData`:
| Field | Type | Meaning |
|---|---|---|
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `scroll` | `f32` | UI scroll offset |
| `resolution` | `vec2<f32>` | render-target size in pixels |
| `mouse` | `vec2<f32>` | mouse position |
| `velocity` | `f32` | scroll velocity |
```wgsl
// @domain: screen
fn fragment(in: ScreenInput) -> vec4<f32> {
let t = engine.time * 0.5;
let col = vec3<f32>(
sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5,
sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5,
material.brightness
);
return vec4<f32>(col, 1.0);
}
```
## Library includes
A library module is a **`.shaderModule` asset**: it only EXPOSES functions and
structs and does nothing on its own (exactly like a Unity `.cginc`). You must
call what you include. Include one by its identity, the same string you would
hand `asset.resolve`:
| Include | Exposes |
|---|---|
| `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting); `zero_pbr_indirect_visibility(FragmentData, PbrSurface) -> ZpbrIndirectVisibility` (the share of the surroundings' light each indirect lobe takes from the scene's ambient occlusion: `diffuse` with the light a crease bounces back, `specular` from the open cone around the bent normal, and `specular_traced`, the material's own occlusion alone, for the part of the reflection a screen-space trace found); `zero_pbr_shade_with_visibility(FragmentData, PbrSurface, ZpbrIndirectVisibility) -> vec3<f32>` (the same lighting with that share stated by the caller); `zero_pbr_surroundings_light(FragmentData, n, albedo) -> vec3<f32>` (the diffuse light the surroundings hand the surface along `n` as `zero_pbr_shade`'s diffuse lobe takes it — lightmap, flat ambient, reflection probes, light-probe volumes, the sky light's diffuse light where the G-buffer pass does not draw the surface, the scene's occlusion — for a self-lit body to multiply by its colour); `zero_pbr_sun_visibility(FragmentData, PbrSurface) -> vec4<f32>` (the sun as it reaches the surface: rgb what translucent casters and a medium leave of it, a the share its shadow maps leave, zero where it puts no light on the surface), which a surface scales on its own terms and hands back in `PbrSurface.sun_visibility` |
| `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)`; each light's `_with_kernel` form takes a shared `ZShadowKernel` (`zshadow_kernel()`) so several lookups of one fragment derive its filter rotation once |
| `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access |
| `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions |
| `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) |
| `@builtin::shaderModules.periodic_noise` | Value noise that repeats along x, for a pattern laid around a circle (a sky over the azimuth, a ring): `zero_azimuth(dir)` (the azimuth about +Y as a fraction of a turn, wrapping along -X), `zero_periodic_noise(p, period)`, `zero_periodic_fbm(p, period, octaves, lacunarity)` (each octave fits a whole number of cells in `period`, so the sum repeats every `period` and a pattern whose x runs over one period per turn closes with no seam), `zero_wrap_cell(cell, period)` and `zero_hash21(p)` for a lattice of one's own |
| `@builtin::shaderModules.parallax` | Parallax occlusion for any lit shader with a height map: `zero_parallax(depth, max_steps) -> ZeroParallax` (the relief's depth in UV units, its steps, its fade distances and whether R is height or depth); `zero_parallax_march(FragmentData, height_texture, height_sampler, uv, ZeroParallax) -> ZeroParallaxHit` (the UV to read every map at, with `ddx`/`ddy` for `textureSampleGrad`); `zero_parallax_sun_visibility(FragmentData, PbrSurface, height_texture, height_sampler, hit, ZeroParallax) -> vec4<f32>` (the sun with the relief's self-shadow, for `PbrSurface.sun_visibility`, marched only where the sun lights); `zero_parallax_self_shadow(...)`
▲ -1↑ born
backing path · systems/procgen.package
Problems
Everything affecting this asset right now: its own problems, anything wrong inside it, and problems on its direct dependencies.
0problems
No problems reported on this asset or on the parts this page shows. Parts it leaves out are not counted here.
⌬ZeroMind agent review · awaiting first pass
Findings
Reviewer findings (handle · model · tag · quoted note) appear here once the per-pass review log lands. Today only the rolled-up
agent_score is exposed.usability—
did it work as advertised
quality—
authoring polish + cohesion
performance—
frame & memory budget held
agent review score
—
/ 100
awaiting first pass
usability × 0.40
+ quality × 0.35
+ performance × 0.25
± compat factor
+ quality × 0.35
+ performance × 0.25
± compat factor
Usability ratings
Did the part work as advertised when consumers tried to drop it in. Separate from upvotes: those are taste; this is "did it function".
—%no reports yet
Sign in to report whether this part worked for you.
Discussion
Scoped to this part · feeds back into the world's score.
0comments
Sign in to post.sign in
No comments yet. Be the first.