# Module (asset type)
A module is Luau code that runs when other code calls it: other code
pulls it in with `require()` and calls its functions. It has no
lifecycle hooks or callbacks; nothing attaches it to an entity or runs
it every frame. Anything that is code can be a module: a whole game
system (rules, an inventory, a level generator, a match flow), a
helper, a format parser, a registry, a shared algorithm. The engine's
own APIs (`physics`, `input`, `audio`, `camera`, `entity`, `asset`,
`http` and the rest) are modules.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the code runs on an entity, driven by hooks and callbacks, use a
`.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# vfs Module
Public Luau surface over the `__vfs` Internal FFI namespace — the
engine's virtual filesystem.
## Purpose
Wrap the raw `__vfs.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.vfs` via the prelude. The standard read / write /
move / remove / mkdir / list / exists / readAsync / reload / evict
surface, plus trusted-only `watch` / `unwatch` for the bootstrap VM.
`vfs.read` yields on a byte-cache miss: the module's last step installs
the `vfs_async_read` fallback over the synchronous read, so every VM that
holds this namespace, the trusted VM included, reads a path through the
same two steps and gets the same bytes for it.
## Usage
```luau
-- Read / write
local src = vfs.read("/zero/source/libs/@builtin/components/Camera.component/init.luau")
vfs.write("/zero/source/notes.md", body)
-- What a write landed: where the bytes went, and what the static passes
-- read in the Luau among them
local ok, report = vfs.write("/zero/source/game/Vent.component/init.luau", code)
if report.diagnostics then
for _, d in report.diagnostics do
print(d.severity, d.path, d.line, d.message)
end
end
if not report.durable then
log.warn(report.warning)
end
-- Listing
for _, e in ipairs(vfs.list("/zero/source")) do
print(e.isDirectory and "[d] " or " ", e.name)
end
-- Async fetch
local png = task.await(vfs.readAsync("/zero/runtime/screenshots/last.png"))
-- Reclaim RAM after processing a big binary
vfs.evict("/zero/source/textures/imported_huge.png")
-- Reload a module after editing its source on disk
if vfs.reload("@builtin::modules.json") then
local m = require("@builtin::modules.json") -- sees the new source
end
```
`vfs.reload(identity)` answers whether a module was cached under that name
and has now been dropped. A `false` says the name matched nothing — either a
misspelled identity or a module this VM never required — so the next
`require()` returns whatever it would have returned anyway.
A module that caches state derived from OTHER files keeps serving the old
value when those files are rewritten, since only its own source is watched.
Reload it by identity to make the next `require()` recompute.
## How a write reaches disk
A native engine's `vfs.write` returns once the engine holds the bytes and the
session's journal holds the record of the write, its bytes with it. The record
is in the operating system's hands before the call returns, so an engine
process that ends right after a write, however it ends, leaves the write for
the next session on the same machine to owe and make again. The blob a binary
write stores by content is written and flushed by a worker thread (`vfs-io`) in
the order the writes were made, so a script that writes a thousand files pays
for handing them over and for their journal records, not for the flush of
each. A read of a blob still waiting for its file answers from memory, so a
write reads back the moment it returns. A queue holding more than its byte
budget (256 MiB) makes the next write wait for it and write inline, which
bounds the memory the queue pins. The queue is flushed when the engine exits
normally. `world.syncStatus()` reports nothing owed once the writes have also
reached the world.
## Exports
- `vfs.read(path, opts?) -> string?`
- `vfs.write(path, content, opts?) -> (boolean, WriteReport | string)`
- `vfs.move(src, dst, opts?) -> (boolean, WriteReport | string)`
- `vfs.copy(src, dst) -> (boolean, WriteReport | string)`
- `vfs.remove(path, opts?) -> (boolean, string?)`
- `vfs.mkdir(path, opts?) -> boolean`
- `vfs.list(path?) -> { VfsListEntry }`
- `vfs.exists(path, opts?) -> boolean`
- `vfs.readAsync(path, opts?) -> promiseId`
- `vfs.reload(modulePath?) -> boolean`
- `vfs.evict(path, opts?) -> boolean`
- `vfs.mutationSeq() -> number`
- `vfs.contentClock() -> number`
- Trusted-only: `vfs.watch(path, callback) -> number` /
`vfs.unwatch(watcherId) -> boolean`.
# asset Module
Public Luau surface over the `__asset` Internal FFI namespace —
asset resolver, ref envelope builder, sidecar metadata.
## Purpose
Wrap the raw `__asset.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.asset` via the prelude. Three families:
- **Lookup** — `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`. Every op accepts any name an
asset has (handle, guid, identity, path, bare name) and returns
the requested view.
- **Discovery** — `categories`, `list`, `containing`.
- **Generic `.metadata` sidecar** — `metadata`, `set_metadata`,
field-level `get_field` / `set_field` / `remove_field` /
`has_field`, tag helpers (`tags`, `has_tag`, `add_tag`,
`remove_tag`), and `validate`.
The previously-FFI `bundle.*` namespace was dissolved into the
bundle assetType (see `@builtin::assetTypes.bundle`);
that's not exposed here. The prelude mints `bundle` separately as
a thin Luau table grafted from `bundle_update`.
## Usage
```luau
-- Lookup
local cam = asset.resolve("@builtin::components.Camera")
local ref = asset.ref("animations.idle", "animation")
print(asset.identity(cam), asset.guid(cam), asset.source(cam))
-- Discovery
for _, c in ipairs(asset.categories()) do print(c) end
for _, sceneRef in ipairs(asset.list("scene")) do print(sceneRef.identity) end
local s = asset.containing("/zero/source/scenes/main.scene/scene.json")
-- Metadata sidecar (agent-editable)
asset.set_field(ref, "category", "movement")
asset.add_tag(ref, "looping")
print(asset.has_tag(ref, "looping"))
-- Structural validation
local v = asset.validate(cam)
for _, p in ipairs(v.problems) do print(p.severity, p.message) end
```
## Exports
- Lookup: `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`.
- Discovery: `categories`, `list`, `containing`.
- `.metadata` sidecar: `metadata`, `set_metadata`, `get_field`,
`set_field`, `remove_field`, `has_field`, `tags`, `has_tag`,
`add_tag`, `remove_tag`, `list_fields`, `list_field_values`.
- Validation: `validate`.
# modules.api.engine.engine
The `engine` global's Luau implementation. Exposes `engine.mode` (edit
vs play), `engine.onModeChange(callback)` subscription registry, and
the mode-flip orchestration that fires the canonical onModeChange
dispatch through `ENGINE_MODE_WATCHERS`.
# json
JSON encode/decode library for Luau. Encodes Lua values to JSON
strings and decodes JSON strings back to Lua values. Used for
communication with the Rust side of the engine, the VFS read/write
bridge, and any wire-format that needs JSON.
Pure Luau, no engine dependencies. Compact and pretty-printed
encoders, plus a hand-rolled decoder that streams the input by position
so it works under WASM as well as native.
## Exports
- `Json.encode(value: any, indent?: string, currentIndent?: string) -> string` — compact encode. Functions / unknown types and NaN/Inf encode as `null`.
- `Json.encodePretty(value: any, indentStr?: string) -> string` — pretty-printed encode with sorted object keys (diff-friendly).
- `Json.encodeArgs(...: any) -> string` — encode varargs as a JSON array.
- `Json.null` — the value that stands for JSON `null` inside a table. A key set to nil is left out of the encoded object; a key set to `Json.null` is written `"key":null`, which is how a request names a field it clears. `decode` answers `null` as nil.
- `Json.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure. The string is one JSON value with optional whitespace around it; anything else after the value is a failure naming the character and its position.
## Usage
```luau
local Json = require("@builtin::modules.json")
local widget = { type = "button", text = "Click Me" }
local compact = Json.encode(widget) -- '{"text":"Click Me","type":"button"}'
local pretty = Json.encodePretty(widget, " ")
local decoded = Json.decode(compact)
local v, err = Json.decode("oops") -- v = nil, err = error message
```
## Notes
- Object keys are sorted alphabetically in both encoders for consistent
output across runs.
- Numeric keys on objects are stringified at encode time (JSON has no
numeric keys). Pure-integer key sets get detected as arrays via
`isArray` and encoded with brackets.
- NaN, +Inf, -Inf encode as `null` — JSON has no representation. Round
trips through `decode` recover `null` (Lua `nil`), so they don't
preserve.
- Unicode `\uXXXX` escapes decode to UTF-8 by hand to stay WASM-safe.
Only the BMP is covered; supplementary planes via surrogate pairs
are not.
- Functions encode as `null`.
- Decode is character-streamed — no regex, no `string.match` patterns
on the whole input — so the line-and-column information needs to be
reconstructed from the position offset.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `interfaces:` | The interfaces every asset of the type implements (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
| `contexts:` | The environment the engine loads a file of the asset into, and what it holds (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export?, export_optional? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## Computed output files
A type can declare files produced by its compiler. Each rule names an exact
asset-relative output path, an activation marker, and guidance for editing the
inputs:
```yaml
computed_files:
- path: "cache.json"
when_exists: "authoring/state.json"
edit: "Edit the recipe and run the asset compiler."
```
Once the marker exists, ordinary writes, removal and individual-file moves are
refused for that output. The marker and output paths stay within the asset.
Declare their folders in `files.required` or `files.optional` as usual.
Compilers commit their outputs with the input revisions through
`modules.sourceOperations.materialize`. A complete asset copy to a new
destination carries its inputs and computed files together. Copying individual
files into protected outputs and merging a tree over protected outputs are
refused before destination leaves change.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. A type that lists `sceneInstantiable` under `interfaces:` guarantees it, and its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `implements`, `as`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
| `validateCommitted` | `(folder, read) -> { { code, message, severity?, remedy? } }` | On every push, for each asset the push changes, over the asset as the commit the push publishes holds it. `read(file)` answers a file's committed text, relative to the asset's folder, or nil for a file the commit holds no text of. A problem of `error` severity (the default) refuses the push, whatever the working tree holds. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
An asset whose picture is what it does to a scene rather than what it looks
like (a lighting setup) names a `subject` on an `instantiate` recipe: a
scene-instantiable asset stood in the studio in its place, while the asset
itself is applied to the world (`applicable`, owner `preview`) for the
shot and dropped after it. `studio_light: false` photographs the subject under
the world's lighting, which the applied asset states, instead of the studio's;
such a picture renders only on an explicit request (`preview.writePreview`,
`assets.generatePreviews`, staging), never from the preview queue or a live
preview.
```yaml
preview:
kind: instantiate
subject: "@builtin::preview.subjects.lookdev"
studio_light: false
```
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in, or a list of categories: a name
there is recorded as the one asset of those categories it answers to, a name
two of them answer to is recorded as neither, and a name written as a path
ending in one of their suffixes is the asset at that path.
A key whose names are assets of any type implementing an interface is stated
under `interfaceKeys`, and is declared typed to the types that implement the
interface, again whenever a type or an interface changes:
```yaml
references:
interfaceKeys:
- { key: "members", implements: applicable, field: "source" }
```
`asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
A JSON or YAML data file of your type is read whole for the references it holds:
every `{ __ref }` envelope, `@` identity and `components` entry in it. When a file
also keeps values that are data rather than links (an edit history holding the
asset a field used to name, say), `documents` names the fields that carry its
links, and the rest of the file is read as data:
```yaml
references:
documents:
- path: authoring/entities/ # every file under this folder of the asset
fields:
- [records, "*", references] # keys from the root; "*" is every entry of a list or mapping
- references
- path: authoring/settings.json # this one file
fields: [references]
```
`path` is inside the asset's folder; the longest `path` covering a file decides
it. Each value a field reaches is read whole. A file that holds none of the
fields is read whole, as is every file no `path` covers. An entry with no valid
`path` or `fields` is refused with a warning naming it.
## What your type guarantees (`interfaces:`)
An interface is an asset (`<name>.interface/`, see the `interface` type) that
states a guarantee: members with signatures, and properties. A type lists the
interfaces its assets implement in its `type.yaml`:
```yaml
interfaces: [sceneInstantiable]
```
Every asset of the type implements every interface the type lists; an asset of
a type that lists nothing never does. The key is a reference to `interface`
assets, so each name resolves like any asset name and is recorded by guid in the
type's reference table, which is where the engine reads the type's marks from.
The `indexing:` role named `interface` is a different thing: it names the file
that states the signatures a caller of an asset uses.
The type meets each member in its `behavior.luau`, implicitly with its own
`M.ref.<member>` of the member's name and signature, or explicitly when its own
method of that name means something else:
```lua
M.ref = { apply = function(self, into) ... end } -- the type's own meaning
M.interfaces = {
applicable = { apply = function(self, owner, values, opts) ... end },
}
```
`M.interfaces` is keyed by the interface's name as the type lists it. A property
the interface states is met by a value or a getter `(self) -> value` in the same
two places, else by the interface's default. A type whose own `<member>` is
shared by two interfaces with different signatures meets at least one of them
explicitly.
| Question | Call |
|---|---|
| Does this asset implement X? | `ref:implements("X")` (a name, identity or guid, or a list meaning any of) |
| Call a member through the interface | `ref:as("X"):member(...)`; `ref:as("X").property` reads a property |
`ref:as("X")` raises, naming the asset and `X`, when the type does not implement
it. A direct `ref:member(...)` reaches the type's own method of that name; when
the type meets the member implicitly, that method is the member and the call goes
through the interface's gate, which checks its inputs and its result. A generic
caller (one that knows only the interface) calls through `:as`.
A declaration that breaks a check is refused: it carries no marks, `asset.validate`
reports each problem as an error that refuses a push, and the engine log states
each once. The codes are `interfaces.shape`, `unknown`, `ambiguous`, `duplicate`,
`missing`, `arity`, `typeKey`, `explicitUnclaimed`, `explicitUnknown`,
`propertyMissing`, `propertyType`, `conflict` and `unloadable`; each message names
the type, the file, the fault and what to write instead. A type that defines
`instantiate` and lists no `interfaces:` (one written before the key existed, or
defined by its `behavior.luau` alone) implements `sceneInstantiable` with the
warning `interfaces.implied`, which names the line to add. `asset.inspect` of an asset lists the interfaces its type
implements, and of a type definition lists them under `detail.interfaces` with
`detail.interfaceProblems` when the declaration was refused. The type's
Inspector shows the same under **Interfaces**: one row per interface (its name,
the first line of its description, and whether the type declares it or it is
implied), then every problem the declaration raised. An interface's own
Inspector shows its guarantee, its contract module and conformance suite, every
member with its signature, inputs and output, and the types that implement it.
The asset browser's **Implements** filter narrows the list to the assets whose
type implements the interface chosen, each interface's description as its
tooltip.
## The environment a file runs in (`contexts:`)
A type whose assets hold a script the engine loads itself states the environment that script runs in, so the engine binds it and the language server checks the script against the same names:
```yaml
contexts:
- name: sceneBuild
file: "build.luau"
surface: "scene's `build.luau`"
globals:
build: "the build surface is bound in a scene's `build.luau`'s own environment, where `build.asset` authors ..."
hooks: [content, editorOnly]
modules: true
```
- `name` is the context's name.
- `file` is the file of the asset folder that runs in the context.
- `surface` names that file in a diagnostic, without an article.
- `globals` are the names the type's loader binds into each run of the file. Each carries the note an unknown-global message gives when the name is used in a file that lacks it.
- `hooks` are the functions the engine calls by name from the file, which the language server does not report as unused.
- `modules: true` says the loader binds the exports of the modules that join the context.
A module joins with `--!context <name>` in its leading comment block. The type's loader builds the environment with `ScriptContext.bind(env, path, values)` (the `script_context` module), which refuses a value the context does not declare. `asset.context(path)` reads the context a file runs in.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# 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.
# 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`.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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;
}
```
# 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"
```
·computeshader · born here
❒asset # 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.
# 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.
·computeshader · born here
❒asset # bvh_codes
A 30-bit Morton code for each primitive of a geometry: its bounds centre,
normalized inside the scene bounds and interleaved bit by bit. Sorting
primitives by this code puts primitives that are near in space near in the
order, which is what the `bvh` kernel builds its tree from. It reads the points
(`pts`), the point each vertex reads (`vpt`), each primitive's `vstart` and
`vcount`, and the scene bounds `lo` and `hi` (xyz each: a min and a max reduce
of the points), and writes `codes`, one word per primitive, 0 for a primitive
with no vertices. The `geometry.bvh` node runs it, sorts the codes and hands
both to `bvh`. Dispatch over the primitives. Exact.
·computeshader · born here
❒asset # 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.
# 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.
# 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.
·computeshader · born here
❒asset # 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.
# 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.
# 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); }
```
·computeshader · born here
❒asset # compact
Turns a keep mask into the indices of the kept elements, and the map back from
every element to the place it holds among them.
`indices` lists the elements whose mask word is not 0 (a float mask of 0.0 and
1.0 reads the same way), in run order; its live count is the number kept.
`inverse` holds, for every element, its place among the kept ones, or -1 for an
element that is not kept, so a column carried to the kept elements (a gather by
`indices`) and a column of per-kept values carried back (a read through
`inverse`) agree on which element is which. The nodes that keep a subset of
elements run it: `core.select`, `core.weld`, `core.edges`, `core.boundary`,
`core.islands`, `curve.grow`, `geometry.extrude`, `geometry.ribbon`,
`instances.to_points`, `sdf.mesh` and `sim.particles`.
The dispatch size `n` is the number of elements. One workgroup of 256 works the
whole run, 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).
·computeshader · born here
❒asset # concat
Joins one attribute of several geometries into one column. `sources` is a column
table with one column per geometry, in order, from column `first`; `desc` says,
from word `base`, where each geometry's elements start in the result, how many it
has, how far to shift each value of a linkage column, and whether the geometry
holds the attribute at all. Where it does not, its elements take the default
stated in the first four words of the description, their own place in their
geometry (`absent` 1), or -1 (`absent` 2). The joined column is `dst`, `n * lanes`
words.
The params are `lanes` (the words an element holds), `parts` (how many geometries
are joined), `first` and `base` (where this attribute's columns and description
begin), `kind`, `absent`, `moved` and `scale`.
Linkage is a shift: `vertex.pt` takes the number of points before the geometry,
`primitive.vstart` the number of vertices before it, and `point.id` the amount
that keeps the ids unique across the geometries. Any other attribute shifts by
0. `scale` multiplies every value before the shift moves it. With `moved` 1 a
negative value stays and only the others move: a column of point ids where -1
names no point.
`kind` states the word form of the joined column (0 f32, 1 i32, 2 u32): each
geometry's column is read as the value it holds, by the form its table entry
states, and written as that value in the joined form, so a column one geometry
holds as Int and another as Float joins by value. The default, 3, moves the words
as they stand.
A join of a whole geometry runs the kernel once per attribute of the union of the
geometries' attributes, with one description run for all of them
(`geometry.join`, and `proc.substrate.Geometry.merge` for geometries that count
their elements on the device, whose descriptions the device writes from the
counts).
Dispatch over `n`, the elements of the joined domain. Exact: each result
element has one writer.
·computeshader · born here
❒asset # contour_cells
Whether each cell of a grid of samples straddles the surface: its eight corner
samples hold both a value below zero and one at or above it. It reads `vals`,
the distance at every grid sample (x fastest), over the grid the params state
(`sx`, `sy` samples along x and y; `nx`, `ny`, `nz` cells; `ox`, `oy`, `oz` the
position of sample (0, 0, 0); `h` the cell size). `flag[c]` is 1 for a
straddling cell and 0 otherwise, the keep mask `compact` turns into the list of
cells that own a vertex. The `sdf.mesh` node runs it first.
Dispatch over the cells. Exact: each flag has one writer.
# 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"
```
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # contour_triangles
Each kept quad as two triangles: `pt` holds, per quad, the vertex numbers of
its corners (`a b c`, `a c d`), and `vstart` the position of each triangle's
first corner in `pt`. Slot `n` of the dispatch is the `n`-th quad `edges[n]`
names (the list `compact` makes of `quad_flag`), read from `quad_v` of
`contour_quads`, so the quads are numbered in edge order.
Dispatch over the kept quads. The `sdf.mesh` node dispatches over every grid
edge and states the kept count times 6 as the vertex count and times 2 as the
primitive count, so the slots past the kept quads lie past the live elements.
Exact: each slot has one writer.
·computeshader · born here
❒asset # edges
The sides of a mesh as point pairs: the first stage of the edge table. It reads
`pt` (the point each vertex reads), and each primitive's `vstart` and `vcount`.
One invocation per primitive writes, for every vertex slot of its run, the side
leaving that vertex as `lo`, `hi` (its lower and higher point), `face` (the owning
primitive) and `rev` (1 when the side runs from the higher point to the lower).
The outputs hold `nv` slots, a bind of the vertex count. A slot with no side (the
last vertex of an open run, a side joining a point to itself, a primitive with
fewer than two vertices) holds `ZERO_NONE` (the largest i32) in `lo` and `hi`
and -1 in `face`, so a sort puts it last. Integers are 32-bit words, exact.
The edge table is this kernel, a stable sort of the slots by `hi` and then by
`lo`, and the `edges_runs` kernel (run heads, then the table). The sort and
the compaction between are the `sort` and `compact` kernels; `edges_runs` states the
whole sequence, and the `core.edges` node runs it. `closed_all` is 1 for a mesh of
faces, which wrap; with 0 the `closed` column decides per primitive, for curves.
`np` is the number of primitives in the plain variant. Over a live count
(`COUNT=device`, see the abi README) the live primitives are read from
`domain_count` and the dispatch covers their capacity; that variant wraps every
primitive and binds no `closed`, which keeps it at 8 storage buffers (8 in the
plain variant).
·computeshader · born here
❒asset # 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).
·computeshader · born here
❒asset # expand
Turns a count per element into runs. Element `j` takes `counts[j]` slots, in
element order; slot `s` of the result holds `owner[s]`, the element it belongs
to, and `local_index[s]`, its place within that element's run. `offsets` is the
exclusive prefix sum of `counts` (what the `scan` kernel makes of it), so every
slot finds its element by a binary search and has one writer.
`owner` is an appended output: its live count is the sum of the counts, up to
the capacity the dispatch was given. Slots at and past the live count hold -1.
An element with a count of zero has no slot; a column of all zeros gives a live
count of zero.
Dispatch over `n`, the capacity of the result. Exact.
`core.owner` runs it to give every vertex its primitive and its place in the primitive's run. `core.realize`,
`core.pairs`, `core.adjacency`, `core.resample.curve`, `core.sample.surface`, `core.normals.corner` and the geometry
nodes that make new primitives (`geometry.extrude`, `geometry.sweep`, `geometry.triangulate`, `geometry.bevel` and
others) expand their counts with it.
Over a live count (`COUNT=device`, see the abi README) the elements are the first
`domain_count` of `counts` and `offsets`, so they can be held in runs larger than
their live count, and the counter of `owner` states the sum of their counts as it is,
above the capacity too: the first `n` slots are written and the sum minus `n` is how
many did not fit. A node that states `n` as a bound checks the count against it. The
plain variant clamps the count to `n`. It binds 6 storage buffers (5 in the plain
variant).
Over live elements (`ELEMENTS=device`) the elements are the first `element_count` of `counts` and `offsets`, whatever
`n` covers: a result sized by one class (the vertices) expanded from the elements of another (the primitives). It binds
one storage buffer more.
# 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"
```
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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).
·computeshader · born here
❒asset # 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`).
·computeshader · born here
❒asset ·computeshader · born here
❒asset ·computeshader · born here
❒asset # gather
Builds a column from another column and a run of indices: element `i` of the
result is element `index[i]` of `src`. An index below 0 or past the end of
`src` gives zeros. The element type is the `T` specialization (`f32`, `i32`,
and two to four lanes of either); a three-lane column is read and written
tightly packed, twelve bytes an element.
Dispatch over `n`, the number of indices. Exact: each result element has one
writer. It declares `fusion:` (the value of element `i` is `element(i)`, a thread
runs where `skip(i)` is false), so a chain of fused kernels evaluates it inside
one dispatch.
Most nodes that reorder, select or copy elements read their columns through it:
`core.select`, `core.concat`, `core.make`, `core.weld`, `attribute.gather`,
`attribute.promote`, `elements.sort` and the geometry nodes among them.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` slots are live: a slot at or past it holds zeros. It binds 4
storage buffers (3 in the plain variant), and `dst` holds `n` elements.
·computeshader · born here
❒asset # grid
Reads and writes a field of cells in one kernel. The field is a Grid (one tile,
no apron, x fastest, `lanes` values per cell) or a Raster (tiles with aprons,
one batched dispatch) through the layout in `tile_layout`.
- sample (`MODE sample`): the field at positions, nearest or trilinear, held to the
edge cell past the field. Reads each cell from the tile that owns it.
- write (`MODE write`): a patch of values blended into the field (replace, add,
max, min, multiply, optionally weighted per cell). Every tile that holds a cell
as core or apron receives it, so apron copies agree. The patch window is stated
in field cells and may reach past the field (negative origin, or a size beyond
the cell counts): a stored cell a border tile holds past the field takes the
patch where the window covers it.
- stencil (`MODE stencil`): per stored cell, a neighbour at an offset, slope in
degrees, curvature (the laplacian over x and z) or the gradient, with neighbour
reads held to the tile's own stored edge. Slope and curvature are the terrain
mask's. The gradient writes two values a cell, d/dx and d/dz per metre.
`MODE`, `SAMPLING` (nearest, trilinear), `STENCIL` (offset, slope, curvature, gradient) and `BLEND` (replace, add, max, min, multiply) are specializations.
The bindings: `field` (the field, read by sample and stencil), `aux` (the
positions, xyz a position, for sample; the patch values for write), `weight` (one
weight a patch cell, read by write when the param `hasWeight` is 1) and `out` (the
sampled column, the stencil result, or the field being written). Sample runs one
thread per position (`count` of them) and writes `outLanes` values each, from lane
`lane`; write and stencil run one thread per stored cell.
`determinism: exact`: each output element has one writer. The bindings a mode
does not use take any buffer of at least one element that is not bound elsewhere
in the dispatch.
`grid.sample` samples with it, `core.raster.blend` writes a patch into a raster
with it, and `core.raster.stencil` measures slope and curvature with it.
·computeshader · born here
❒asset # 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).
# 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.
·computeshader · born here
❒asset # hash_count
For each query position, how many indexed points lie within a radius of it,
searched through the spatial hash the `hash` and `hash_starts` kernels build. An
exclusive scan of the counts gives the offsets `hash_gather` writes each query's
neighbour list at; `core.pairs` runs the three in that order. Exact.
It reads `pts`, `order` and `range` (the index), `qpts` (xyz a query) and the
params `buckets`, `inv_cell`, `radius` and `skip_self` (1 leaves out the point
whose index is the query's, for queries that are the indexed points), and writes
`counts`, one a query. Dispatch over the queries.
·computeshader · born here
❒asset # 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).
·computeshader · born here
❒asset # hash_hook
One hooking round of the connected sets of the points that stand within a radius of each other, searched through
the spatial hash the `hash` and `hash_starts` kernels build. `label` names each point's root, and every point of a set
names the same root (a star); `hooked` starts as a copy of `label`. Every point walks the points within the radius and
lowers the entry of its own root in `hooked` to the smallest root among them, so after the round each root links to
the smallest root next to its set, or to itself. Links only ever point at a smaller root, so they form a forest, and
the `find` stage, which follows each point's links in `hooked` to their end and lowers its entry to that root, makes
every set a star again.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `STAGE` | `hook`, `find` | the hooking round over the hash (binds `pts`, `order`, `range`, `label`, `hooked`), or the walk of each point's links to its root (binds `hooked` alone) |
| `MATCH` | `position`, `normal` | every point within the radius is next to the point, or only one whose normal (`nrm`) is within `cos_angle` of its own |
| `COUNT` | `plain`, `device` | every slot is live, or the live count is read from `domain_count` |
A round of hooking then finding halves the number of sets that still have a neighbouring set every two rounds, so
twice as many rounds as the bits of the number of points leave every set a star of its smallest point. `core.weld`
folds that many rounds, with no read-back. Exact: the smallest root wins whatever order the invocations run in.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # hash_starts
Finishes a spatial hash: given each point's bucket and the permutation that
sorts the points by bucket, states for every bucket where its points start and
end in the sorted order. Each bucket finds its two places by binary search over
the sorted keys, so no bucket needs clearing and the answer is a function of the
keys alone. Exact.
Dispatch over the buckets. It reads `keys` (from `hash`), `order` (the sort's
permutation) and the param `points`, and writes `range`, two words a bucket: the
places `range[2k]` .. `range[2k + 1] - 1` hold bucket `k`'s points. `core.spatial`
finishes its index with it, and `hash_count`, `hash_gather`, `hash_nearest`,
`hash_repel` and `hash_hook` read `range`.
# 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.
# 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.
·computeshader · born here
❒asset # intersect_cuts
The segment each entry of `intersect_pairs` is cut along, one thread per entry. The thread reads the entry's
`a`, `b` and part and writes the part's two endpoints (`intersect_core` states the parts). An endpoint record
is 8 words: the position as f32 bits, the kind word (the kind in the low byte, which meshes the segment cuts
in bits 8 and 9), then `lo`, `hi`, `tri` and `extra`, which name the crossing; two endpoints, 16 words, an
entry. The endpoint slot `s = 2 * entry + e` names an endpoint to `intersect_unify` and `intersect_retri`.
A point on a shared edge writes the same record as both endpoints. Exact.
It binds `apts`, `atri`, `bpts`, `btri` and `pairs` and writes `cut`. Over a live count (`COUNT=device`, see the
abi README) an entry past the live ones is not read or written. `geometry.boolean` runs it.
·computeshader · born here
❒asset # intersect_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.
·computeshader · born here
❒asset # intersect_retri
The triangles of one mesh retriangulated along the segments that cut them. One thread per triangle: a
triangle no segment reaches is written as itself; a cut triangle is worked in its own plane, in world
lengths, where its corners and the cut endpoints are the points and its sides and the cut segments are the
constraints. The triangulation holds every constraint first (each cut out by the points that lie on it),
then holds the remaining candidate edges shortest first, a length class at a time (the exponent and top
three mantissa bits of the squared length), each when it crosses no held edge and has no point on it. The held edges are a planar graph: the
neighbours of each point are sorted by direction, the faces are walked with their inside on the left, a face
of three points is a triangle and a face of more is cut ear by ear (each ear a corner that turns left with no
other point of the face inside it or on its sides), and the face outside the triangle is left out. Every
triangle is wound the way the source triangle was, so the pieces of a triangle agree on the direction of every
side they share however thin the sliver between two cut points. A triangle whose three points stand on one
line in the world has no area and is left out. Every cut segment is a union of edges of the result, and the
pieces of a triangle tile it. Points and distances are compared within a few steps of the coordinates'
precision (`5e-7` of the largest coordinate of the triangle, and no less than `1e-7` of its longest side),
the same measure for a triangle of either mesh, so cut points a few millionths apart are told apart by the
triangles of both meshes alike.
Param `side` names the mesh the pass cuts, 0 for A and 1 for B; a segment cuts the mesh when its endpoint
records say so (`intersect_core`). A triangle takes every point of its entries, a segment of no length
giving a point on an edge and nothing more.
`STAGE count` writes how many triangles each triangle becomes; `STAGE write` writes them at the offsets of
the prefix sum, four words each (three vertex references, the source triangle) from word 4 of `out`. A
reference below `npts` is a point of the mesh; `npts + s` is the cut endpoint in slot `s`, which
`intersect_unify`'s `rep` names. `out[0]` is 1 when a triangle ran out of working space, which the sizing
below prevents. `geometry.boolean` builds the pieces of each mesh from `out`.
It binds `pts`, `tri`, `cut`, `runs`, `order` and `out`, with `cnt` in the count stage and `off` (the exclusive
prefix sum of the counts) in the write stage; the params are `npts`, `total`, `entries` and `side`. Over a live count
(`COUNT=device`, see the abi README) a triangle past the live ones becomes no triangle.
## Working space
A triangle takes a slice of working memory sized by its entries, so the number of points a triangle can
carry follows the data: a run of `m` entries gives at most `3 + 2 m` points, `3 + m` segments and three
edges a point, and the slice is `64 + 40 m` words. The slices of consecutive triangles follow one another
and make the tail of `out`, after its 4 header words and the `4 * total` words of the triangles
(`total` is 0 in the count stage): the slice of triangle `t` starts `64 * t + 40 * first(t)` words into the
tail, `first(t)` the first entry of its run, so the runs' firsts are the exclusive prefix sum of their
counts (the `start` of `intersect_pairs` for mesh A, the offsets of the per-b counts for mesh B). `out`
is sized `4 + 4 * total + 64 * n + 40 * entries` words from the params `total` and `entries` (the number of
entries of `intersect_pairs`).
The triangles of mesh A are grouped by `a` already (`runs` is `start` and the counts of
`intersect_pairs`, `order` the identity); for mesh B the entries are stably sorted by `b` first and
`order` holds the sorted entry indices. Exact: each triangle is worked alone and in a fixed order.
·computeshader · born here
❒asset # intersect_unify
The first slot of every cut point. Endpoint slots whose records name the same crossing (the kind word, `lo`,
`hi`, `tri` and `extra`) are one point; `rep[s]` is the lowest slot among them, which is the point's
identity. A slot with `rep[s] == s` is a new point's first slot, so a compaction of those slots
numbers the cut points, and every endpoint reference maps through `rep`.
Three dispatches (`STAGE claim`, `fold`, `resolve`) over a hash table `table` of `cells` words (a power of two,
at least twice the slot count) and a second table `lowest` of the same size, both zero before the first stage.
`table`, `lowest` and `rep` (one word a slot) carry from stage to stage: each stage is bound the three the stage
before it wrote, so `fold` reads the claims and `resolve` the cells `fold` recorded in `rep`. Exact: the cell a key
takes depends on thread timing, the answer does not.
Over a live count (`COUNT=device`, see the abi README) a slot past the live ones is not read or written.
`geometry.boolean` numbers its cut points with it.
·computeshader · born here
❒asset # 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).
·computeshader · born here
❒asset # 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).
·computeshader · born here
❒asset # loops_cut
Finds where each ring and chain of linked edges starts and ends. `STAGE head`
marks the first edge of every list (a chain's head, a ring's smallest edge) in
`head`, from `next` and `head0` (the `loops` outputs) and `label` and `par` (the
min rounds of `jump`); `STAGE cut` makes the edge before each first edge the end
of its list in `cut`. The lists that result are what `jump` ranks. See `loops`
for the whole sequence.
Over a live count (`COUNT=device`, see the abi README) the edges are the first
`domain_count` slots of a capacity `n`, and the `n` param is not read. A slot past
the live edges is no head (`head` 0) and ends its own list (`cut` is the slot itself).
It binds 7 storage buffers (6 in the plain variant).
·computeshader · born here
❒asset # 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).
# 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.
·computeshader · born here
❒asset # make
Builds the elements and the primitives of a geometry from a count per owner and
a shape (`points`, `strip`, `fan`, `grid`, `ring`, the `SHAPE` specialization).
The result is the columns a Geometry holds: `P` over the points, `vertex_pt` over
the vertices (the point each reads), and `prim_vstart` / `prim_vcount` over the
primitives (each one's run of vertices). All indices are into the result, so
owners' pieces sit end to end with their links already offset.
It runs as two passes of one shader (`PASS`): `sizes` writes the points,
vertices and primitives each owner makes; after a prefix sum of each component
into `bases`, `fill` writes every element once, found by a binary search over the
bases. Exact: each output element has one writer. The shape's layout is stated
at the top of `bindings.yaml`; `grid` takes its second axis from the `across`
param (default 2, at least 2).
`core.make` runs it: the `sizes` pass, a `scan` of the sizes, then the `fill`
pass, and the columns become the Geometry the node answers.
·computeshader · born here
❒asset # map
The per-element kernel: `dst[id] = TEMPLATE` over `n` elements. The template is
a WGSL expression over `p` (the element's position), `id`, the numbers `u_get(k)`
and the columns of the `cols` table; the preludes `rand`, `noise` and `color`
supply the functions a template calls. `fieldc.mapSpec` writes a chain of field
templates as one function, so a chain of any length is one dispatch.
Specialize `T` (f32, i32, vec2, vec3 or vec4 of f32), `TEMPLATE`, and optionally
`PRELUDE` and `POSITION`. Bind `cols` (a table from `compute_abi.table`) and `u`.
The output `dst` holds `n` elements of `T`, tightly packed. 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.
# 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); }
```
# 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); }
```
# 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.
# 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.
·computeshader · born here
❒asset # ray
Casts rays and segments against the triangles of a geometry through the
hierarchy the `bvh` kernel builds (closest hit, or any hit for occlusion), and
computes the generalized winding number of the geometry about each origin, which
is the inside test a boolean or a distance field needs. A hit is the parametric
t, the primitive index and the barycentric weights. The header of
`bindings.yaml` states the ray and hit layouts: a ray is 8 words of `rays`
(origin xyz, tmin, direction xyz, tmax); a miss writes t = -1 and `hit_prim`
0xffffffff. Exact: the same rays give the same hits, ties going to the lower
index.
`ray` binds `rays`, the geometry's `pts` (xyz a point), `vpt`, `vstart` and
`vcount`, and the `accel` node table the `bvh` kernel builds, with the `np` param
the number of primitives; the `STAGE` specialization picks `closest`, `any` or
`winding`. The winding stage sums over every primitive and reads only the origin
of each ray. `geometry.boolean` and `geometry.to_sdf` run the `winding`
stage for their inside test, and `sim.particles` runs `ray_shapes` for its
collisions.
`ray` is a family of three kernels, since one dispatch binds at most 8 storage
buffers a stage:
| Kernel | Answers |
|---|---|
| `ray` | `hit` (t, u, v, fan) and `hit_prim` (the primitive, the shape index of a mesh hit) for the `closest`, `any` and `winding` stages |
| `ray_surface` | for the `closest` hits `ray` found: `hit_normal` (unit triangle normal facing the ray's origin side) and `hit_end` (the hit point pushed out along the normal by the `skin` param; a miss answers the ray's end) |
| `ray_shapes` | the analytic shape table, bound as a `columns` binding (`shapeKind, center, extent, rotation, bounce, friction, index`; a plane's extent is its unit normal, a sphere's extent.x its radius): `hit`, `hit_prim` (the row of the shape table), `hit_normal`, `hit_end` |
Chain for a mesh: dispatch `ray` with `STAGE = closest`, then `ray_surface` with
the same `rays`, geometry bindings and the `hit` and `hit_prim` that `ray`
wrote.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # 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`.
·computeshader · born here
❒asset # 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.
# 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.
·computeshader · born here
❒asset # 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`.
·computeshader · born here
❒asset # scan_mat4
The running product of a run of 4x4 matrices, whole or per segment: the frames
of a sweep, each placed relative to the one before it.
A matrix is 16 consecutive floats, column by column. The product runs in run
order, so `out[i] = m[0] * m[1] * ... * m[i]`. `params.exclusive` picks the
product of the matrices before each one (the identity for the first) or the
product up to and including it. `total` holds each group's product, the
identity for an empty group. A segmented scan (`params.segments` above 0, the
number of segments) restarts at each start in `starts`.
One workgroup scans one group at a time, a tile of 128 matrices at a time, with
the product of everything before a tile carried into the next. The dispatch size
`n` is the number of matrices; any workgroup count from 1 up scans every group.
Exact: the order of multiplication is fixed, so the same run gives the same bits
on every dispatch.
·computeshader · born here
❒asset # 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.
·computeshader · born here
❒asset # search
Binary search of a run of queries in a sorted column: the pick of a value from
a cumulative distribution, the segment of an arc length.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `T` | `f32`, `i32` | the scalar the column and the queries hold |
| `SIDE` | `lower`, `upper` | which boundary a query answers |
`lower` answers the first place whose value is not below the query, `upper` the
first place whose value is above it, and both answer the length of the column
when no place qualifies. The greatest place whose value is not above a query is
`upper - 1`; with the cumulative sums of a run of weights, `upper` of a draw in
`[0, total)` is the index of the weight it lands in.
The column bound as `sorted` is the sorted run, every element of it. One thread
per query; the dispatch size `n` is the number of queries.
Exact: a search reads the column and nothing else, so the same inputs give the
same answers on every dispatch.
`core.sample.surface` picks a primitive by area with `upper`; `attribute.normalize`
and `geometry.shared` search with `lower`.
·computeshader · born here
❒asset # 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.
# 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);
}
```
·computeshader · born here
❒asset # sort
A stable radix sort of a column's keys into a permutation: place `s` of `perm`
holds the index of the element that sorts `s`-th, so a gather by `perm` puts
any column in key order.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `KEY` | `f32`, `i32` | the scalar a key holds |
Elements with equal keys keep their run order, in both directions
(`params.descending` 1 sorts from the greatest key down), and `-0` and `+0` are
one key. The sort works 4 bits of the key at a time from the least significant
up, and a pass whose digit is the same in every key is skipped, so a run of keys
inside a narrow range takes fewer passes. `work` is the sort's second
permutation; its contents after a dispatch are not an answer.
The dispatch size `n` is the number of keys. One workgroup of 128 works the whole
run; the other workgroups of a larger dispatch return.
Exact: the sort is a function of the keys and their order, so the same keys give
the same permutation on every dispatch.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` keys are live: they are sorted, and a slot at or past the live
count holds its own index in `perm`. A live count of 0 sorts nothing and `perm` is
the identity. It binds 4 storage buffers (3 in the plain variant).
Nodes that order or group elements run it, among them `attribute.order`, `elements.sort`, `core.edges`,
`core.adjacency`, `core.spatial`, `geometry.bvh`, `geometry.boolean`, `geometry.decimate` and `geometry.shared`.
# 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"
```
·computeshader · born here
❒asset # topology
Mesh edit operations over a geometry's linkage (`vertex.pt`, `primitive.vstart`,
`primitive.vcount`), selected by the `OP` specialization (`split_edge`, `collapse_edge`, `insert_face`, `delete_face`, `split_vertex`), each stage by `STAGE` (`count`, `write`): split an edge (insert a point),
collapse an edge (merge two points and drop the faces that degenerate), insert a
face, delete a face, split a vertex (give a group of corners a point of their own).
Each operation runs in two stages with an exclusive prefix sum between them. The `count`
stage writes `cnt`, how many output vertices each primitive contributes (`insert_face`
appends one entry per new face after the `np` primitives). The caller's exclusive prefix sum
of `cnt` is `off`. The `write` stage writes the output vertices' points (`o_pt`) and where
each came from (`o_src`). The output primitives are `off` as run starts and `cnt` as run
lengths; a primitive with an empty run is gone, and `core.select` removes it. `split_vertex`
runs per vertex instead: `cnt[v]` is 1 for the first vertex of each group, the groups'
new points are numbered from `npts` in order of their `off`, and `o_pt[v]` / `o_src[v]`
are written at the vertex's own slot. The shader's header states the records each
operation reads in `rec`.
The params are `np`, `nv` and `npts` (the input's primitives, vertices and points),
`nnew` (the faces `insert_face` appends), `wrap` (1 when runs wrap from their last vertex
to their first) and `minv` (the fewest vertices a primitive keeps after a collapse). The
caller binds `nv_out`, the output vertex count `o_pt` and `o_src` are sized by (the total
of the prefix sum). The dispatch is one thread per primitive, per primitive and new face
for `insert_face`, and per vertex for `split_vertex`.
The operation's records come from the edge table: for split edge, the point
for each split edge gathered to the vertex slots through `edges`' side slots
(both faces of an edge name the same point); for collapse, the point each
point becomes, from an independent set of edges. The point an inserted
vertex or a split vertex stands for is carried by the output maps: `o_src` names the vertex
whose attributes an output vertex takes (negative when it is new, with ~v the
vertex a split inserted after), and the compaction of the records names each
new point's source. Integers are 32-bit words, exact.
`geometry.decimate` runs `collapse_edge`.
·computeshader · born here
❒asset # walk
One thread per walker running `steps` dependent steps: each walker's start state goes in, its end
state and the state after every step come out, with the number of steps it ran. A state is 1 to 8
floats (`width`).
The step is a Field, handed to the kernel the way `map` takes its template: the fields package
fuses the Field into WGSL expressions and the kernel is specialized with them. A node holds no
WGSL.
| Specialization | Type | Meaning |
|---|---|---|
| `WALK_STEP` | `vec4<f32>` expression | lanes 0 to 3 of the next state; default `zero_walk_advance(s)`, the constant step |
| `WALK_STEP_HI` | `vec4<f32>` expression | lanes 4 to 7 of the next state; default `s_hi` |
| `WALK_DONE` | `bool` expression | whether the walker stops before step `k`; default `false` |
| `WALK_PRELUDE` | module-scope WGSL | the functions the expressions call, and `#include` lines for the `rand`, `noise` and `color` preludes |
The expressions read the state leaves `s` (lanes 0 to 3) and `s_hi` (lanes 4 to 7), the step
number `k` (u32) and the walker number `id` (u32), the numbers of `u` (`u_get(n)`) and the columns
of the `cols` table (`cols_f32(slot, i, lane)`, `cols_vec3(slot, i)`), which is how a step reads a
raster, a field column or a per-walker attribute. The constant step needs no Field: its vector is
the params `dx`, `dy`, `dz` and `dw`.
Bind `cols` (a table from `compute_abi.table`), `u`, `start` (`width` floats a walker). Outputs:
`finish` (`n * width`), `path` (`n * steps * width`, row `k` of walker `i` at
`(i * steps + k) * width`) and `steps_run`.
```luau
local variant = ref:program():variant({ specialize = {
WALK_STEP = "vec4<f32>(s.x + 1.0, s.y * 0.5, 0.0, 0.0)",
WALK_DONE = "s.x > 8.0",
} })
local run = variant:run({ n = walkers, inputs = { cols = emptyTable, u = numbers, start = startBuffer },
params = { steps = 8, width = 2 } })
```
`fieldc.walkSpec(step, opts)` writes the specializations from a step Field over the leaves `field.walk_state` and
`field.walk_index`, and `fieldc.bindSpec(spec)` the `cols` and `u` to bind; `device.kernel` runs the kernel with them
(the abi README states the form).
Exact: each walker writes its own path rows, so the result does not depend on thread order.
# 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.
# 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.
# 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.
# component (nodebox)
component.set gives every element of a class a component with the fields given.
# 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.
# debug (nodebox)
debug.dump summarizes any graph value into a record; debug.validate checks a Geometry's structure and reports every issue it finds.
# 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.
# 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.
# 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).
# 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.
# 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`.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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`
# 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`
# 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`
# 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.
# 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.
# 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" })
```
# 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`
# 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" } })
```
# 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.
# 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`
# 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`
# 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" } })
```
# 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`
# 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`
# 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" })
```
# 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`
# 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" })
```
# 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`
# 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`.
# 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`
# 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`
# 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`
# 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`
# 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" })
```
# 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`).
# 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`
# 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.
# 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")
```
# 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`
# 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")
```
# 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`
# 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`
# 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.
# 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`
# 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 })
```
# 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.
# 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.
# 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.
# 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.
# result
The handle `asset.list` returns.
A query result **is** the array of matched `AssetRef` handles. Entry `1` is the
first match, `#rows` is the count, `ipairs(rows)` walks it, and anything that
accepts a list of refs accepts it unchanged. The handle adds methods on top of
that array through a metatable, so reading the result stays one expression.
```lua
local hero = asset.list({ type = "mesh", fields = { tags = "hero" } }):first()
local prop = asset.list({ type = "mesh", path = "/zero/source/props" }):random()
asset.list("material")
:filter(function(m) return m.name:find("rust") ~= nil end)
:each(function(m) print(m.identity) end)
```
## Methods
| Method | Returns |
|---|---|
| `:first()` / `:last()` | One entry, or nil when the query matched nothing. |
| `:random()` | One entry chosen at random, or nil. |
| `:count()` | How many entries matched. |
| `:isEmpty()` | Whether nothing matched. |
| `:each(fn)` | The same result, after calling `fn(entry, index)` in order. |
| `:map(fn)` | A new result holding `fn(entry, index)` per entry. |
| `:filter(predicate)` | A new result holding the entries kept. |
| `:searchable()` | A new result without the deprecated assets, the ones a search or a picker offers. |
| `:sort(comparator?)` | A new, ordered result; ordered by identity when the comparator is omitted. |
| `:toArray()` | The entries as a plain table, without the handle. |
`:map`, `:filter`, and `:sort` return new results carrying the same methods, so
they chain. `:sort` leaves the result it was called on as it is.
## Ordering
`asset.list` already returns its matches ordered — by identity unless the query
asks for another field with `order` — so `:first()` names the same asset on
every call. `:sort` is for orders the query cannot express, such as one computed
from an entry's fields.
## What the handle does not change
The metatable carries `__index` alone. Length, `ipairs`, `pairs`, `next`,
`table.*`, and serialisation all read the array part, so a result behaves
exactly as a plain array everywhere those are used.
# asset_warmup
`asset.warmup` — a **read-only closure inspector**.
Returns the transitive set of assets that the CPU-residency system *would* load
when the given asset enters `/runtime/` — i.e. the asset plus everything
reachable through its declared content references. It does **not** itself change
residency or touch bytes:
```lua
local closure = asset.warmup("@builtin::meshes.cube")
-- → the asset + every texture/material/mesh it transitively references
```
Residency is owned by the engine's reference-counted CPU-residency system, which
acquires the closure on a `/runtime/` enter (usage 0→1) and releases it on the
last drop (→0), loading/unloading bytes at the per-node 0↔1 boundaries so a
texture shared by two materials stays resident until BOTH are gone. This helper
just lets scripts and agents **inspect** that closure (debugging, "what would loading
X pull in?") without any side effect — it avoids `asset.resolve` (which fires the
BlobStore prefetch) and uses the side-effect-free `asset.guid` / `asset.deps` /
`asset.identity`.
The closure is the generic `.refs` graph, so this is fully type-agnostic —
material/mesh/user-types all resolve the same way with zero per-type knowledge.
By default it follows `asset_ref` / `component` (content) edges and skips
`asset_type` (structural) / `require` (code); `opts.vias` overrides. Deduped by
guid via an explicit work-stack so diamonds appear once and cycles terminate.
Installed onto the FFI `asset` namespace by the prelude.
# transform
Math helpers for positions, rotations, and directions on transforms.
Exposed as the global `Transform` table via `--!global Transform` — no
explicit require needed in user code. Functions that take an entity
accept either an entity ID string or an entity proxy table from
`entity("id")`.
## Exports
Look-at and entity-aware helpers:
- `Transform.lookAtQuat(fx, fy, fz, tx, ty, tz) -> (qx?, qy?, qz?, qw?)` — quaternion from origin toward target. Nil when degenerate.
- `Transform.lookAt(entity, txOrTarget, ty?, tz?) -> (boolean, string?)` — make an
entity face a world position or another entity. Both slots read world space:
the subject and an entity target are read as `entity(id).position` and the aim
is written as `entity(id).rotation`, so a parent under either one still leaves
the aim on the point named. Returns whether the rotation was written, and the
reason when it was not.
- `Transform.distance(x1, y1, z1, x2, y2, z2) -> number` — Euclidean distance between two points.
- `Transform.distanceBetween(entityA, entityB) -> number?` — distance between two entities' world positions. Nil when either is unresolvable.
- `Transform.direction(fromX, fromY, fromZ, toX, toY, toZ) -> (dx, dy, dz)` — unit direction vector.
- `Transform.directionBetween(entityA, entityB) -> (dx, dy, dz)` — unit world-space direction between two entities' world positions.
Rotation shapes:
A quaternion **constructor** here returns the four components as four separate
values, so a caller either names them or braces the call to make one table:
```lua
local qx, qy, qz, qw = Transform.quatFromAxisAngle(0, 1, 0, math.rad(90))
entity("cam").localRotation = { Transform.quatFromAxisAngle(0, 1, 0, math.rad(90)) }
```
A rotation-taking **surface** reads that table through
`Transform.toQuaternion`, which also takes euler DEGREES — so
`{ qx, qy, qz, qw }`, `{ x =, y =, z =, w = }`, `{ pitch, yaw, roll }` and
`{ pitch =, yaw =, roll = }` all mean the same thing wherever a rotation is
assigned: `entity(id).rotation` / `.localRotation`, `entityOps.spawn`,
`entityOps.transform`, and the capture viewpoints.
- `Transform.toQuaternion(rotation, label?) -> { qx, qy, qz, qw }` — the shared reading of a rotation a caller wrote. Raises when the value matches no form, naming what arrived; a value that is one of the shapes a quaternion helper returns is named as such along with the packing it goes in as.
- `Transform.tryQuaternion(rotation, label?) -> ({ qx, qy, qz, qw } | nil, message?)` — the same reading without raising, for a surface that wants to raise the message at its own caller's line.
- `Transform.readVec3(value, label?) -> { x, y, z }` — the same for a vector.
- `Transform.snapVec3(v, step) -> { x, y, z }` — quantize a vector to a step grid.
Quaternion construction / conversion:
- `Transform.quatFromYaw(yaw)`, `Transform.quatFromYawPitch(yaw, pitch)`, `Transform.quatFromAxisAngle(ax, ay, az, angle)` — quaternion constructors.
- `Transform.quatIdentity()` — identity quaternion.
- `Transform.euler(qx, qy, qz, qw) -> (yaw, pitch, roll)` and the named alias `Transform.quatToEuler`.
- `Transform.eulerToQuat(yaw, pitch?, roll?)` — euler-to-quaternion in YXZ order.
Lerps and interpolation:
- `Transform.lerp(ax, ay, az, bx, by, bz, t) -> (x, y, z)` — vec3 lerp.
- `Transform.lerp1(a, b, t) -> number` — scalar lerp.
- `Transform.normalizeAngle(a) -> number` — wrap angle into `[-pi, pi]`.
- `Transform.lerpAngle(a, b, t) -> number` — shortest-arc angle lerp.
- `Transform.slerp(ax, ay, az, aw, bx, by, bz, bw, t) -> (qx, qy, qz, qw)` — quaternion slerp with shortest-path and near-parallel fallback.
Quaternion operations:
- `Transform.quatMul(...) -> (qx, qy, qz, qw)` — `qa * qb` composition.
- `Transform.quatInverse(qx, qy, qz, qw) -> (qx, qy, qz, qw)` — inverse (= conjugate for unit quats).
- `Transform.quatRotateVec(qx, qy, qz, qw, vx, vy, vz) -> (x, y, z)` — rotate a vec3 by a quaternion.
Pose helpers:
- `Transform.orbit(centerX, centerY, centerZ, radius, height, angle) -> (x, y, z, qx, qy, qz, qw)` — orbital pose facing the center.
- `Transform.worldToLocal(...)` / `Transform.localToWorld(...)` — pose-space conversions.
Nested `Transform.vec.*` namespace (component-wise vec3):
- `Transform.vec.add`, `sub`, `scale`, `dot`, `cross`, `length`, `normalize`.
Types:
- `Vec3 = { x: number, y: number, z: number }`
- `EntityRef = string | { entityId: string }`
## Usage
```luau
-- Look-at by coordinates or by target entity:
Transform.lookAt("cam", 0, 1, 0)
-- an entity target resolves to that entity's world position
local aimed, why = Transform.lookAt("cam", "box")
-- Orbit pose around a point:
local x, y, z, qx, qy, qz, qw = Transform.orbit(0, 1, 0, 5, 2, t)
entity.find("cam").localPosition = { x, y, z }
entity.find("cam").localRotation = { qx, qy, qz, qw }
-- Quaternion math:
local qx, qy, qz, qw = Transform.quatFromYawPitch(math.pi / 4, 0)
local sx, sy, sz, sw = Transform.slerp(0, 0, 0, 1, qx, qy, qz, qw, 0.5)
-- Component-wise vec3 helpers:
local nx, ny, nz = Transform.vec.normalize(1, 1, 0)
```
## Notes
- The `--!global Transform` directive promotes the module's typed
functions onto the runtime universe's globals bucket, so `Transform.*`
is available without any per-source `require`.
- Entity-aware functions (`lookAt`, `distanceBetween`,
`directionBetween`) report a missing entity or a missing transform in
their return value rather than raising: `lookAt` answers
`false, "unresolved"` / `"no-transform"` / `"incomplete-target"` /
`"degenerate"`, `distanceBetween` answers `nil`, and
`directionBetween` answers zeros.
- Quaternion APIs operate on raw `(qx, qy, qz, qw)` tuples for parity
with the entity proxy's `localRotation.get`/`set`. Use
`Transform.quatIdentity()` rather than hand-rolling `(0, 0, 0, 1)`.
- `Transform.slerp` flips the second quaternion if `dot < 0` to take
the shortest path, and falls back to lerp+normalize when the inputs
are within `dot > 0.9995` to avoid `1/0` near-parallel issues.
# luau_introspect (module)
Parses Luau/asset source TEXT into structured declarations. Pure
string/pattern parsing (`string.find` / `string.match` / `string.gmatch`)
over the literal source — no compiling, no VM spawn, no runtime state, no
engine FFI. Given source text, it extracts what is written in the file.
This is the shared parser every per-assetType `M.ref.inspect` hook uses to
turn a component/module/tool's own source into the structured record
`asset.inspect` returns.
## Exports
- `docstrings(src) -> DocMap` — scans `--!desc` / `--!arg` / `--!return` /
`--!example` comment runs and binds each run to the name of the
declaration on the next non-comment line (the identifier after
`function`, `public:`, `local function`, or `M.`).
- `publicFields(src) -> { FieldEntry }` — parses `public = { name =
Field.<kind>(default, mode), ... }` table-literal entries and
module-scope `public.<name> = Field.<kind>(...)` assignments.
- `events(src) -> { EventEntry }` — parses `events = { name =
Event(payloadSchema?, syncMode?), ... }` table-literal entries.
- `methods(src) -> { MethodEntry }` — parses `function public:<name>(...)`
/ `typed function public:<name>(...)` declarations (params + optional
return type).
- `lifecycleHooks(src, catalog) -> { string }` — top-level `function
<name>(` declarations whose name is in the caller-supplied `catalog`
array.
- `moduleExports(src) -> { ExportEntry }` — parses `M.<name> = function`
assignments, `function M.<name>(...)` declarations, and a trailing
`return { foo = foo, ... }` export table.
- `forSource(src, computeFn) -> any` — memoises `computeFn(src)` keyed on
`src` itself in a module-local table. The same source text returns the
cached result without re-running `computeFn`; different source text
recomputes. Keyed on the source content (not an asset checksum) because
composite/container assets (component folders, scene folders, etc.) all
hash to the empty-string checksum — a checksum-keyed cache collapses
every such asset's detail onto whichever one was inspected first.
## Usage
```luau
local Introspect = require("modules.luau_introspect")
local src = self:getInitScript()
local detail = Introspect.forSource(src, function(s)
return {
fields = Introspect.publicFields(s),
events = Introspect.events(s),
methods = Introspect.methods(s),
hooks = Introspect.lifecycleHooks(s, lifecycleCatalog),
}
end)
```
## Notes
- Every function is a pure string→table transform: same source text in,
same structured table out, every time. No reads of live component
state, no entity/world queries.
- Structural scanning runs over a comment- and string-aware **mask** of
the source (a same-length copy where comment bodies and string-literal
contents are blanked to spaces, delimiters and newlines preserved).
Pattern matches and brace/paren balancing run on the mask — so a brace,
`Field.`, `Event(`, or a whole entry that appears inside a comment or a
string literal never registers — while captured values are sliced from
the original source at the same (aligned) indices. This makes the
parser robust to apostrophes in comments, commented-out entries, string
defaults containing `}` / `Field.` / `Event(`, and `[[ ]]` long
strings.
- `default` / `category` are raw trimmed source-text slices (with any
trailing comment stripped), not evaluated values.
- For a **ref constructor** (`Field.assetRef` / `dataRef` / `resource`
/ `componentRef`) the FIRST positional argument is the category /
contract / componentType selector, captured under `category`; the
SECOND argument is captured under `default`.
- For every **other** Field kind the first argument is the `default`
and `category` is nil.
- A trailing `Sync` / `NoSync` identifier is captured as `sync`,
tolerating a trailing comma or a trailing comment after the last
argument.
- Field/Event entries whose key is a computed or indirect expression
(`[expr] = Field.number(...)`) are omitted — only literal identifier
keys are recognised.
- `methods` captures a `...` variadic parameter (as `name = "..."`), with
its `: <type>` annotation when present.
- A `--!desc` written above a field/event declaration (`<name> =
Field.<kind>(...)` / `<name> = Event(...)`) or a `public.<name> =`
assignment binds to that name in `docstrings`, and is folded into the
corresponding `publicFields` / `events` entry's `desc`.
- `lifecycleHooks` never hardcodes the lifecycle-callback catalog; the
caller passes the list of names to match against.
- `forSource`'s memo is bounded (oldest-key eviction) so a long session
touching many distinct asset versions can't grow it without limit.
# assetType.shared.ref
Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries: the default methods every ref answers and the per-type behaviour its asset type defines.
## Public API
```lua
local assetRef = require("@builtin::assetTypes.assetType.shared.ref")
-- Called by the Rust factory (push_asset_ref_handle) via
-- _G.__build_asset_ref_proxy after the envelope fields are set.
assetRef.build(envelope) -- attaches AssetRefMT, returns the table
```
The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below).
## Method dispatch order
`ref.foo` is resolved in this order:
1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (an engine contract).
2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods.
3. **Nil** — unknown key, same shape as the original C metatable.
## Adding methods for a new asset type
Drop a `behavior.luau` into the type folder:
```
assetTypes/<typename>.assetType/
├── type.yaml -- structural spec (existing)
├── behavior.luau -- ref + global behaviour (new)
└── template/ -- placeholder body (existing)
```
`behavior.luau` returns:
```lua
return {
ref = {
--!desc Per-instance method on every `<typename>` AssetRef.
myMethod = function(self, ...) ... end,
},
global = {
-- Reserved for the asset.<typename>.* surface — not consumed
-- yet; reserved for that surface.
},
}
```
Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined.
## Discovery and hot-reload
Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half.
Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call.
The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods.
## Why Luau, not Rust
The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means:
- Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code.
- Adding a new asset type drops in a new folder; no Rust rebuild.
- Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives.
## Consumers
- The engine's asset bindings — the factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push.
- Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.