ZeroJS is a JavaScript interpreter for the Zero engine, written in Luau. It parses and executes ES2017-practical JavaScript entirely inside the Luau VM — no native code, no WebAssembly, no external dependency — and marshals values back to Luau transparently.
## Importing
```luau
local zerojs = require("~zerojs.api")
```
`~zerojs` is this package's alias, registered from the `name` in its `package.yaml` wherever the package sits. The same spelling therefore works from the world that authors the package and from a world that installed it, at any depth. Every module is reachable the same way — `~zerojs.parser`, `~zerojs.stdlib.promise` — and the package's own modules reference each other with those ids.
## API surface
### Module-level
| Symbol | Type | Description |
|--------|------|-------------|
| `zerojs.eval(src)` | `(string) -> any` | Parse and execute `src` in a fresh one-shot VM. Returns the marshaled JS completion value. Raises a Luau error on a JS exception. |
| `zerojs.new(opts?)` | `(table?) -> VM` | Create a persistent VM. `opts.env` seeds additional JS globals from a Luau table. |
| `zerojs.null` | sentinel | The JS `null` value (distinct from Luau `nil`). |
| `zerojs.undefined` | sentinel | The JS `undefined` value, which marshals to Luau `nil` when returned. |
| `zerojs.version` | `string` | Version string of this package. |
| `zerojs.lastError(vm)` | `(VM) -> table?` | Returns the structured payload `{ name, message, stack }` from the most recent JS exception on `vm`. `nil` if no exception has occurred on that VM. |
### VM instance
| Method | Description |
|--------|-------------|
| `vm:run(src, opts?)` | Execute `src` in this VM's persistent realm. `opts.sourceName` names the source for error messages and stack frames. Returns the marshaled completion value. Raises directing to `runAsync` when the script leaves a timer armed or a coroutine suspended across a frame. |
| `vm:runAsync(src, opts?)` | Execute `src`, driving its event loop across engine frames until it settles. Returns a `RunHandle` immediately. `opts.timeoutMs` rejects the run if it outlasts that many milliseconds. Only one `runAsync` may be in flight per VM at a time; a second call while the first is unsettled raises. |
| `vm:get(name)` | Read a global from the VM's realm. |
| `vm:set(name, value)` | Write a marshaled Luau value as a JS global in the VM's realm. |
### `RunHandle` (returned by `vm:runAsync`)
| Field | Description |
|-------|-------------|
| `done` | `false` until the run reaches a terminal state, then `true`. |
| `ok` | Once `done`, `true` for a resolved run and `false` for a rejection or timeout. |
| `value` | The marshaled completion value on a resolved run. |
| `error` | The rendered message text on a rejected or timed-out run. |
| `lastError` | The structured `{ name, message, stack }` payload for a failed run. |
| `thread` | The engine `task.spawn` driver pumping the loop each frame — present only while the run is still pumping, and `nil` once the run settles on its arming frame (a synchronous or microtask-only completion needs no per-frame driver). |
| `handle:await(maxFrames?)` | From a yieldable Luau context, poll `done` frame-by-frame until the handle settles, then return it. |
A `runAsync` stays pending while the loop has work: an armed `setInterval` keeps it pending exactly as an un-`unref`'d handle keeps Node alive — clear the interval or bound the run with `timeoutMs`.
## Marshaling
Luau values passed to `opts.env` or `vm:set` are converted to JS values. JS values returned from `run`/`eval` are converted back to Luau: numbers, strings, and booleans are transparent; arrays become 1-based Luau tables; objects become string-keyed Luau tables; JS functions become callable Luau closures; `undefined` becomes `nil`; `null` becomes `zerojs.null`.
## Step-budget sandbox
Each VM runs with a default execution budget of 1,000,000 interpreter steps. A script that exceeds the budget raises a JS `RangeError: step budget exceeded`, which surfaces as a Luau error. The budget resets on each `run`/`eval` call.
## Language scope
- Variable declarations: `var` (function-scoped hoisting), `let` and `const` with full TDZ enforcement
- Functions: declarations, expressions, arrow functions, closures, rest parameters, default parameters
- Classes: declarations and expressions, inheritance via `extends`, `super()` in constructors and methods, getter and setter accessors, instance fields, static fields and methods, computed method keys, named class expressions, TDZ before declaration
- Destructuring: object and array patterns in declarations, assignment, and function parameters; nested patterns; rename, default, rest; computed keys in object patterns; elision in array patterns
- Spread: array literals, call arguments, `new` arguments, object literals
- Template literals (untagged)
- Full coercion and equality semantics: `==`/`!=` abstract equality, `===`/`!==` strict equality, `typeof`, `instanceof`
- `try`/`catch`/`finally`, `throw`
- All loop forms: `for`, `while`, `do-while`, `for-in`, `for-of`; `switch` with fallthrough
- `async`/`await` — real event-loop semantics: an async function returns a promise, runs synchronously up to the first `await`, and resumes from a microtask when its awaited operand settles
- Property enumerability: `for-in` yields only own enumerable keys; object rest excludes prototype methods
### Asynchrony and the event loop
- `Promise` with the full ES surface: `then`/`catch`/`finally`, `resolve`/`reject`, and the combinators `all`, `allSettled`, `race`, and `any` (with `AggregateError` when every input to `any` rejects)
- `queueMicrotask` for scheduling a microtask directly
- Timers: `setTimeout`/`clearTimeout` and `setInterval`/`clearInterval`, with extra arguments forwarded to the callback
- `vm:runAsync(src, opts?)` drives a script's timers, microtasks, and promise settlements across engine frames and returns a `RunHandle` (see the VM table above)
- A long synchronous loop under `runAsync` yields at each step-budget boundary and resumes on a later frame instead of raising `RangeError`; the same script under `vm:run` still raises
### Standard library
- `Object`: callable coercion plus `keys`, `values`, `entries`, `assign`, `freeze`, `isFrozen`, `create`, `getPrototypeOf`, `defineProperty`, `fromEntries`, `hasOwn`, and the `Object.prototype` methods (`hasOwnProperty`, `toString`, `isPrototypeOf`)
- `Function.prototype`: `call`, `apply`, `bind`
- Global conversions and predicates: `parseInt`, `parseFloat`, `isNaN`, `isFinite`, `String`, `Number`, `Boolean`
- `Array` and `Array.prototype`: construction, `isArray`, `from`, `of`, and the iteration/mutation/query methods (`map`, `filter`, `reduce`, `forEach`, `find`, `some`, `every`, `slice`, `splice`, `concat`, `join`, `indexOf`, `includes`, `sort`, `reverse`, `push`, `pop`, `shift`, `unshift`, `flat`, `fill`, `keys`, `values`, `entries`)
- `String.prototype`: `slice`, `substring`, `substr`, `split`, `indexOf`, `includes`, `startsWith`, `endsWith`, `repeat`, `padStart`, `padEnd`, `trim`, `trimStart`, `trimEnd`, `toUpperCase`, `toLowerCase`, `charAt`, `charCodeAt`, `codePointAt`, `at`, `concat`, `replace`, `replaceAll`, `match`, `matchAll`, `search`
- `Number`: `isInteger`, `isSafeInteger`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`, `MAX_SAFE_INTEGER`, `MIN_SAFE_INTEGER`, `MAX_VALUE`, `MIN_VALUE`, `EPSILON`, `POSITIVE_INFINITY`, `NEGATIVE_INFINITY`, `NaN`, and `Number.prototype` (`toFixed`, `toString`, `toPrecision`)
- `Math`: the constants and functions (`abs`, `floor`, `ceil`, `round`, `trunc`, `sign`, `min`, `max`, `pow`, `sqrt`, `cbrt`, `hypot`, `exp`, `log`, `log2`, `log10`, the trig family, `random`)
- `Date`: construction as `new Date()` (now) and `new Date(ms)` (epoch milliseconds), `now`, `getTime`, `getFullYear`, `getMonth`, `getDate`, `getHours`, `getMinutes`, `getSeconds`, `getMilliseconds`, `getDay`, `toISOString`, `toJSON`
- `JSON`: `parse` and `stringify` (indent argument and array replacer whitelist)
- `Map` and `Set`: construction from iterables, `get`/`set`/`has`/`delete`/`clear`, `add`, `size`, `forEach`, `keys`, `values`, `entries`, insertion-order iteration
- `RegExp`: literals and the constructor, `test`, `exec`, `lastIndex`, `source`, `flags`, `global`, `ignoreCase`, `multiline`, `dotAll`, and the `String` regex methods above
- Errors: `Error`, `TypeError`, `RangeError`, `ReferenceError`, `SyntaxError` constructors and inheritance; `console.log`/`warn`/`error`; `globalThis`, `NaN`, `Infinity`
### Out of scope by design
- Generators and iterators (`function*`, `yield`)
- `Proxy` and `Reflect`
- Labeled statements and `with`
- Tagged template literals
- Optional chaining (`?.`) and nullish coalescing (`??`)
The full divergence list — where ZeroJS behavior differs from a browser engine — lives in the guide's divergence section.
## Test suites
Seven suites ship with the package, run via `tools.tests.run`:
```luau
tools.tests.run({ suite = "zerojs_lexer" }) -- tokenization
tools.tests.run({ suite = "zerojs_parser" }) -- AST construction and error recovery
tools.tests.run({ suite = "zerojs_semantics" }) -- runtime semantics end-to-end
tools.tests.run({ suite = "zerojs_stdlib" }) -- the standard-library surface
tools.tests.run({ suite = "zerojs_regex" }) -- the regex engine and RegExp methods
tools.tests.run({ suite = "zerojs_async" }) -- the event loop, promises, and timers
tools.tests.run({ suite = "zerojs_smoke" }) -- unmodified real-world JS programs
```
# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries.
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()`.
Globals leak across reloads. 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**.
# Package (asset type)
A package is an asset — a `<Name>.package/` folder that bundles
components, modules, scenes, presets, tools, and any other typed
sub-assets under one identity, installed into a world as one unit.
Packages are how authoring sets get distributed across worlds.
A **library** is the addressable root scope content resolves under
(`@builtin`, `@<name>`) — a whole world mounted into this one under a
namespace, via `zeromind.installLib` / `world.installLibrary`. A package is
an asset that lives inside such a root, and one library holds as many
packages as its author put there. A package is installed by guid the
way every asset is (`zeromind.install`, `zeromind.installAsset`).
## When to use one
- You're authoring a coherent feature suite (character controller
stack, voxel engine, UI kit, animation library) and want to ship
it as one install target.
- You want a stable identity worlds can install and resolve sub-assets
against (`@<lib>::pkg.sub_module`).
- You want versioning + a per-package metadata layer that travels with
the contents.
If you're authoring inside a single world and don't need a separate
install lifecycle, you don't need a package — drop your `.component`
/ `.module` / etc. directly in `/zero/source/`. Packages are for
cross-world distribution.
## Where it lives
- Source: `/zero/source/.../<Name>.package/` (or, for legacy
packages, a folder containing `package.yaml` at its root).
- Identity: `<Name>` (the `.package` suffix collapses in identity —
mirrors `.module`). A file at `<Name>.package/<sub>/init.luau`
resolves under the same identity it would at `<Name>/<sub>/init.luau`.
- Folder shape (container-style — open child set):
- `package.yaml` — metadata (name, version, description).
**Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- Sub-asset folders: any combination of `.component/`,
`.module/`, `.scene/`, `.preset/`, `.tool/`, `.toolbox/`,
`.material/`, `.shader/`, etc.
The validator permits unlisted children (`allow_unlisted: true`) by
design — packages are open containers.
## How to create one
```luau
asset.create("package", "<Name>")
-- Creates: /zero/source/<Name>.package/
-- package.yaml (metadata scaffold)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("package", "<Name>", { folder = "systems" })
```
Then scaffold sub-assets inside it:
```luau
local pkg = asset.resolve("<Name>.package")
asset.create("component", "Spinner", { into = pkg })
asset.create("module", "util", { into = pkg })
```
## How it operates
1. **Registration.** Writing `package.yaml` indexes the package with
the package registry.
2. **Install.** A package is installed by guid, the way every asset
is: `zeromind.install` from the shared library, or
`tools.use("zeromind", "installAsset", <guid>)` inside the engine. The
install writes the package's files (and the deps its `.refs`
record) into this world's source, so its sub-assets resolve here.
`tools.use("zeromind", "preview", <guid>)` reports what an install would
write before it writes anything.
3. **Sub-asset resolution.** Because `.package` collapses in
identity, sub-asset paths work whether the package folder is
suffixed (`<Name>.package/<sub>`) or not (`<Name>/<sub>`).
4. **Updates.** `tools.use("zeromind", "updates")` lists installed content
with upstream changes available; re-running the install pulls them.
5. **Metadata.** `package.yaml::name` overrides the folder stem if
present (rare); `version` + `description` are surfaced in the
package index.
6. **Hot reload.** Edits to sub-assets hot-reload as normal; edits to
`package.yaml` reload package metadata.
## Discovery
- `asset.list("package")` — every registered package.
- `asset.inspect("<name>")` — sub-asset catalog, source, this type
README.
- `ls /zero/source/<Name>.package` lists the files the folder holds.
- `library.list()` — the library assets registered in this world,
including the ones packages under an installed library contribute.
## Authoring conventions
- Name packages by their feature (`voxels`, `cameraRigs`,
`dialogSystem`), not by their owner — the host library is the
`@<lib>::` scope prefix.
- Cluster cohesive sub-assets together. A "character controller"
package should ship the controller component, its preset configs,
its supporting modules, and a demo scene — not just the component.
- Document the package's surface in `README.md` — what install
installs, what each sub-asset does, how they relate. Agents reading
`cat /zero/source/<Name>.package/README.md` get the full picture in one shot.
- Version conservatively — breaking a package means breaking every
world that installed it. Use semantic version bumps.
## Common pitfalls
- **Missing `package.yaml`.** Without it the folder isn't recognized
as a package even if it has a `.package/` suffix.
- **Dependency installs.** A package that depends on another package
must declare it (in `package.yaml::dependencies` once supported)
and the parent world must install dependencies in order.
- **Identity collapse.** Sub-asset paths skip the `.package` suffix.
Don't include `.package` in `require` strings.
## Referencing inside a package: the `~` rule
`~` means **this package**, resolved structurally from the referring file's own
location. It is the only package-specific syntax. It is rename-safe (no package
name is ever written) and library-agnostic (it never names the host library, so
it survives `@builtin` being renamed or the package being mounted elsewhere).
`~.tail` maps to `<pkg>.package/tail` from anywhere inside the package.
| Referencing from | Use | Example |
|---|---|---|
| An asset/module **inside this package** | `~.tail` | `require("~.modules.myThing")`, `shader: "~.shaders.myThingBlend"` |
| A **different package** under the same root | root-relative identity | `require("@root::systems.otherPkg.modules.x")` |
| A **different library's** public API (a deliberate external dependency) | `@otherlib::…` | `require("@physics::modules.rigidbody")` |
**Never write `@builtin::` (or any host-library name) to reference your own
package** — that couples the package to the library it currently lives in and
breaks if the library is renamed or the files move. Use `~.`. It works from
Luau `require()` and from asset-reference strings in data files (a material's
`mat.yaml` `shader:` field, a component's default asset ref); the engine
resolves it against the referring file's own package. `asset.resolve` takes a
`~.` name the same way, against the package of the file that calls it:
`asset.resolve("~.materials.myThingStandard", "material")`.
`~.` is the package-relative self-reference; `@root::` is the root-relative one
(the library root, or the world source tree for non-library content). The
`core/requiring-modules` guide covers the root model in full.
A package that ships substantial functionality should include a `.guide` asset
(a `<name>.guide/guide.md` folder anywhere under the package); the `guides` tool
discovers it live, so collaborators find the system the way they find built-in
guides. A package's test suite reaches the shared `Test` framework through its
enclosing asset: `local Test = asset.containing(__FILE__).modules.shared`
(`asset.containing` returns the deepest enclosing typed asset, the `.testSuite`,
not the outer `.package`).
## Related types
- Any of `.component`, `.module`, `.scene`, `.preset`, `.tool`,
`.toolbox`, `.material`, `.shader`, `.style`, `.service`,
`.importer` — packages bundle these.
## In the Inspector
Package: the name, version and description package.yaml declares, how many things the package holds and what they are, and **Open** for package.yaml. A package.yaml that does not decode is listed under Problems with the decoder's error.
# agentSkill
A skill packages what an agent needs to do one job well: the instructions,
the assets and toolboxes the job runs through, and — for jobs with distinct
branches — subskills that go deeper.
Skills advertise themselves. Every registered skill's name and one-line
description rides the agent's tool responses, so an agent discovers what this
world knows how to do without being told to look. Invoking one returns the
instructions plus the exact identities and tool names the job needs.
## Shape
```
<name>.agentSkill/
skill.yaml # the manifest: description, when, checks, dependencies, order
instructions.md # the prose an agent receives on invoke
README.md # what this skill is, for a human reading the tree
.metadata # tags
<sub>.agentSkill/ # optional subskills, reachable as <name>/<sub>
```
## The manifest
```yaml
$schema: zero/agent-skill/v1
description: Making a character a person can actually play.
when: >
Reach for this when the player should look like something else, or when
you are about to build a camera and a body and wire them together by hand.
checks:
- check: Holding a movement key in play moves the body across the ground.
observe: Read its position before and after holding the key; the numbers differ.
- check: The body animates while it moves.
observe: A time-sampled collage from a camera outside the player, while the key is held.
dependencies:
- "@builtin::tools.scene"
- "@builtin::tools.scene.player"
- "@builtin::components.PlayerPrototype"
- "@builtin::docs.core.multiplayer"
order: [spawn-points, camera-rig]
```
`description` is the line the roster carries, and the whole basis on which a
skill is chosen. Name the job the skill makes a reader competent at, in the
outcome they are after — "getting a scene's player and view right", "making
content the engine will load". A reader scanning the roster is matching it
against the job in front of them, so the closer it reads to their own
sentence about that job, the sooner they open it.
`when` is the longer trigger — the situations that should send a reader here,
in the words they would use for their own task.
`checks` is what the reader is answerable for at the end, and it leads the
rendered skill, ahead of the procedure. Each entry pairs a **condition that
must hold** with **where it is seen**, and both halves are required — a
condition alone is satisfied by any glance, and the wrong vantage is how a
job passes while every one of its faults sits outside the frame. Write them
as observations someone else could repeat and disagree with: a number that
changed, a thing visible in a named shot, a count that came back as one.
A skill publishes only once it carries at least one.
`stages` models a skill whose passes run in order, when the order is
load-bearing. Each stage is `{ name, detail?, checks? }`, and a check that
sits in a stage is answered after that pass has run — which is the difference
between a criterion that means something and one that misleads. A skill with
no meaningful order leaves `stages` out and lists its checks flat; a skill
that has one may do both, and the flat checks then read as the final gate.
`verdicts` names the fixed set of outcomes a reader reports — at the end of
each stage when the skill has stages, and once at the end when it does not.
Each is `{ verdict, means }`: the word, and what reporting it asserts. Both
halves are required for the reason both halves of a check are. A verdict is a
check one level up, deciding a whole pass rather than one condition, and a
bare `refine` is a label each reader fills in privately — so two runs report
the same word about different states and nothing downstream can tell them
apart. Saying what it means settles the boundary in the skill instead of in
whoever happens to be reading it.
A check marked `perRun: true` is one whose content is written for the job at
hand: the manifest can say *keep a list of every feature this object must
have and answer against it*, but not what is on that list, because that is
per run. It renders with that instruction attached.
```yaml
verdicts:
- verdict: continue
means: Every check in the stage held, and the next stage can build on it.
- verdict: refine
means: A check failed on something this stage can still fix. Run it again.
- verdict: stop
means: A check failed on something an earlier stage decided. Go back to it.
stages:
- name: blockout
detail: Mass and proportion only.
checks:
- check: Every part on the identity list has a stand-in at roughly the right size.
observe: A capture beside the reference, at the same angle.
perRun: true
- name: material
checks:
- check: Metal reads as metal and cloth as cloth.
observe: The metallic and roughness passes, after the lighting stage has run.
```
`dependencies` is one flat list of asset **identities**: a toolbox, a single
tool, a guide, a component, a module, another skill. Each entry is resolved
when the skill is opened and reported with what it turned out to be, so a
skill never declares "this one is a toolbox" — the asset says so, and the
reader groups by that.
Identities are what make a skill portable. They pin like any other reference,
so installing a skill into another world brings the toolboxes and guides it
runs through along with it. A bare name (`scene`) or a guide path
(`core/multiplayer`) resolves to nothing and is refused before publish.
A toolbox entry lists the tools it carries, and a tool entry carries its own
signature, so the instructions never restate a call contract that can drift.
An identity this world lacks is reported as missing rather than dropped.
Write instructions that name the toolboxes and tools a job runs through, and
leave the call form to the reader — an agent may be holding the MCP tool
surface, the shell, or Luau, and the signatures are listed for it either way.
## Subskills
A `<sub>.agentSkill/` folder nested inside a skill is a subskill. It has the
same shape as its parent and is invoked as `parent/sub`.
Subskills are reachable only through their parent: they are absent from the
roster and from `skills.list`, and appear in the parent's invoke result. A
skill can therefore carry a dozen narrow procedures while costing the roster
one line.
`order` in the manifest names the subskills that lead. Any subskill it omits
still appears, sorted by name, after the ordered ones — so adding a subskill
folder is the only step needed to publish it.
## Publishing one
Make a skill and it is live: it joins the roster agents read and it opens by
name from the moment it exists. Edit its description and that is the line
agents see next.
A skill lives anywhere under `/zero/source/`. `asset.create` hands you a
valid one to fill in:
```luau
asset.create("agentSkill", "waveSpawning", { folder = "skills" })
```
A skill's scope — `builtin`, `library`, or `world` — comes from where it
lives rather than from anything it declares, so a world's own skill always
reads as the world's.
## Opening one
```
agent_skill {} -- the roster
agent_skill { name = "scenes" } -- one skill's instructions + deps
agent_skill { name = "scenes/player-setup" } -- a subskill
```
The same three through the toolbox — `skills.list`, `skills.invoke` — and
from Luau via `tools.use("skills", "invoke", "scenes")`. `asset.inspect` on a
skill ref returns the structured record all of them render.
Skills authored in a world are the world's own, and are labelled as world
content wherever they surface beside built-in ones.
## In the Inspector
Skill: what the skill is for and when it applies, how many checks and verdicts it declares, its stages, a link to each asset it depends on (and a problem for each that does not resolve), its subskills, and **Open** for instructions.md.
# inputBinding assetType
One control in a scheme — `jump`, `move`, `boost` — expressed as an asset. A
`<name>.inputBinding/` folder whose `init.luau` returns the binding record,
living inside a `.inputMap/` parent the same way a `.tool` lives inside a
`.toolbox`.
Containment is what records the reference, so a scene that carries its map
carries every control the map declares. A scene pulled into another world
cannot arrive somewhere `boost` binds to nothing.
```luau
-- racer.inputMap/boost.inputBinding/init.luau
local B = require("@builtin::modules.zinput.bindings")
return {
label = "Boost",
kind = "button",
kbm = { B.key("ShiftLeft") },
gamepad = { B.padButton("left_shoulder") },
touch = { B.touchButton({ zone = "right-lower" }) },
}
```
## Every device class, always
`kbm`, `gamepad` and `touch` are all required. A control bound on one device
and not another is how a world ships playable on a desktop and dead on a
phone, so a record missing a class is refused at activation, naming the
binding and the class it lacks.
Setting a class to `false` suppresses it deliberately — a text-entry control
with no touch counterpart says so, and says it in the record where a reader
sees it.
The cost of that rule is paid at authoring time rather than by the author:
the `inputAuthor` toolbox stamps canonical defaults for a control whose name
the catalog knows, so a complete three-class binding is one call.
## Kinds
| `kind` | Shape per class | What it is |
|---|---|---|
| `button` | an **array** of bindings — any one satisfies it | A press: jump, fire, interact |
| `axis1` | **one** binding | A scalar: throttle, zoom, lean |
| `axis2` | **one** binding | A vector: movement, look, aim |
A button takes an array because a control usually has more than one way to
be pressed on the same device (`ShiftLeft` and `ShiftRight`). An axis takes
one because an axis evaluates exactly one binding per class.
```luau
-- move.inputBinding/init.luau
return {
label = "Move",
kind = "axis2",
kbm = B.wasd(),
gamepad = B.padStick("left"),
touch = B.touchStick({ zone = "left" }),
}
```
## Shaping an axis
An `axis1` / `axis2` control conditions its reading before a consumer sees
it. Four optional fields, applied every tick in this order:
| Field | What it does |
|---|---|
| `deadzone` | A magnitude below it reads 0. On an `axis1` that is the value; on an `axis2` it is **radial** — the magnitude of the pair — so a diagonal held past the threshold keeps both components |
| `curve` | `"linear"` (the default), `"quadratic"` (squares, keeping the sign), `"cubic"`, or a function taking the reading and returning the shaped one |
| `invert` | `true` negates the reading — both components, for an `axis2` |
| `smoothing` | The time constant, in seconds, the reading approaches its target over. `0` (the default) arrives at once |
```luau
-- look.inputBinding/init.luau
return {
label = "Look",
kind = "axis2",
deadzone = 0.12,
curve = "quadratic",
smoothing = 0.05,
kbm = B.mouseDelta(),
gamepad = B.padStick("right", { as = "delta", unitsPerSecond = 1200 }),
touch = B.touchDrag({ zone = "right" }),
}
```
The shaping lands on the reading the classes produced, after `as` /
`unitsPerSecond` / `scale` have brought each of them into the control's own
unit — so one `deadzone` is written once, in that unit, and covers the
stick, the mouse and the finger together.
`smoothing` carries the same value toward whatever the devices report next,
so a control whose context leaves, whose group stands down, or whose gate
closes drains to neutral rather than cutting to it, and reports its drop
frame when it arrives.
Shaping is refused on a `button`: it is held or it is not, so there is no
magnitude to cut, bend or approach. Say when a button may read at all with
`gate`.
## Events
A binding exposes the events a controller subscribes to. Handlers take
positional arguments, so a movement handler reads them directly rather than
unpacking a table every frame.
| Event | Fires |
|---|---|
| `input` | Every frame the binding is active, carrying `(value, dt, active)` — and once more on the frame it goes inactive, with `active = false` and the neutral value |
| `pressed` | The press edge of a button |
| `released` | The release edge of a button |
| `changed` | When the value changes |
`input` firing on the drop frame is what lets one handler both start and
stop motion. Inside a component, whose hooks reach its fields through
`public`:
```luau
map.move:onInput(function(v, dt, active)
public.moving = active
if not active then return end
local p = public.entity.position
local step = public.speed * dt
public.entity.position = { p.x + v.x * step, p.y, p.z - v.y * step }
end)
```
## Ref methods
- `:record()` — the validated binding record. Raises when a class is
missing or the record is malformed, naming what is wrong.
- `:problems()` — every problem with the record, without raising. What an
authoring tool reports so a whole map's faults surface at once.
- `:inspect()` — `{ label, kind, classes }` for `asset.inspect`.
- `.events` — the subscribe-only view over the four events above.
## Creating one
`asset.create("inputBinding", name, opts)` writes a record carrying every
device class, so a binding is complete the moment it exists:
```luau
asset.create("inputBinding", "boost", {
label = "Boost",
kind = "button",
kbm = '{ B.key("ShiftLeft") }',
gamepad = '{ B.padButton("left_shoulder") }',
touch = '{ B.touchButton({ zone = "right-lower" }) }',
})
```
## In the Inspector
Binding: the binding's label, its kind and the device classes it binds, every problem its definition has, and **Open** for its source.
# lightmapData
A baked-lighting container: ONE asset per scene holding every baked
lighting payload the GI bake flow produces — per-entity lightmaps and
per-volume probe-field bricks. The container is what makes a bake
persistent: a fresh boot (or a runtime-profile session) restores baked
lighting from it with zero re-baking.
## How it's referenced
Entities point at the container through typed fields and resolve their
own entry out of its manifest:
- `Model.lightmapData` / `SkinnedModel.lightmapData` — set by the bake
flow on every per-texel receiver; the component's awake hands the ref
to the lightmap manager, which rebuilds the runtime lightmap texture +
material from the entry keyed by the entity's id.
- `VolumeProbe.lightmapData` (+ its `fieldId`) — set when a volume's
field is baked; the component's awake restores the SH buffer and
republishes the volume into the renderer's irradiance set.
Because every receiver shares one container, a scene with hundreds of
baked entities stays ONE asset in the world listing.
## Layout
```
<name>.lightmapData/
manifest.yaml version + `lightmaps` (by entity id) + `probeFields` (by field id)
lm_<key>.bin lightmap payload: raw LE f32 RGBA, resolution² × 4 floats
pf_<key>.bin probe-field payload: raw LE f32 SH L2, 36 floats per probe, X-fastest
```
## Lifecycle
`baking.all` creates (or reuses) the scene's container and writes every
baked entry; `baking.clear` removes entries (a full-scene clear empties
the container). Entries are replaced atomically per key on re-bake.
Instance methods (`:manifest()`, `:lightmap(key)`, `:probeField(key)`,
`:setLightmap(...)`, …) are the read/write surface — see the behavior
docs via `asset.inspect`.
## In the Inspector
Selecting a lightmap container opens its **Bake** section, read from `manifest.yaml`: the manifest's version, a table of the baked lightmaps (the entity each belongs to, its resolution and intensity) and a table of the probe fields (each field's resolution per axis and probe count). A container nothing has been baked into says it has no lightmaps and no probe fields.
# plugin
Compiled code in a world, used the way a module is.
A plugin is a WebAssembly component in a `<name>.plugin/` asset. Code that
uses one `require`s it and calls it like any module: the calls answer values,
and a refusal raises. Nothing about the call says compiled code ran, the way
calling into a native library from Python does not.
```luau
local counter = require("counter")
local total = await(counter.add(2)) -- a number
print(await(counter.total())) -- 2
```
It is for work Luau cannot do fast enough, or cannot do at all: a simulation
step, a decoder, a solver, a model.
## Getting one into a world
Write the component into the world as a `.wasm` file (upload it). It becomes
a plugin asset of the same name, with the component moved inside, and it
loads. The asset starts with:
```
counter.plugin/
├── plugin.wasm the component
├── plugin.yaml what it offers, and where it loads
├── surface.module/ the module a `require` of the asset lands on
├── README.md this plugin's own description
└── .metadata
```
Nothing is callable until `plugin.yaml` lists it. Edit it to name the methods
the component offers, and the plugin reloads with them.
## plugin.yaml
```yaml
profiles: # where it loads; required
- editor
- runtime
storage: none # none | private; none when left out
events: private # private | exposed; private when left out
memory: 512MiB # the most memory it may hold; 4GiB when left out
exposed: # the methods a caller may run; none when left out
- name: add
- name: total
```
- **profiles** says where the plugin loads. A `runtime` plugin is part of the
game: components and scene entrypoints can call it, and a player loads it.
An `editor` plugin is for authoring, and a call to it from a component or an
entrypoint is refused, because the shipped game would not have it.
- **storage** `private` gives the plugin a store of its own, in this world,
that survives a restart. With `none` what it stores lasts until it is
reloaded.
- **events** `exposed` lets code in the world listen to the events the plugin
raises. With `private` nothing in the world hears them.
- **memory** is the most memory the plugin may hold, written with `KiB`,
`MiB` or `GiB`, up to `4GiB`, which is also what a plugin that says nothing
gets. A plugin that would grow past it stops, and the log says it went past
its `memory:`.
- **exposed** is the plugin's whole callable surface. A method not listed
cannot be called, whatever the component contains, and a listing that names
a method the component does not have is refused when the plugin loads.
## Using it
The asset's `surface.module` is its Luau face, and `require("<name>")`, with
the asset's name, lands on it. Its code is `surface.module/init.luau`, and
each of its functions calls the plugin through the asset it belongs to:
```luau
local self = asset.containing(__FILE__)
local me = self.modules.shared.forAsset(self)
local M = {}
function M.add(amount: number)
return me.call("add", amount)
end
return M
```
- Arguments are numbers, strings, booleans, nil, buffers, handles, and tables
of them. A whole number arrives as an integer. A string has to be text; send
bytes as a `buffer`, which arrives whole, as bytes.
- A file or a folder goes as a handle, which the plugin reads or writes by
itself, without a copy through the call:
```luau
local weights = vfs.open(self.path .. "/weights.bin") -- read a file
local model = vfs.openDir(self.path .. "/model") -- read a folder
local out = vfs.sink("/source/out/sphere.zvol", { maxBytes = 64 * 1024 * 1024 })
local frames = vfs.dirSink("/source/frames", { maxFiles = 240, maxBytes = 200 * 1024 * 1024 })
me.call("render", model, frames)
```
A handle lets the plugin do what this script could do at that path, and
nothing more: a plugin has no filesystem of its own. A sink's file appears
when the plugin closes the sink or lets go of it, and only the world's own
files take a sink. The `plugin-development` guide has the rules.
- Entities go as a binding: `ecs.bindEntities(ids):forPlugin()`. The plugin
reads and writes their fields as packed floats and never learns an id; a
write it makes answers to the same locks, owners and builds this script's
own `entity.batchWrite` does.
- A GPU buffer goes as `buf:forPlugin()` (a `"gpu"` buffer from
`substrate.createBuffer`), and a compute shader as `shaderRef:forPlugin()`.
The plugin writes and reads the buffer's floats and dispatches the shader
over buffers the same script handed it. It never learns a buffer's name or
a shader's key, so it reaches no buffer it was not given.
- The answer is the value the plugin returned: a table as a table, a number as
a number, bytes as a `buffer`.
- A refusal raises where it is awaited: a method not exposed, a plugin that is
not loaded, or the plugin's own error.
- `me.on(function(eventType, payload) ... end)` listens to the plugin's
events, waiting for it to load first. The payload is a value, as an answer
is. It needs `events: exposed`.
- A refusal is an error like any other, and `pcall` catches it.
- `plugins.isLoaded("<name>")` answers whether it is running, and never
raises.
## More than one part
A plugin can carry more than its surface: modules the surface builds on, and
an editor panel. They sit beside `surface.module` inside the asset:
```
counter.plugin/
├── plugin.wasm
├── plugin.yaml
├── surface.module/ what `require("counter")` lands on
├── history.module/ a module the surface uses
└── panel.editorPanel/ a dock tab
```
The parts reach each other with the dot form, which means the same thing
wherever the asset is installed:
- From a module, `require(".history")` is the module beside it.
- From the panel, `require(".")` is the plugin (its surface), and
`require(".history")` the module beside the panel.
The surface IS the plugin: it has no name of its own, so no part requires
`.surface`. Don't write a path (`./history.module`) or a name that says where
the asset is installed (`require("counter.history")`): moved into a library,
the asset stops finding its own parts.
## While it runs
- **A new build replaces it in place.** Upload the component again under the
same name and the running plugin is replaced, with no restart. Uploading the
same bytes again changes nothing.
- **Editing plugin.yaml reloads it.**
- **Removing the asset stops it.**
- **A new build or an edit stops a call in progress.** A call the plugin is
in the middle of answers that the plugin was stopped, however long it would
have run, and the new build starts.
- **A crash stops it once.** If the component traps, the plugin stops, the log
says so in one line, and every later call raises that it stopped and why,
until it loads again: a new build, or an edit to `plugin.yaml`.
- **`plugins.status()`** lists each plugin: whether it is loaded, why not, and
its component: the SHA-256, the size, and what built it.
The same holds in the desktop engine and in a browser.
## Building one
The `plugin-development` guide covers writing a component: the interface in
`zero-plugin.wit` beside this file, a Rust project that builds one, how calls
are encoded, what a plugin may use, and the development loop.
# Bundle (asset type)
A bundle is a composable, spawnable entity assembly— a saved entity
hierarchy plus its components, sub-assets (meshes, textures,
animations, materials, sub-bundles), and any nested data, packaged
into a single addressable identity. Bundles are the engine's "prefab"
primitive.
There are **two ways** to bring a bundle into a scene — and the
difference matters enormously for scene saving and live editing. See
"How to spawn" below before you write anything.
If you want one snapshot of a whole world / level, use a `.scene`.
## Where it lives
- Source: `/zero/source/.../<Name>.bundle/`
- Identity: `<Name>` (the `.bundle` suffix strips for use in
identities, but the on-disk folder keeps the suffix).
- Folder shape (container type — open child set):
- `entity_template` — JSON of the entity hierarchy + components.
**Required.**
- `preview.png` — a rendered still of the assembled hierarchy, the
bundle's persisted visual description. **Required.** Rendered when
the bundle is staged (`zm add`) with its preview missing or stale,
and by `generatePreviews`; it syncs, publishes, feeds image-based
search, and gives browsers a thumbnail.
- Anything else: meshes / textures / materials / animations /
sub-bundles. Validator allows arbitrary additional files
(`allow_unlisted: true`).
## How to create one
Two paths, depending on whether you have an in-scene hierarchy or are
authoring from scratch:
```luau
-- From an existing in-scene entity: composes the given entity tree into a bundle.
local bundle = asset.create("bundle", "<Name>",<entityProxy/id>)
-- Or scaffold an empty bundle, then update it from an entity:
local bundleRef = asset.create("bundle", "<Name>")
bundleRef:update(entityId)
```
## How to spawn
### 1. `Asset` component — live-linked (the canonical way)
**This is the primary way to put a bundle into a scene that survives
saving as an asset reference.** Spawn an empty entity, attach the
`Asset` component, point it at the bundle:
```luau
local car = entity.spawn("car_1")
car.component.add("Asset", { source = "<bundleIdentity>" })
```
What you get:
- The bundle's hierarchy spawns as **temporary** children under the
owning entity. They're real, addressable runtime entities, but
they are NOT serialized into `scene.json` on save, only the Asset component and its entity is saved.
- **Live editing of the bundle is supported.** When you edit
anything inside the `.bundle/` (entity_template, meshes,
materials, sub-bundles, components), every entity in the world
carrying that `Asset` component automatically tears down its
spawned children and rebuilds them from the new template — same
frame, no restart, no manual reload. The `onAssetReload` hook in
`Asset.component/init.luau` drives this.
- **Per-instance overrides survive across reloads.** Move a spawned
child, rename it, add/remove components on it, edit a component's
public state — the changes land in the Asset's `public.diff` (a
sparse delta keyed by the child's `original_id`) at save time and
are replayed by `bundleRef:instantiate()` on next load. The bundle stays
a single source of truth; per-spot tweaks ride on top.
- **Stable child ids across reloads.** `public.idMap` records the
`original_id → runtimeId` assignment on first spawn; on every
subsequent spawn the same mapping is reused so cross-entity
references (e.g. `SkinnedModel.skeletonRoot = "ent_xxx"`) stay
valid.
### 2. `bundleRef:instantiate` — baked, no live link
Resolve the bundle and instantiate it onto an entity — this spawns the
children **without** the live-link plumbing the `Asset` component
provides:
```luau
local car = entity.spawn("car_1")
asset.resolve("<Name>", "bundle"):instantiate(car)
```
What you get — and the trade-offs:
- The children spawn as **regular** (non-temporary) entities. On the
next `layers.active:save()`, the entire spawned hierarchy is serialized into
`scene.json` verbatim.
- **No live link to the bundle.** Editing the `.bundle/` after the
fact has no effect on already-spawned hierarchies. The bundle was
effectively consumed at spawn time.
- Scene-save / restore round-trip works the same as for any other
hand-authored entity tree.
Use this path when you want a one-shot expansion of the bundle into
permanent scene state (e.g. you're populating a scene's static
layout from a parametric bundle and don't want a live link).
You can convert a live-linked instance into a baked one explicitly
via `Asset:bakeIntoScene()` — this drops the `Asset` component and
promotes the temporary children to permanent scene entities.
## How it operates
1. **Registration.** Writing into a `.bundle/` folder indexes the
asset with the container-category restore plumbing.
2. **Inner refs.** Component fields that reference assets inside the
bundle use the `__ref` shape (`{ "__ref": "<guid>", "name": "...",
"type": "..." }`). The asset registry resolves them at spawn
time.
3. **Identity preservation.** The `.bundle` suffix stays in the
identity for container types — `<Name>.bundle` resolves under
that exact string, distinguishing it from any `<Name>.scene` at
the same stem.
4. **Hot reload.** Saving `entity_template` (or any file in the
bundle directory) fires the engine's per-asset content-changed
hook, which calls `onAssetReload("source")` on every entity
whose `Asset` component points at the bundle. Each carrier
despawns its children and re-instantiates against the new
template — typically next frame.
## Discovery
- `asset.list("bundle")` — every registered bundle.
- `asset.inspect("<name>")` — sub-asset catalog, source, this type
README.
- `ls /zero/source/<Name>.bundle` lists the files the folder holds.
## Authoring conventions
- Prefer `bundle:update()` or `asset.create("bundle","<name>",entity)` over hand-authoring `entity_template`. The
in-scene composer wires `__ref` shapes correctly and pulls in every
transitively-needed asset.
- Keep bundles focused — one prefab per bundle. If you have a "vehicle
+ driver + sound" assembly, split into three bundles and reference
them from a scene rather than packing all three into one bundle.
- Name child entities meaningfully — bundle interiors are
inspectable, and stable IDs let other tooling (`entity_template`
edits, animation hooks) find them.
- Sub-bundles compose: a bundle's `entity_template` can `__ref` a
child `.bundle/`. The asset registry resolves them transitively.
## Common pitfalls
- **Confusing the two spawn paths.** `Asset` component = live link,
reference-only scene save. `bundleRef:instantiate()` directly = baked,
full hierarchy in `scene.json`.
- **Inner-ref guids drift.** If you copy an `entity_template` from
one bundle into another, the `__ref` guids may not resolve —
re-compose from a live scene rather than copy-pasting JSON.
- **The `.bundle` suffix is part of the identity.** This is the
container-category convention. Don't strip it in reference strings.
- **Live editing only fires for live-linked carriers.** Already-baked
entities don't update when you edit the source bundle.
## Related types
- `Asset.component` — the canonical mount point for a live-linked
bundle. See its README for the `idMap` / `diff` machinery in
detail.
- `.scene` — owns a whole world's worth of entities; spawns bundles
into itself via `Asset` components on per-spot entities.
## In the Inspector
Selecting a bundle opens its **Contents** section, from the bundle's inspect detail: the template's node count, its root, the component types attached across it, a table of each renderable node's mesh and material, and a link to each of those meshes and materials.
# guide
A guide is a single-file documentation asset: a `<name>.guide/` folder whose body is `guide.md`, surfaced through the `guides` MCP tool, the `man` shell builtin and the Docs panel. Drop one anywhere under `/zero/source/`, a `.package` included, and it shows beside the built-in guides.
## In the Inspector
Guide: the guide's word count, its headings, and **Open in Docs**, which opens it in the Docs panel.
# dataType (asset type)
A dataType is a user-authored typed-data contract: it declares a set of
fields — names, types, constraints, defaults — that any bound `.data`
instance must satisfy. A contract can carry an optional `behavior.luau`
of methods its instances expose. Think of it as a ScriptableObject
schema: the contract defines structure and behavior, `.data` instances
supply the values.
## When to use one
- You want a typed, validated configuration shape (a weapon's damage /
fire mode / recoil profile, a quest's objectives, a loot table's
entries) that many `.data` instances can be authored against.
- You want field-level validation (required, numeric ranges, enums,
references to other assets or data instances) enforced the same way
everywhere the contract is used.
- You want shared structure across related contracts without
duplicating field declarations — `extends` factors common fields
into a parent contract.
If you only need a named set of values for settings something already
declares, use a `.preset` instead. If you need executable shared logic rather than
typed configuration, use a `.module`.
## Where it lives
- Source: `/zero/source/.../<Name>.dataType/`
- Identity: `<Name>` (the `.dataType` suffix strips).
- Folder shape:
- `schema.yaml` — the field declaration (`fields:`, optional
`extends:`). **Required.**
- `README.md` — instance documentation: what the contract models,
what each field means. **Required.**
- `.metadata` — description + tags for search. **Required.**
- `behavior.luau` — optional ref methods this contract's `.data`
instances expose beyond the built-in `:contract` / `:satisfies` /
`:validate` surface.
## How to create one
```luau
asset.create("dataType", "<Name>")
-- Creates: /zero/source/<Name>.dataType/
-- schema.yaml (`fields: {}`, a valid contract with no fields yet)
-- README.md (instance README template)
-- .metadata (empty description/tags — fill both to publish)
```
Then edit `schema.yaml` to declare the contract's fields.
## `schema.yaml` field-spec vocabulary
```yaml
extends: "item" # optional: parent contract identity
fields:
damage:
type: number
required: true
min: 0
max: 100
fireMode:
type: string
enum: ["semi", "burst", "auto"]
default: "semi"
muzzle:
type: vec3
default: [0, 0, 0]
tint:
type: color # "#rrggbb"/"#rrggbbaa" or {r,g,b[,a]}
fireSound:
type: assetRef
assetType: soundClip # required for assetRef fields
recoil:
type: dataRef
contract: recoilProfile # required for dataRef fields
required: true
falloff:
type: array
items:
type: struct
fields:
distance: { type: number }
multiplier: { type: number }
```
Field types: `number`, `string`, `boolean`, `vec3`, `color`, `assetRef`,
`dataRef`, `array`, `struct`.
- `required` — a boolean; a field with a `default` is never "missing"
even when `required` is set.
- `default` — must itself satisfy the field's own constraints (checked
at declaration time).
- `min` / `max` — apply only to `number` fields.
- `enum` — apply only to scalar fields (`number` / `string` /
`boolean`); the value must equal one of the listed entries.
- `assetRef` — needs an `assetType`; validated against
`asset.resolve(identity, assetType)`.
- `dataRef` — needs a `contract`; validated against whether the
referenced `.data` instance's contract chain includes it
(`:satisfies`).
- `array` — needs an `items` field spec every element must satisfy.
- `struct` — needs a `fields` map of nested field specs; struct values
reject unknown keys the same way top-level values do.
## `extends`
A contract may declare `extends: "<parentContract>"` to inherit the
parent's fields. The child adds new fields — it never redeclares a
field the parent (or any ancestor) already declared; doing so is a
schema error. Behavior is optional at every level: a contract may
carry `behavior.luau` or not regardless of whether its parent does.
Chains are single-inheritance and acyclic — a cycle raises loudly the
moment the chain is resolved (`:schema`, `:validate`, `:defaults`,
`:chain` all resolve the chain). Editing a parent's schema does not
re-warn its child contracts at edit time; validation stays loud where
the chain is used — `:schema` / `:validate` calls and the publish gate.
## Ref surface (`AssetRef<dataType>`)
- `ref:schema()` — the merged field map (own fields + every field
inherited through `extends`).
- `ref:validate(values)` — `(ok, violations)` against the merged
schema. `violations` is an array of `{ path, message }`.
- `ref:defaults()` — the default value table the merged schema
declares (a fresh, mutable table).
- `ref:parent()` — the parent contract ref (`extends`), or nil for a
root contract.
- `ref:chain()` — the full extends chain as refs, root parent first,
this contract last.
- `ref:instances()` — every `.data` instance bound to this contract or
to a contract that extends it, as `AssetRef`s. A full scan over the
world's data assets — a discovery surface for authoring and tooling,
not a per-frame call.
## Discovery
- `asset.list("dataType")` — every registered contract, as `AssetRef`s.
- `asset.inspect("<name>")` — the contract's files, declared schema
body, instance README, and this type README.
- `ls /zero/source/<Name>.dataType` lists the files the folder holds.
## Authoring conventions
- Name contracts for the concept they type (`weapon`, `questObjective`,
`lootTable`), not for a specific instance.
- Factor genuinely shared fields into a parent contract via `extends`;
don't duplicate a field declaration across sibling contracts.
- Document every field's meaning and units in `README.md` — the schema
only carries types and constraints, not intent.
## Common pitfalls
- **Redeclaring an inherited field.** `extends` merges parent fields
in; a child that re-declares a field name the parent already
declared is a merge error, not a silent override.
- **Cyclic `extends`.** Contract A extending B extending A raises
loudly the first time the chain is resolved — fix the chain, there
is no partial result to fall back to.
- **assetRef/dataRef without existence checks.** `assetType` and
`contract` on ref fields are declaration-time requirements; the
referenced asset or data instance is checked at validation time, not
declaration time.
## Related types
- `.data` — a configured value instance bound to a dataType contract.
- `.preset` — a named set of values for one declarer's settings schema
(an assetType, an importer, a component), not a contract of its own.
- `.component` — executable entity behavior, versus this type's typed
configuration data.
## In the Inspector
Contract: the contract it extends (a link), every field across the extends chain with its type, whether it is required, its default and its bounds or allowed values, and **Count instances**, which scans every data asset for the ones that satisfy it (a count taken before a data asset was made or removed says so).
# Tool (asset type)
A tool is a single agent-callable function whose schema is its
`typed function` signature. Tools are the workflow surface — composed
Luau operations that bundle multiple engine APIs into one named call,
suitable for agents (and for use from `execute`). Each tool has a
declared input shape, return shape, and a strict result envelope
(`ZmToolResult`).
**Every exported tool function is declared `typed function`.** The
`typed` keyword is what makes the signature real: it compiles to a
runtime dispatch wrapper that checks each argument against its
declared type and raises on a mismatch. A plain `function` — even one
carrying Luau type annotations — is checked by nothing at call time,
so the tool accepts any input and reports success on garbage. See
"The typed signature is the schema" below.
## When to use one
- You're composing several engine APIs into a workflow that's worth
naming and discovering (`tools.list`, `search_tools`).
- You want an agent to be able to call this function by name without
reading source code — the typed signature is the API contract.
- The operation has clear success / failure modes that fit
`{ exitCode, data?, stdout?, message? }`.
If the function is just a Luau utility called from other code, use a
`.module`. If it's stateful background work, use a `.service`. If
it's pure GPU compute, use a compute `.shader`.
## Where it lives
Tools nest under a `.toolbox/` parent — toolboxes are the namespace.
- Source: `/zero/source/.../<Toolbox>.toolbox/<name>.tool/`
- Identity: `<Toolbox>.<name>` (dotted form — the toolbox name is
part of the tool identity).
- Folder shape:
- `init.luau` (or `init.lua`) — exports the function, and carries its
schema in `--!desc` / `--!arg` / `--!return` / `--!example`
annotations above it. The typed signature IS the tool's signature.
**Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — tool-level tier and tags. **Required.**
## How to create one
Use the workflow tool that scaffolds the right `.tool/` shape under
an existing toolbox:
```luau
-- The `tools` global authors a tool inside an existing toolbox:
tools.create({
name = "<name>",
toolbox = "<Toolbox>",
description = "What this tool does, agent-facing.",
code = "return shared.ok(true)", -- the function body
})
-- Or scaffold the folder manually:
local box = asset.resolve("<Toolbox>.toolbox")
asset.create("tool", "<name>", { into = box })
```
Always nest under an existing toolbox — if you don't have one yet,
call `tools.createToolbox({ name = "<Name>", description = "..." })`
first.
## How it operates
1. **Registration.** Writing `init.luau` into a `.tool/` folder
registers the tool with the tools registry. It becomes callable
as `tools.use("<toolbox>", "<name>", ...)` from Luau,
`use_tool { toolbox, tool, args }` over MCP, and
`zero <toolbox> <name> [args]` from the engine shell.
2. **Schema validation.** The `typed function` signature declares the
parameter shape. Its runtime dispatch wrapper checks each argument
before the body runs and raises a message naming the argument, the
expected type, and what arrived.
3. **Return envelope.** Tools MUST return `ZmToolResult`:
```
{ exitCode = 0|n, data? = any, stdout? = string, message? = string }
```
`exitCode = 0` means success; non-zero means failure, with
`message` carrying the human-readable reason.
4. **Discovery.** The tool surfaces in `tools.list()`,
`search_tools { query: "..." }`, and `asset.inspect`'s
`exposes:` section (parsed from the typed signature and the
`--!` annotations).
5. **Hot reload.** Editing `init.luau` re-registers the tool.
Subsequent calls see the new behaviour / schema.
## Discovery
- `tools.list()` — every registered tool (any toolbox).
- `search_tools { query: "..." }` — MCP-side tool search.
- `asset.list("tool")` — same set, asset-style listing.
- `asset.inspect("<toolbox>.<name>")` — signature, parameters,
return shape, this type README.
- `ls /zero/source/<Toolbox>.toolbox/<name>.tool` lists the files the folder holds.
## Authoring conventions
- **Implementation lives in `init.luau`.** The tool's full function
body — argument validation, the call into engine APIs, the
return value — goes in `init.luau`. The toolbox's
`shared.module/` is for genuinely cross-tool helpers (`ok` /
`fail` constructors, shared parsers / validators), not per-tool
logic. Do NOT make `init.luau` a one-line forwarder onto a
function defined in `shared.module/`.
- Use `shared.module/` in the parent toolbox for `ok` / `fail`
result constructors. Don't hand-roll the envelope per tool. Pull
it in with `local shared = require(".shared")` from any tool
that needs the helpers.
- Annotate every public function with `--!desc` / `--!arg` /
`--!return` / `--!example` directly above the function — the LSP
and toolbox surfaces extract these.
- **Declare every exported function `typed function M.name(arg: T,
opt: U?): R`.** This is not conditional on the signature being
"clear" — a loose argument is the case that needs the checked
contract most. Give the argument the type it actually accepts
(a union, a named table type, a literal enum) instead of dropping
to an unchecked `function`.
- Keep tools focused. One tool, one named workflow. Split rather
than grow.
- Tag tools in the sibling `.metadata` (`{ "tags": [...], "tier":
"core|content|specialized" }`) so `search_tools` can find them by
domain (e.g. `entity`, `scene`, `assets`, `physics`).
## The typed signature is the schema
The `typed` keyword compiles the function into a dispatch wrapper
that validates arguments at call time. Without it there is no check
at all, so the tool runs its body on whatever arrived and returns a
success envelope built from garbage. Type each argument as narrowly
as the operation actually accepts:
```luau
export type Mode = "edit" | "play"
export type SpawnOpts = {
position: { number }?,
parent: EntityRef?,
count: number?,
}
--!desc Spawn a primitive and return the entities it created.
--!arg kind Primitive shape to spawn.
--!arg opts Placement and repetition options.
--!return The spawned entity refs.
--!example "cube", { count = 4 }
typed function M.spawn(kind: ("cube" | "sphere" | "plane"), opts: SpawnOpts?): { EntityRef }
```
- **A fixed set of accepted words is a literal union**, never
`string`. `("cube" | "sphere")` rejects `"Cube"` at the call and
lists the accepted values in the error; `kind: string` accepts
`"banana"` and fails somewhere deeper, or not at all.
- **A structured argument is a named `export type`**, never
`{ [string]: any }`. Naming it puts every field and its type on
the tool's page and checks them on entry.
- **A named type is only as strong as its fields.** `opts: DrawOpts`
where `DrawOpts = { value: any }` passes for a table and checks
nothing inside it — the same hole, one level down. The argument
checker walks nested fields, so type each one; a type name is not
a place to put the work off.
- **A dispatch table keyed by an `op` string is several tools.**
`{ op: string, [string]: any }` is one unchecked entry point
wearing N signatures — split it so each operation carries its own
checked arguments.
- **An entity or asset argument is `EntityRef` / `AssetRef<kind>`**,
never `any` and never a bare name string.
- `any` is correct only for a value the tool genuinely does not
constrain — a passthrough payload, arbitrary user data. It is not
a placeholder for a type not yet written down.
## Common pitfalls
- **A plain `function` export.** The tool registers and dispatches,
so nothing looks wrong — it just never rejects bad input, and
every call reports success. Declare it `typed function`.
- **Annotations without `typed`.** `function M.f(x: string)` reads
as typed and checks nothing at runtime; the annotation only
informs the LSP. The keyword is what enforces it.
- **Wrong return envelope.** Returning a raw value instead of
`{ exitCode = 0, ... }` will be flagged by callers expecting
`ZmToolResult`.
- **Tool identity.** The fully-qualified identity is
`<toolbox>.<name>`, NOT just `<name>`. Toolbox-less tools don't
exist by design.
- **Missing dependency.** Tools requiring another package /
service must declare it; otherwise the call fails at runtime
with a missing-module error.
## Related types
- `.toolbox` — the required parent namespace for tools.
- `.module` — for Luau libraries with no agent-facing schema.
- `.service` — for stateful background work, not callable
request/response operations.
## In the Inspector
Tool: how the tool is called (its signature), what it does, each argument, what it returns, and its examples, with **Open** for its source.
# preview
Render an asset's preview in the preview studio: an isolated camera, lit only
by its own three-point rig, over a neutral backdrop, that nothing in the scene
reaches. `ref:preview()` renders any asset by the recipe its type declares under
`preview:` in its `type.yaml`, and these are the primitives it calls: they spawn
temporary entities, frame an offscreen camera over them, render one frame,
read it back as a PNG, and tear the entities down.
## Surface
- `preview.fromEntities(makeFn, opts?) -> PreviewResult` — run `makeFn` to
instantiate entities, frame a camera to their bounds, render one offscreen
frame, and return the still PNG.
- `preview.fromRecipe(ref, recipe, opts?) -> PreviewResult` — render `ref` by a
declared recipe: `instantiate` stands it through its own `instantiate`,
`surface` paints the material its type's `ref.previewMaterial` returns on the
recipe's mesh, and `image` fits a file the asset holds to the frame on the
studio backdrop without rendering anything.
- `preview.backdrop() -> { r, g, b }` — the studio backdrop's colour in a
finished preview, 0-255.
`PreviewResult` is `{ available, imageBase64?, rendered?, width?, height?,
bounds?, stats?, reason? }` — `imageBase64` is the rendered PNG when `available` is true, and
`reason` explains why when it is false. `opts` is `{ size? = { width, height },
angle? = { yaw, pitch } }`.
## Example
local result = asset.resolve("gold", "material"):preview({ size = { width = 512, height = 512 } })
-- result.imageBase64 holds the rendered PNG (base64)
# Style (asset type)
A style is a UI design-token bundle: colour palette, spacing scale,
typography pairs, and the widget classes built from them. Registered
with the UI theme system, its classes cascade to every widget that
names them. Authoring a style is the way to express a brand / theme;
consumers register it once and every widget carrying its classes picks
up the tokens.
## When to use one
- You're branding a UI surface (game theme, editor theme, dialog
theme) and want a named token set widgets pick up automatically.
- You want a swappable theme — light vs dark, normal vs accessibility
contrast.
- You want designers to edit tokens (`color.primary`,
`spacing.md`) without touching widget code.
If you need per-widget overrides, those go inline on the widget, not
in a style. If you need shader-driven looks, that's a `.shader` +
`.material`.
## Where it lives
- Source: `/zero/source/.../<name>.style/`
- Identity: `<name>` (the `.style` suffix strips).
- Folder shape:
- `init.luau` (or `init.lua`) — returns the module carrying the
token table. **Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("style", "<name>")
-- Creates: /zero/source/<name>.style/
-- init.luau (token scaffold: color / spacing / font)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("style", "<name>", { folder = "themes" })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.style/` folder
registers the asset — it is listable, inspectable, and referencable
by identity.
2. **Token shape.** `init.luau` returns a module exposing `M.tokens`,
one nested table per token category:
- `color.<name>` / `spacing.<name>` / `font.<name>` are the
conventional three; a style may declare any category it wants.
- A value is a literal (a `"#rrggbb"` colour string, a number, an
array) or a `"$otherToken"` reference resolved during the
cascade.
An optional `M.styles` maps a selector — `<widgetType>`,
`<widgetType>.<className>`, or a bare `.<className>` — to a block
of style properties, each value a literal or a `$token` reference.
3. **Cascade.** The stylesheet resolves a widget's look in the order
`type` → `type.class` → `.class` → inline props. Widgets select
classes with their `classes` (or `class`) prop.
4. **Application.** The UI theme surface takes the style's table:
`Theme.register(name, tokens_and_styles)` from
`@builtin::modules.zui.theme` resolves every `$token` in Luau and
pushes the flat result through `ui.registerTheme`. From there
`ui.setTheme(name)` makes it the active theme, and
`ui.useStyles(name)` applies a registered theme's classes
additively without changing the active one. `ui.defineStyle` /
`ui.defineStyles` define individual classes directly.
5. **Hot reload.** Editing `init.luau` reloads the asset; re-register
the style for the change to reach the live stylesheet.
## Discovery
- `asset.list("style")` — every registered style.
- `asset.inspect("<name>")` — `tokenCategories` (the top-level keys of
the style's `M.tokens` literal, read from its source text), source,
and this type README.
- `ls /zero/source/<name>.style` lists the files the folder holds.
- `styleRef:getInitScript()` — the entry script's raw text.
## Authoring conventions
- Write colours the way the theme system reads them — `"#rrggbb"` /
`"#rrggbbaa"` hex or `rgba(r,g,b,a)` strings.
- Name tokens semantically (`color.primary`, `color.danger`,
`spacing.gutter`), not by visual value (`color.blue`,
`spacing.eight`). Semantic names survive theme swaps.
- Keep token names stable. Widgets reference tokens by name —
renaming a token forces every consumer to update.
- Document `light` / `dark` variants under separate `.style/` folders
with paired names (`game.style`, `gameDark.style`) rather than
switching values within one style.
## Common pitfalls
- **Unknown `$token` reference.** A `"$name"` with no matching token
fails the cascade — `Theme.register` returns
`false, "token 'a': unknown token: $name"` and the style never
reaches the stylesheet. Read the error rather than the render.
- **Token reference cycles.** `$a` → `$b` → `$a` is reported as
`token 'a': cycle detected: a → b → a` at register time.
- **Missing tokens.** A widget asking for `color.warn` when the
style doesn't define it falls back to the active theme. Inspect the
style to confirm the token surface.
## Related types
- `.component` — `UiPanel` and other widget components consume
styles.
- `.material` / `.shader` — for 3D surface looks (different cascade
system).
- `.package` — to ship styles + components together as a theme
package.
## In the Inspector
Selecting a style opens its **Tokens** section, from the theme `styleRef:loadTheme()` returns: a swatch per colour token, its spacing values, and a table of its font tokens (family and size). A style written as YAML style classes (a `styles:` map of class name to properties, applied with `ui.useStyles`) shows how many classes it declares and, for each class, its colour properties as swatches and its other properties as values. A style whose `init.luau` does not load a `tokens` table says why.
# soundClip
An **audio asset** — a managed container holding a sound effect or music
track, addressed by the `.soundClip` suffix.
`soundClip` is a first-class assetType (not a bare plural-dir category) so
that:
- a soundClip has a stable asset **identity** and an explicit `asset_type`
link, and
- a component that plays a soundClip records a real `.refs` edge to it.
## Internal layout
A `.soundClip/` is permissive (`allow_unlisted: true`) — the conversion step
decides its shape. A managed container holds:
```
<name>.soundClip/
source.<ext> the retained source audio (.ogg / .mp3 / .wav / .flac):
`asset.create` keeps a copy of the bytes it was given under
this name, and the importer moves the uploaded file in under
its own name instead. Absent for a PCM-baked clip.
settings.yaml compression settings — see below
data.zaud engine-native ZAUD payload the runtime decodes + plays, under
the codec its own header names
README.md what the sound is and what it is for
```
`data.zaud` is the **preferred primary**: when present the runtime resolves
and decodes it directly. When absent the primary falls through to the source
audio file, so imported-only containers keep working.
## Settings
A soundClip's settings are declared in `settings.luau` and live in
`settings.yaml` — or, for a clip published before that file existed, a legacy
`settings` block inside `.metadata`. Editing any of the encode-relevant ones
re-runs encoding — against the retained source audio when the container has
one, or against the decoded `data.zaud` for a PCM-baked clip — and rewrites
`data.zaud`. Rewriting the retained source audio re-encodes it the same way:
| key | values | meaning |
|-----|--------|---------|
| `codec` | `opus` (default) / `pcm` | output codec. `opus` compresses; `pcm` stores uncompressed samples. |
| `bitrateKbps` | integer, default `96` | Opus target bitrate (ignored for `pcm`). |
| `vbr` | `true` (default) / `false` | Opus variable bitrate. |
| `sampleRate` | integer, `0` = keep source | resample target in Hz. |
| `forceMono` | `false` (default) / `true` | downmix to a single channel. |
| `loadType` | `auto` (default) / `decompressOnLoad` / `streaming` | how the runtime loads the clip. |
| `loopStart` | integer frames, `0` = none | loop-point start. |
| `loopEnd` | integer frames, `0` = none | loop-point end. |
`loadType` alone never re-runs encoding — it decides how the runtime holds
the clip, not what `data.zaud` holds. It acts on an already-playing `Audio`
component instead: the next source that component builds reads the new
value fresh and rebuilds under it.
The `data.zaud` payload is produced by the engine's audio codec, exposed to
Luau as `audio.encode` / `audio.encodePcm` / `audio.decode` / `audio.info` /
`audio.loopSeam` and consumed by this assetType.
Every sample the codec is handed must be a finite number, so `asset.create`
raises when the `pcm` or `bytes` it is given carries a NaN or an infinity, and
the error names how many samples fail and where the first one sits.
## Does it loop without a click
Whole-clip repeat is the loop the runtime plays, so the join between a clip's
last frame and its first is heard once a lap. `clipRef:loopSeam()` reads what
the samples do there: the step the wrap makes (`|x[1] - x[frames]|`) against
the step the signal ordinarily makes between neighbouring samples, as
`ratio = step / meanStep`. The figure is in the units the signal itself moves
in, so a generated ambience travelling a thousandth of a unit per sample and a
synth drone travelling a hundredth are read the same way.
| field | meaning |
|-------|---------|
| `ratio` | `step / meanStep` on the worst channel — one channel clicking is the clip clicking. |
| `step` | `\|x[1] - x[frames]\|`, the step the wrap makes. |
| `meanStep` | the mean `\|x[i + 1] - x[i]\|`, the distance the signal ordinarily travels in one sample. |
| `maxStep` | the largest `\|x[i + 1] - x[i]\|` the channel already carries. |
| `channel` | which channel the four figures above came from, counted from 1. |
| `seamless` | `ratio <= threshold`. |
| `threshold` | the ratio the engine warns past — `8`. |
| `channels` | every channel's own `{ ratio, step, meanStep, maxStep }`, in channel order. |
A bed whose partials complete a whole number of cycles across the buffer reads
near 1; one carrying a percussive strike at its head and silence at its tail
reads in the tens.
```lua
local seam = clipRef:loopSeam()
if not seam.seamless then
print(seam.ratio, seam.step, seam.meanStep) -- e.g. 41.0 0.5993 0.0146
end
```
`asset.create("soundClip", ...)` takes the same reading of the payload it just
encoded and logs a warning naming the ratio when it is past `threshold`, so a
bed that ticks is reported at the call that bakes it. The re-encodes a source
edit and a settings change trigger report it the same way.
The reading is taken on the DECODED payload, so it answers for what the codec
left behind rather than for the buffer that was handed to the encoder — and
for a clip that arrived already encoded, from an import or from ZeroMind, whose
source buffer nobody holds.
## Creating a soundClip
`asset.create("soundClip", name, opts)` reads seven keys of its own out of
`opts`, and the settings table above is one of them. `asset.create`'s
framework keys — `folder`, `into`, `dest` and `overwrite` — apply to a
soundClip the way they apply to every type.
| parameter | type | meaning |
|-----------|------|---------|
| `bytes` | `string?` | encoded source audio (OGG / MP3 / WAV / FLAC), stored verbatim as `source.<ext>` by default. |
| `ext` | `"ogg"` (default) / `"mp3"` / `"wav"` / `"flac"` | which container `bytes` is in. |
| `writeSource` | `boolean?`, default `true` | keep the source audio in the container as `source.<ext>`. `false` skips the copy — the caller supplies the source itself (the importer moves the uploaded file in under its own name instead). |
| `pcm` | `buffer \| string \| { number }?` | interleaved f32 samples — a `buffer`, the shape `microphone.samples` hands back; a binary string of little-endian f32, the shape `audio.decode` returns; or a flat number array. |
| `sampleRate` | `number?` | the rate the `pcm` samples are at, in Hz. Required with `pcm`. To resample a clip, set `settings = { sampleRate = ... }`. |
| `channels` | `number?` | how many channels they interleave. Required with `pcm`. |
| `settings` | `table?` | the full settings table from the section above, baked in the same pass; wins over the defaults. |
`ext` and `writeSource` belong with `bytes`, and `channels` with `pcm`: a
create that passes one of them without the opt it belongs with is refused,
naming both.
```lua
-- from encoded audio bytes (kept as source.<ext>, encoded to data.zaud)
asset.create("soundClip", "music", { bytes = oggBytes, ext = "ogg" })
-- the caller supplies the source itself (moved in under its own name after
-- create, preserving its identity) — the importer's own promote path
asset.create("soundClip", "music", { bytes = oggBytes, ext = "ogg", writeSource = false })
-- from raw PCM samples (no source file; encoded straight to data.zaud)
local samples = buffer.create(960 * 4)
for i = 0, 959 do
buffer.writef32(samples, i * 4, math.sin(i * 0.05) * 0.5)
end
asset.create("soundClip", "beep", { pcm = samples, sampleRate = 48000, channels = 1 })
-- the same samples kept exactly as handed in, under a codec and a load
-- strategy chosen in the one pass that bakes them
asset.create("soundClip", "bed", {
pcm = samples, sampleRate = 48000, channels = 1,
settings = { codec = "pcm", loadType = "decompressOnLoad" },
})
```
A `buffer` is the cheap container for a long clip: a 1.5 s mono 48 kHz clip is
72 000 samples, which is a 288 KB buffer against a 72 000-entry Luau table.
**Choose the codec at create time.** Encoding runs once per bake, and a later
settings change re-encodes from what is already stored — the retained source
audio when the container has one, and otherwise the decoded `data.zaud`. So a clip baked with
the default `opus` and then given `setSettings({ codec = "pcm" })` stores the
Opus signal losslessly rather than the samples that were handed in: the frame
count, the duration and the settings table all read as asked for, and only the
samples differ. Passing `settings` to `asset.create` bakes the samples once,
under the codec they are meant to keep.
Read a clip's settings with `clipRef:settings()`, patch them with
`clipRef:setSettings({ bitrateKbps = 64 })`, read its stored payload's header
with `clipRef:info()`, decode its samples with `clipRef:pcm()`, and read its
loop point with `clipRef:loopSeam()`.
`clipRef:info()` is the length, rate, channel count, codec and loop points of
the payload the container stores, read off its header:
```lua
local info = clipRef:info()
print(info.durationMs, info.sampleRate, info.channels)
```
It is the reading to time something against a clip, such as a caption held for
as long as its line is spoken, because it costs a header read where `pcm()`
decodes every sample to arrive at the same figures. The `sampleRate` it reports is the
rate the payload holds; the `sampleRate` in the settings table above is the
resample target the encode was asked for, and `0` there means the source's own
rate was kept.
`clipRef:pcm()` hands back `(pcm, sampleRate, channels)` — the same triple
`audio.decode` returns. The samples come back packed rather than as a Luau
array: a binary string of interleaved little-endian f32, four bytes per sample,
so `#pcm // 4` is the sample count and one sample reads as
`string.unpack("<f", pcm, i * 4 + 1)` or through `buffer.fromstring(pcm)`.
```lua
local pcm, sampleRate, channels = clipRef:pcm()
local frames = #pcm // 4 // channels
print(frames / sampleRate, "seconds") -- e.g. 1.5 seconds
local peak = 0
for i = 0, #pcm // 4 - 1 do
peak = math.max(peak, math.abs(string.unpack("<f", pcm, i * 4 + 1)))
end
```
The second and third returns are the clip's own rate and channel count, so a
duration is arithmetic on what `pcm()` alone hands back. `audio.info` reads the
same figures off the stored payload without decoding it, and the `topics/audio`
guide lists every field it returns.
The `topics/audio` guide covers synthesis end to end: computing a buffer,
baking it into a clip, playing it from an `Audio` component, and reading it back.
## How a source holds the clip
`clipRef:streams(bytes?)` answers whether a source playing this clip holds it
streaming: `loadType = "streaming"` does, `"decompressOnLoad"` does not, and
`"auto"` streams a clip longer than 5 seconds. Pass the `data.zaud` bytes when
you already hold them, to skip reading the payload again. Every source the
`Audio` component builds asks it, so the policy lives with the clip.
## Auditioning
`clipRef:audition()` plays the clip once through the mixer, unpositioned, on
the `sfx` channel. It plays on a temporary host entity that the scene never
saves and the entity listings leave out, and it replaces any clip already
auditioning. It returns the host's entity id, or nil when the payload is
unreadable. The host goes when the mixer reports the voice ended.
`clipRef:stopAudition()` ends the audition at once and its host goes on the
next frame; it returns whether this clip was the one auditioning. A later
audition ends the earlier one the same way. `clipRef:lastAuditionEnd()` says
how this clip's most recent audition ended once its host is gone, as
`{ host, reason }`: `"ended"` (the mixer reported it played through),
`"stopped"`, `"replaced"`, `"unvoiced"` (no output, or the mixer turned it
away), `"timeout"` (on the mixer past the clip's length with no end reported),
`"neverArrived"` or `"hostGone"`. The Playback section shows it under "Not
playing.". `clipRef:auditionVoice()` is the audition in progress
for this clip: `{ host, voice }`, where `voice` is `audio.voice(host)` (the
mixer's view of the voice, nil until the mixer has it), or nil when this clip
is not auditioning.
## In the Inspector
Selecting a clip shows, after its identity:
- **Clip**: the payload header (duration, sample rate, channels, frames,
codec, packets and the loop points when set) and whether a source holds the
clip streaming or decoded on load.
- **Playback**: Play auditions the clip and Stop ends the audition. While it
plays, the section shows the mixer's state for the voice and, when the voice
is silent, why.
- **Settings**: the settings above.
- **Waveform** (collapsed at first): 96 bars, each the loudest sample of an
equal span of the clip across its channels, from `audio.peaks`. The payload
is decoded a block at a time, so a long clip costs no more memory than a
short one, and it is read again only when `data.zaud` changes.
# Importer (asset type)
An importer is a Luau function that converts a source file (GLB,
PNG, CSV, custom binary) into one or more derived assets registered
in the engine. Importers extend the engine's file-format knowledge —
adding a new importer means "the engine now understands `.foo`
files". Importers run automatically on VFS writes that match their
claimed extensions.
## When to use one
- You're bringing a new file format into the engine and want to
derive engine-native assets from it (meshes, textures, animations,
data tables).
- You want one VFS write to fan out into multiple derived assets
(e.g. a GLB write derives mesh, texture, and animation assets).
- You want format ingestion to be idempotent + hot-reloadable —
importers re-run on source-file changes.
If you only need to consume an existing engine asset type, you don't
need an importer; just resolve it via `asset.resolve`. If you're
building an authoring tool that emits assets, that's a `.tool`, not
an importer.
## Where it lives
- Source: `/zero/source/.../<name>.importer/`
- Identity: `<name>` (the `.importer` suffix strips).
- Folder shape:
- `init.luau` (or `init.lua`) — exports `canImport` and `import`, and
`extensions`: the file extensions it claims, lower-case without the dot.
An importer that makes one asset beside its source also exports
`produces`, the type of that asset (`"texture"` makes `<stem>.texture`).
**Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- `settings.luau` — the importer's own settings schema, declared with
`Field` descriptors. Optional; an importer without one takes no settings.
- `settings.yaml` — the importer's settings values. Optional.
## Settings
An importer that takes settings declares them in its own `settings.luau` and
receives the resolved values as `ctx.settings` in `import(ctx)`.
`asset.schema(importerRef)` reports the schema, `asset.settings(importerRef)`
the values, and `asset.setSettings(importerRef, patch)` changes them. What an
importer stamps onto the assets it creates is typically one of these: the
texture, SVG and model importers each declare `textureSettings =
Field.settingsOf("@builtin::assetTypes.texture", NoSync)` — the texture type's
own fields — and pass it to `asset.create` as `importerSettings`, the importer
layer of each texture's settings. A change to an importer's settings counts as
a change to what an import is made from, so an unchanged source is imported
again after one.
## How to create one
```luau
asset.create("importer", "<name>")
-- Creates: /zero/source/<name>.importer/
-- init.luau (canImport / import stubs)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("importer", "<name>", { folder = "importers" })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.importer/` folder
indexes the importer with the importer registry.
2. **Dispatch.** When a file is written to VFS, the engine asks every
registered importer `canImport(path, bytes)` (cheap predicate).
The first importer that accepts dispatches to its `import`
function.
3. **Derivation.** `import(path, bytes)` returns a list of
`{ path, kind }` pairs naming the assets to derive. The engine
instantiates each derived asset against its registered category.
4. **Idempotency.** `import` MUST be deterministic — importing the
same source bytes twice produces identical derived assets. The
importer pipeline uses content-hashing to short-circuit re-imports
when bytes haven't changed.
5. **Hot reload.** Editing the importer reloads it; subsequent writes
use the new logic. Already-imported assets stay imported with the
old derivation until their source is imported again — writing the
source path re-dispatches the importers, and
`tools.use("importers", "run", <path>)` re-imports a target, many
targets, or a whole folder on demand.
6. **Play.** A source written while play runs lands on the play shadow
and imports there, so the source and its asset are kept or discarded
together at play-exit. A source play holds where it stands (written
before play, or by a durable write during it; `vfs.playHoldsInPlace`)
cannot be moved into a new asset while play runs, so its import is
owed: the job reads `owed` (reason `play-lock`), a notice names it,
and it imports when play ends or pauses. `tools.use("importers",
"queue")` lists owed imports and `importers.cancel` drops one.
## Re-importing over an asset an import made
An import keeps its source inside the asset it makes: `art/plate.svg` becomes
`art/plate.texture/` holding `plate.svg`. `import(ctx)` reads where to write
from `ctx.output` (`<dir>/<stem>.<produces>` on a first import) and keeps the
source with `ctx.retainSource(dest, opts?)`, which moves it to `dest` and
returns where it is now. `import` returns `{ output, source }`, `source` being
the file the asset keeps, which the asset's `import` provenance records as its
source.
- **The source written again beside the asset.** Writing `art/plate.svg` once
more re-imports it into the same `plate.texture`: the new bytes replace the
svg the texture retains (which keeps its guid), the written file leaves, and
the asset is made again from the new bytes. Its `import` provenance counts
the iteration on.
- **The same bytes written again.** When the source's checksum and the
importer's settings match the import that made the asset, no import runs:
the asset already holds those bytes, so the written copy is folded into it,
and `writeOutcome` answers `skipped` with reason `unchanged-content`, naming
the asset and the file that holds the bytes.
- **The asset itself.** `tools.use("importers", "run", <asset>)` re-imports a
produced asset in place from the source it retains (`ctx.container` names
it), so rewriting `plate.texture/plate.svg` and running it re-bakes the
texture. A run that makes nothing says why: each skipped result carries a
`reason` (`missing`, `no-source`, `no-claimant`, `unclaimed`).
## Discovery
- `asset.list("importer")` — every registered importer.
- `asset.inspect("<name>")` — claimed extensions, derivation
conventions, source, this type README.
- `ls /zero/source/<name>.importer` lists the files the folder holds.
- `tools.use("importers", "list")` — every registered importer, with
its name and identity.
- `tools.use("importers", "explain", <path>)` — which importers claim
a given source and which gate would block the import.
## Where a write's bytes end up
An importer that claims a written source may move it into the asset it
makes (the texture importer turns `shots/a.png` into `shots/a.texture/`
holding `a.png`), so the path the write named stops holding the bytes.
`require("@builtin::assetTypes.importer.shared").writeOutcome(path,
sinceFrame, timeoutSecs)` answers where they went, for a write made on
engine frame `sinceFrame` (`time.frameCount()` read before it): nil when
no importer claims them, else the import's `state`, the `importer`, the
asset made (`output`), the file the bytes are in now (`source`) and a
`note` saying all of it. Every write that fires its side effects is
offered to the importers by the same rule, whichever route made it, and
the MCP `write_file` and `upload_file` answers carry this outcome as
`import`. A quiet write (`{ quiet = true }`, and every `capture` save)
is offered to no importer, and its bytes stay where they were written;
`writeOutcome` answers `not-started` for one an importer would claim.
A write whose import the running play session holds back (a fresh
import moves its source into the asset it makes, and play holds a source
that predates it, or that a durable write made canonical, where it
stands) answers `owed` at once, with `reason` `play-lock`: the bytes stay
at the written path, and the import runs when play ends or pauses.
`writeOutcomes(paths, sinceFrame, timeoutSecs)` answers a run of writes
made together (a model, then its buffer and textures) once all of them
have landed, within one wait: a folder `write_file` or `upload_file`
lands every file without waiting on any import, then answers each this
way. `write_file { awaitImport = false }` lands one file of such a run
without waiting on its import.
## Authoring conventions
- Keep `canImport` cheap — it's called for every VFS write. Match on
extension or a quick header probe; defer real parsing to
`import`.
- Declare the extensions the importer claims as `M.extensions` and have
`canImport` claim by that list. The Inspector lists them, and
`require("@builtin::assetTypes.importer.shared").extensionsOf(importerRef)`
answers them (lower-case, without the dot; nil for an importer that
declares none).
- Name derived assets predictably (e.g.
`imported/<source-stem>/<asset-name>`). Predictable paths let
callers reference derived assets directly.
- Make `import` pure relative to its inputs. Don't read mutable
globals or side-channel state.
- Log derivations via `print` / the script log so authors can see
what got produced from each source.
## Common pitfalls
- **Expensive `canImport`.** It runs on every VFS write; an
expensive predicate slows down the entire authoring loop.
- **Non-idempotent `import`.** Re-importing produces different
output → content hashing falsely caches stale results. Use only
deterministic transforms.
- **Conflicting importers.** Two importers claiming the same
extension causes ambiguous dispatch. First-registered wins, but
this is fragile — coordinate ownership of file extensions.
- **Derived-asset suffixes.** Make sure derived paths end in the
right `.<category>` suffix; otherwise they won't register as
recognized assets.
## Related types
- `.module` — for plain ingestion helpers that don't need the
importer dispatch path.
- `.tool` — for one-off conversions an agent invokes manually.
- `.service` — if your importer needs persistent state (e.g. a
cache); the service owns it, the importer reads from it.
## In the Inspector
Imports: the extensions the importer claims (`M.extensions`), each file it imported in this session with the state its job reached, and **Find assets it produced**, which lists the assets in the world whose import provenance names this importer.
# `animation` asset type
A single animation clip, as a composite asset. The folder `<name>.animation/`
carries:
- **`data.zanim`** — the engine-native binary clip payload (bincode `AnimAsset`):
bone-named tracks, duration, channels. This is the asset's *primary*; consumers
reference the `.animation` asset's guid, never this inner file. Parallel to how
`.mesh` carries `data.zmsh`.
- **`source_rig.json`** (optional) — a reference to the `.rig` the clip was
authored on. A clip whose source rig qualifies as humanoid retargets onto any
humanoid rig, through the roles each rig's `qualify()` reads from its structure.
Clips are produced by the model importers (`model`, `model_animation`),
which decode embedded animation tracks and call
`asset.create("animation", name, { bytes })`. Bare `.anim` files are the legacy
shape; the `.animation` composite supersedes them (existing `.anim` guids are
inherited by their migrated `.animation` asset so references keep resolving).
## In the Inspector
Selecting an animation opens its **Clip** section, decoded from `data.zanim` once per payload version. It reports the clip's name, duration in seconds, channel and bone counts, and, when the clip is tagged, whether it is humanoid. It links the rig named in `source_rig.json` and lists the clip's bones. An animation with no `data.zanim` says so.
# gaussianSplat
A photographic capture of a real place, stored as a cloud of oriented 3D
Gaussians rather than as triangles. Drop a `.spz` or `.ply` into the world and
the importer turns it into one of these.
```
room_01.gaussianSplat/
room-01.spz the capture — the primary the runtime decodes
.metadata count, bounds, SH degree, axis convention
README.md
```
The capture keeps the name it arrived under, so the file you dropped in is the
file you find inside. Reach its bytes through the asset — `captureRef:getBytes()`
— rather than by spelling the filename.
## Putting a capture in the scene
A capture instantiates under the same name a bundle and an avatar do — the
entity drawing the cloud is spawned for you, in the axis convention the
container recorded:
```luau
local root = asset.resolve("room", "gaussianSplat"):instantiate()
local child = captureRef:instantiate(entity.spawn("mount")) -- as an owner's child
```
It is scene-compatible (`ref:canInstantiate()` is true), so every consumer of
the scene contract takes one: `zero entityOps fromAsset <capture>` is the same
spawn as one packaged call, and an `Asset` component pointed at a capture
spawns and tears down the cloud with its owner.
To place the cloud by hand instead, point a `GaussianSplat` component at it:
```luau
local id = entity.spawn("scan").id
entity(id).component.add("GaussianSplat", { source = "captures/room.gaussianSplat" })
```
## Reading a cloud without decoding it
`.metadata` carries what a tool needs to reason about a capture — how many
splats it holds, the world-space box it occupies, whether it stores
view-dependent colour — so framing a camera on a cloud or reporting its cost
does not pay for a decode of the whole thing.
```json
{
"count": 1920000,
"boundsMin": [-24.48, -0.92, -22.19],
"boundsMax": [27.52, 33.40, 16.81],
"shDegree": 0,
"convention": "rightDownFront",
"recordBytes": 24
}
```
`boundsMin` / `boundsMax` are the full extent, outliers included. A capture of
a whole scene usually carries a sparse halo of stray Gaussians far outside the
part anyone looks at, so framing a camera on these bounds puts it outside the
scene looking at the halo. For a scene capture, place the camera **inside** it.
## Why the capture stays the primary
The engine's packed record pool is 24 bytes per splat — larger than the `.spz`
the capture arrived in, whose quantized encoding is what makes the format worth
using. Baking the pool into the container would spend storage to save a decode
that costs a few hundred milliseconds once per load.
## Guide
`guides { path = "topics/gaussian-splats" }` covers capturing, placing, and
tuning a cloud.
## In the Inspector
Selecting a splat capture opens its **Capture** section: the facts the importer stamped in the capture's `.metadata` (splat count, SH degree, record size, format, axis convention, antialiasing and bounds), and the capture file the asset holds: its primary, the `.spz` or `.ply` under the name it was imported with. A capture folder with no capture file says so.
# data (asset type)
A `.data` instance is a configured value binding to a `dataType`
contract: `values.yaml` names the contract and supplies the field
values the contract's schema declares. Instances carry values only —
structure (field types, constraints, defaults) and behavior live on the
bound contract, never on the instance. Think of it as the
ScriptableObject *asset* to `dataType`'s ScriptableObject *class*.
## When to use one
- You have a `dataType` contract (e.g. `weapon`, `questObjective`) and
need one or more concrete, named configurations of it (`smg`,
`rifle`, `sniper`).
- You want the configuration to persist as authored content, discovered
by `asset.list("data")` / `contractType:instances()`, and validated
against the contract on every edit.
- Mutable *runtime* state (ammo remaining, cooldown timers) belongs on
a component, not here — a `.data` instance is configuration, not
simulation state.
If you don't have a contract yet, author one first
(`asset.create("dataType", ...)`).
## Where it lives
- Source: `/zero/source/.../<Name>.data/`
- Identity: `<Name>` (the `.data` suffix strips).
- Folder shape:
- `values.yaml` — `contract: <dataTypeName>` plus a `values:` map of
the contract's fields. **Required.**
- `.metadata` — description + tags for search. **Required.**
Play-mode edits fork a runtime copy (`runtime_copy: true`) — tweaking
values while gameplay runs never writes back to the source instance.
## How to create one
```luau
asset.create("data", "<Name>", { contract = "<dataTypeName>" })
-- Creates: /zero/source/<Name>.data/
-- values.yaml (contract binding + the contract's declared defaults)
-- .metadata (empty description/tags — fill both to publish)
```
`opts.contract` is required — creating without it, or naming a
contract that isn't a registered `dataType`, errors loudly and names
`contract` in the message. The seeded `values.yaml` fills every field
the contract declares a default for, so a fresh instance is immediately
valid wherever every required field has a default.
## Ref surface (`AssetRef<data>`)
- `ref:contract()` — the bound `AssetRef<dataType>`.
- `ref:satisfies(wanted)` — `(ok, reason?)`: whether this instance's
contract chain includes `wanted` (the bound contract itself, or any
contract it extends). `reason` is a string explaining a `false`
result (unrelated contract, unresolvable binding, invalid values).
- `ref:validate()` — `(ok, violations)` against the bound contract's
merged schema. `violations` is an array of `{ path, message }`.
- `ref:data(wanted?)` — the resolved, read-only value object: this
instance's `values.yaml` with the bound contract's schema defaults
filled in, `assetRef` / `dataRef` fields materialized (`assetRef` →
`AssetRef`, `dataRef` → a nested value object resolved the same way),
and the bound contract chain's `behavior.luau` methods reachable by
field-style call — `v:someMethod()` alongside `v.someField`. Method
resolution is **child-first**: the bound contract's own methods win
over an inherited one of the same name, and either loses to an
explicit instance value of that name (values always shadow methods).
A contract with no `behavior.luau` simply contributes no methods —
it still inherits its ancestors' via the chain.
Pass `wanted` to assert the instance's bound contract satisfies that
contract before resolving (same semantics as `:satisfies`) — it's an
assertion of intent, not a filter: the returned object still carries
the full bound schema and full method chain, not a view scoped to
`wanted`.
Raises when the instance's values violate its contract (same
violations `:validate()` reports), when `wanted` doesn't appear
in the bound contract's chain, and when `dataRef` fields form a
circular chain (instance A referencing B referencing A).
The object is read-only at the top level — assigning a field raises;
change configuration by editing `values.yaml` instead. Nested plain
tables (struct and array values) are private copies of the resolved
snapshot: mutating them changes only your snapshot, never the source
instance or any other caller's resolve.
Generalized iteration (`for k, v in w do`) walks the resolved value
fields (explicit values + filled defaults); methods are reachable by
name but never appear in iteration.
```luau
local w = smg:data() -- resolved value object
print(w.damage, w.fireMode) -- schema values (with defaults)
print(w:dps()) -- a behavior.luau method, if the contract ships one
local weapon = smg:data("weapon") -- asserts smg's contract chain includes "weapon"
```
## Discovery
- `asset.list("data")` — every registered instance, as `AssetRef`s.
- `<contractRef>:instances()` — every `.data` instance bound to that
contract or to a contract that extends it (see `dataType`'s ref
surface).
- `asset.inspect("<name>")` — the instance's files, bound contract,
values, and this type README.
- `ls /zero/source/<Name>.data` lists the files the folder holds.
## Authoring conventions
- Name instances for the specific thing they configure (`smg`,
`rifle`), not for the contract they bind (that's `values.yaml::contract`).
- Keep `values.yaml` limited to configuration; anything that changes
during gameplay belongs on a component instead.
- Say what this specific configuration is tuned for in the `description`
of its `.metadata` — the contract's own README documents field meaning.
## Common pitfalls
- **Missing or unknown contract at creation.** `opts.contract` must
name an existing `dataType`; both a missing `opts` and an unknown
contract name error before any file is written.
- **Values drifting from the contract.** Editing `values.yaml` re-runs
validation immediately; a violation warns rather than silently
passing through.
- **Confusing configuration with runtime state.** A `.data` instance
never mutates during play — components own live state.
## Related types
- `.dataType` — the contract this instance is bound to; owns
structure, validation, and (optional) behavior.
- `.preset` — a named set of values for one declarer's settings schema
(an assetType, an importer, a component), not a contract of its own.
## In the Inspector
Values: a link to the contract this instance is bound to, every contract field as a typed control (`data_schema`'s `toFields`), and the values that break the contract. An edit is checked against the contract and written through `dataRef:setValues`, one undoable step. `setValues` re-encodes values.yaml with `Yaml.encode`, so comments in the file are not kept; a values.yaml that carries comments is therefore shown read-only, with **Open** for the file.
`dataRef:setValues(patch)` replaces the named top-level fields and checks the result against the contract. A change is refused (one error naming each violation, nothing written) when it introduces a violation or leaves one standing at or under a value it set. A list item is known by what it holds rather than where it sits, so removing or reordering items sets none of the rest. A violation the file already held anywhere else stays listed and does not stop the change, so an instance that does not yet satisfy its contract fills in one field at a time, and a value beside a key the contract does not declare stays editable. It writes values.yaml, recorded into the open undo operation when there is one. An Inspector edit writes only the leaves it changed: every other value keeps its stored value and form, including a colour held as numbers, a map-form vector, and keys the contract does not declare.
# mesh
A mesh is renderable geometry — vertices and triangle indices, and, for a skinned
mesh, the per-vertex skinning data that binds it to a skeleton. A component that
draws geometry references a mesh, and the renderer binds the mesh's GPU resource
for that entity.
> New to how a mesh exists as an asset, as CPU-side vertex data, and as a live
> GPU resource (and how `renderer.mesh.*` moves between them)? Read
> `core/resource-model` first.
Geometry is stored in `data.zmsh`; the GPU resource is keyed by
the asset's guid.
## Create
`asset.create("mesh", name, opts)` writes the geometry and registers the mesh.
`opts` is raw geometry — flat arrays; `positions` and `indices` are required,
`normals` and `uvs` optional:
```luau
asset.create("mesh", "tri", {
positions = { 0,0,0, 1,0,0, 0,1,0 }, -- [x,y,z, ...] (required)
indices = { 0, 1, 2 }, -- [i0,i1,i2, ...] (required, 0-based)
normals = { 0,0,1, 0,0,1, 0,0,1 }, -- [x,y,z, ...] (optional)
uvs = { 0,0, 1,0, 0,1 }, -- [u,v, ...] (optional)
})
```
The full authorable geometry, all flat arrays unless noted:
| Field | Shape | Notes |
|---|---|---|
| `positions` | `[x,y,z, ...]` | required |
| `indices` | `[i0,i1,i2, ...]` | required; 0-based, counter-clockwise for the front face (see Conventions) |
| `normals` | `[x,y,z, ...]` | optional; the surface's outward direction |
| `uvs` | `[u,v, ...]` | texture UVs, optional; `(0,0)` is the image's top-left |
| `colors` | `[r,g,b,a, ...]` | optional |
| `tangents` | `[x,y,z,w, ...]` | optional (`w` = handedness) |
| `uvs1` | `[u,v, ...]` | the lightmap UV set, optional |
| `unwrapUvs` | boolean | generate `uvs1` when it is absent |
| `skinning` | `{ joints, weights }` | per-vertex skin binding (four each per vertex) |
| `skins` | array of skin tables | the skeleton (see `renderer.mesh.decode` for the shape) |
| `morphTargets` | array of `{ name?, positions, normals? }` | the shapes the mesh blends towards, each a per-vertex displacement |
`encode` / `decode` round-trip every one of these, so a **skinned** mesh can be
built in engine, not only imported. Pass `unwrapUvs = true` to generate a lightmap
UV set at creation time.
## Conventions
Geometry is read against these whether it arrived through `asset.create`,
`renderer.mesh.create`, or an importer.
| Convention | How the engine reads the geometry |
|---|---|
| Index base | `indices` count vertices from **0** — index `0` is the first `positions` triple. The Luau array carrying them is 1-based like any other, so `indices[1]` is the first triangle's first index, and vertex `v` has its x at `positions[v * 3 + 1]`. |
| Triangle winding | A triangle's **front** face is the one whose three vertices turn **counter-clockwise** as the viewer sees them. Put another way, `cross(v1 - v0, v2 - v0)` points out of the front face. |
| Back faces | A material culls its back faces by default, so a triangle turned away from the camera draws nothing where it stands and whatever is behind it shows through. |
| Normals | `normals` give the surface its outward direction and shade the face. Which side of a triangle draws comes from the index order alone, so a normal pointing away from the side the winding draws leaves that face standing and shades it as if the light were behind it. |
| UVs | `(0, 0)` samples the first texel of an image — its top-left corner — and `v` grows downward through it. |
| Axes | Model space carries the world's basis: `+X` right, `+Y` up, and `-Z` the direction an entity's `transform.forward` points. |
Winding is what the author states: the inward faces of a room and a sky shell
seen from inside are geometry meant to be wound the other way, and `asset.create`
writes the index order it is handed. Two levers turn a face around:
```luau
indices = { 0, 2, 1 } -- the same three vertices, reversed
asset.create("material", "two_sided", { -- or keep the order and draw both sides
shader = "@builtin::shaders.pbr", render = { cull = "none" },
})
```
`cull = "front"` draws the far side by itself, which is what an inverted-hull
outline is built on, and `"back"` is the default. `.shader` documents the whole
`render` block a material's `mat.yaml` carries.
A mesh states which way its own triangles face, so the question is answerable
off the geometry — every triangle whose cross product agrees with the normal it
carries is wound to draw the side that normal points at:
```luau
local cpu = meshRef:load()
local g = cpu:geometry()
local function facesOutward(t: number): boolean -- t counts triangles from 0
local i = { g.indices[t * 3 + 1], g.indices[t * 3 + 2], g.indices[t * 3 + 3] }
local function p(k: number, c: number): number return g.positions[i[k] * 3 + c] end
local ax, ay, az = p(2,1) - p(1,1), p(2,2) - p(1,2), p(2,3) - p(1,3)
local bx, by, bz = p(3,1) - p(1,1), p(3,2) - p(1,2), p(3,3) - p(1,3)
local cx, cy, cz = ay*bz - az*by, az*bx - ax*bz, ax*by - ay*bx
local n = i[1] * 3
return cx * g.normals[n+1] + cy * g.normals[n+2] + cz * g.normals[n+3] > 0
end
local inward = 0
for t = 0, #g.indices // 3 - 1 do
if not facesOutward(t) then inward += 1 end
end
cpu:unload()
```
## Built-in primitive meshes
The engine ships blockout geometry every world references by bare name
(`{ model = "cube" }`). Each one is centred on its local origin, so an entity's
`scale` reads directly as the size the mesh covers in the world:
| Mesh | Extent (x, y, z) | Local AABB |
|---|---|---|
| `cube` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` |
| `sphere` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` |
| `cylinder` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` |
| `cone` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` |
| `octahedron` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` |
| `rounded_box` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` |
| `capsule` | 0.5 x 1 x 0.5 | `-0.25, -0.5, -0.25` .. `0.25, 0.5, 0.25` |
| `torus` | 1 x 0.3 x 1 | `-0.5, -0.15, -0.5` .. `0.5, 0.15, 0.5` |
| `plane` | 1 x 0 x 1 | `-0.5, 0, -0.5` .. `0.5, 0, 0.5` |
| `ground_quad` | 1 x 0.1 x 1 | `-0.5, -0.05, -0.5` .. `0.5, 0.05, 0.5` |
| `ground_hex` | 1.732 x 0.1 x 2 | `-0.866, -0.05, -1` .. `0.866, 0.05, 1` |
| `shader_ball` | 0.933 x 1 x 0.933 | `-0.467, -0.5, -0.467` .. `0.467, 0.5, 0.467` |
`plane` is a flat quad in the XZ plane, so it has no vertical extent at all and
scaling it on Y moves nothing. `meshRef:load():getBounds()` reads the same
numbers back off any mesh, built-in or authored.
## Put a mesh on an entity
A component draws a mesh through a `resource("mesh")` field, which accepts the mesh
**by name, by ref, or as a `MeshHandle`** — the component resolves whatever you give
it. The builtin `Model` and `SkinnedModel` both expose a `model` field:
```luau
entity.find("box").component.add("Model", { model = "tri" }) -- by name
entity.find("box").component.add("Model", { model = asset.ref("tri") }) -- by ref
entity.find("box").component.add("Model", { model = meshHandle }) -- a MeshHandle (below)
```
## Runtime mesh — no asset
Build geometry straight onto the GPU and render it without creating an asset. The
`resource("mesh")` field takes the returned `MeshHandle` directly:
```luau
local h = renderer.mesh.create({ positions = {0,0,0, 1,0,0, 0,1,0}, indices = {0,1,2} })
entity.find("box").component.add("Model", { model = h })
```
Its geometry reads back off the handle. `renderer.mesh.geometry(mesh)` returns the
same flat-array `MeshGeometry` `create` takes, carrying every stream the mesh has —
so a runtime mesh can be inspected, edited, and rebuilt without ever becoming an
asset:
```luau
local geom = renderer.mesh.geometry(h) -- { positions, indices, tangents?, ... }
geom.positions[1] = 0.5
local h2 = renderer.mesh.create(geom)
```
An optional stream is present only when the mesh carries one, so `geom.tangents`
answers whether the mesh has a tangent basis and `geom.uvs1` whether it has a
second UV set.
## Read geometry — `meshRef:load()`
`:load()` decodes `data.zmsh` into the CPU store and returns a CPU handle carrying
`vertexCount` / `indexCount`:
| Method | Returns |
|---|---|
| `cpu:getVertices()` | array of `{ pos = {x,y,z}, normal = {x,y,z}, uv = {u,v} }`, one per vertex |
| `cpu:getTriangles()` | array of `{ v1, v2, v3 }`, each a full vertex (the shape above) |
| `cpu:getBounds()` | `{ min = {x,y,z}, max = {x,y,z} }` — the local-space AABB |
| `cpu:geometry()` | the complete `MeshGeometry` — flat arrays, every stream the mesh carries |
| `cpu:encode()` | the `data.zmsh` bytes |
| `cpu:unload()` | drop this guid's CPU copy |
```luau
local cpu = meshRef:load()
local v = cpu:getVertices()[1] -- { pos = {x,y,z}, normal = {x,y,z}, uv = {u,v} }
local aabb = cpu:getBounds()
cpu:unload()
```
By default the CPU copy is transient (decode → read → `unload`). Set `keepCpu` to
keep it resident — see Settings.
## Write geometry back — `meshRef.primary`
The inverse of reading: encode a `MeshGeometry` and write it to the asset's
primary content file. The assetType picks the write up and re-uploads the live
GPU mesh, so the change shows without a reload:
```luau
local geom = renderer.mesh.geometry(meshRef)
geom.tangents = computeTangents(geom) -- add a stream it did not carry
vfs.write(meshRef.primary, renderer.mesh.encode(geom), { overwrite = true })
```
`meshRef.primary` is the asset's `data.zmsh` path. This is the route for a
stream with no setting of its own; `keepCpu` + `meshRef:setVertices` moves
positions in place, and `lightmapUvs` regenerates the second UV set (both
below).
## GPU handle — `meshRef:handle()`
`:handle()` uploads the geometry (Disk → CPU → GPU) and returns a `MeshHandle`,
cached on the asset so every consumer shares ONE GPU entry. A component does this
for you when you pass it the mesh; call it directly only for the runtime/low-level
path.
## Settings — `meshRef:settings()` / `meshRef:setSettings(patch)`
A mesh's settings are declared in `settings.luau` and live in `settings.yaml`
(or, for content published before it existed, a legacy `.metadata` block).
`:settings()` returns them with every declared default filled in.
`:setSettings(patch)` writes any subset — sibling settings are preserved, and
a patch that fails the schema is refused, naming the field and why.
| Setting | Type | Default | Meaning |
|---|---|---|---|
| `keepCpu` | boolean | `false` | Keep the CPU geometry copy resident — for an in-use mesh — so geometry can be read repeatedly without re-loading. |
| `lightmapUvs` | string | `"keep"` | The mesh's second (lightmap) UV set. `"keep"` leaves the stored geometry's set as-is; `"generate"` unwraps a fresh non-overlapping set; `"none"` strips it. See below. |
| `clusterLod` | boolean | `true` | How deep the cluster set is built. Every static mesh draws through clusters, from the frame it materialises (its `lod0` set) until its bake lands. `true` (default) builds the LOD hierarchy; `false` builds one level, drawn at full detail. |
```luau
local s = meshRef:settings() -- { keepCpu = false }
meshRef:setSettings({ keepCpu = true })
```
`keepCpu` is an active lifecycle control, and only ever holds geometry for a mesh
that is **in use** (GPU-resident):
- Setting it **on** while the mesh is in use loads the CPU copy immediately.
- Setting it **on** for a mesh that is **not** in use loads nothing — the copy is
retained the next time the mesh is materialised, so an unused mesh is never
pinned in memory.
- Setting it **off** drops a resident CPU copy (the renderer keeps drawing from
the GPU).
`clusterLod` is the same kind of lifecycle control, for the depth of the
cluster set rather than the CPU copy:
- Setting it **off** on a mesh in use rebakes it as one level of clusters
(`single`), drawn at full detail.
- Setting it **on** on a mesh in use rebakes the LOD hierarchy (`dag`).
- A mesh that is not in use bakes at the depth the setting asks for when it
next materialises.
Acting on either setting for a mesh in use can read the mesh's stored geometry,
and where the geometry is fetched on first read that read spans frames.
`meshRef:settingsPending()` answers whether one is still in flight; once it
answers `false`, every settings change made so far has reached the mesh.
### Second UV set (`lightmapUvs`)
A mesh can carry a **second**, independent UV set (`uv1`) alongside its texture UVs
(`uv`) — a distinct per-vertex channel, non-overlapping where the texture UVs tile
and reuse charts. `lightmapUvs` controls whether the stored geometry keeps one,
generates one, or drops it:
| Value | Effect |
|---|---|
| `"keep"` | Leave the stored geometry's `uv1` as-is (the default). |
| `"generate"` | Unwrap a fresh non-overlapping `uv1` (near-planar charts packed into `[0,1]` with gutters). |
| `"none"` | Strip the `uv1` set. |
```luau
meshRef:setSettings({ lightmapUvs = "generate" })
```
Changing the setting reprocesses the asset's geometry in **edit** mode; a change in
play mode never rewrites the source. The reprocess round-trips the geometry through
the codec, so positions, normals, tangents, skinning, and the skeleton are preserved
— only the `uv1` set changes. A runtime mesh carries `uv1` the same way: pass `uvs1`
(or `unwrapUvs = true`) to `renderer.mesh.create`.
## Read vertices — `meshRef:getVertices()`
With `keepCpu` on for an in-use mesh, read its vertices straight from the resident
CPU copy:
```luau
meshRef:setSettings({ keepCpu = true }) -- on an in-use mesh
local verts = meshRef:getVertices() -- { { pos = {x,y,z}, normal = {x,y,z}, uv = {u,v} }, ... }
```
If the CPU copy isn't resident — `keepCpu` is off, or the mesh isn't in use — it
errors loudly, naming the reason and the remedy, rather than silently loading a
throwaway copy:
```
mesh:getVertices: cannot read vertices — keepCpu is off, so no CPU copy is kept.
Turn on CPU retention for an in-use mesh first: meshRef:setSettings({ keepCpu = true }).
```
## Morph targets — `meshRef:morphTargets()`
A mesh can carry morph targets: shapes it blends towards, each a per-vertex
displacement from the base geometry. Every target carries the name it was
authored under, and an imported model keeps the one its source file gave its
blend shapes, so content addresses a shape as the thing it means rather than as
the ordinal it happened to import at.
```luau
for i, name in meshRef:morphTargets() do print(i, name) end -- 1 Eyes_Blink
```
An entity blends them with `ecs.MorphWeights`, weight `i` driving target `i`.
`renderer.mesh.morphWeights(mesh, { Eyes_Blink = 1 })` builds that ordered array
from weights named by shape — shapes left out sit at 0, and an unknown name
errors listing the ones the mesh carries.
## Discovery
| Call | Shows |
|---|---|
| `asset.list("mesh")` | every registered mesh |
| `asset.inspect("<name>")` | a text report about the mesh (metadata, source, status) |
| `meshRef:settings()` | the resolved settings |
| `meshRef:settingsPending()` | whether a settings change is still reading the stored geometry |
| `meshRef:morphTargets()` | the shapes it blends towards, named, in target order |
For the on-disk shape of a mesh asset, run `asset.inspect("<name>")` or read the
type's `type.yaml` — those are the live source of truth.
## Related
- `renderer.mesh.*` — the GPU/CPU resource layer (`create` a runtime GPU mesh,
`encode`/`decode` the `ZMSH` payload, `readback` GPU → CPU). `:load`/`:handle`
wrap it; see `man renderer`.
- `.material` + `.shader` — what shades the geometry.
- `.bundle` — container assets that carry `.mesh` interiors.
## In the Inspector
Selecting a mesh opens its **Geometry** section, after the asset's identity and before its Settings. It reports what `data.zmsh` holds, decoded once per payload version: vertices, triangles, the bounds and their size, the vertex streams beyond positions (normals, uvs, uvs1, colors, tangents, skinning), and, when the mesh has them, its skin joints and morph targets. While the renderer holds the mesh's cluster hierarchy, the section also reports its cluster and level counts. A payload is one index stream, so the section names no submeshes. A mesh folder with no `data.zmsh` says so.
# edui
The editor UI framework, on the CSS-parity `ui.*` surface. An editor-only
toolkit: panels author closures instead of callback ids, a dock shell over
`ui.*` native docking, and typed editor-chrome primitives. Gameplay and normal
world UI author raw `ui.*` trees and need none of this.
**`edui.guide` beside this file is how to use it** — creating a panel, the spec
it returns, how a panel is drawn and redrawn, the whole widget vocabulary, and
how a panel reaches the selection and the dock.
## What installs
- **`framework`** — everything under one table. From outside the package,
`require("@builtin::~edui.framework")`; inside it, `require("~.framework")`.
It carries `app`, `widgets`, `shell`, `topbar`, `query`, `fileDialog`,
`worldDialog`, `stats`, and the chrome primitives flat (`panel`, `tree`,
`field`, `section`, `text`, `button`, `menu`, …).
- **`app`** — maps a panel's closures to `ui.*` callback ids, dispatches to
them, and coalesces redraws.
- **`widgets`** — the primitives, plus the typed inspector layer
(`widgets.tree`, `widgets.fields`, `widgets.controls`).
- **`inspector`** — the Inspector as an ordered list of sections: the generic
asset sections, the Settings section and its actions, and the merge with
the sections a type's `inspector.luau` declares (`inspector.assetSections`,
`inspector.settingsSection`), and the building blocks those sections
compose (`inspector.parts`, reached as `ctx.parts`).
- **`shell`** — the dock: one `ui.*` `dockArea` holding a `dockPanel` per
registered panel, and the panel registry behind it.
## Referencing
- Inside this package, modules reference siblings with `~.` — e.g.
`require("~.app")`, `require("~.widgets.fields")`.
- Editor content built on the framework references it by package identity —
`require("~edui.framework")`, `require("~edui.shell")`.
# avatar
A playable character, composed from three **independent** parts:
- **body** — a `.bundle`: a skinned `.mesh` + bone entities (a character imported
from a GLB/FBX). The look.
- **controller** — the movement system. Default: the standard humanoid kit
(`CharacterController` + `MovementState` + `Humanoid`).
- **animation** — the system that animates the body. Default: the shared
`Locomotion` blend space (reads the controller's velocity, plays retargeted
clips). Or `ClipPlayer`. Or your own component.
Movement and animation are **not** tied together — attaching the controller never
pulls in `Locomotion`, and choosing your own `animation` keeps the standard
controller. Authoring your own locomotion is a one-field swap (`animation = ...`).
Because the standard clip set retargets onto **any** humanoid rig, the default
locomotion drives any humanoid body with no per-body setup and no editing of any
built-in content.
## Make an imported character playable
```luau
-- After importing a rigged humanoid GLB, the importer leaves a `.bundle`
-- (skinned mesh + bones). Survey for it, then wrap it in an avatar:
local body = asset.resolve("my_character", "bundle")
local hero = asset.create("avatar", "my_hero", { body = body })
```
To make `hero` the body every connecting player spawns with, point the scene's
`PlayerPrototype.body` at a body entity whose `Asset` source is `hero` (authored
in the scene tree — see `man scene`). To drive the **local** player with it right
now, instantiate it and bind the entity:
```luau
local root = hero:instantiate() -- spawns the body + movement kit
layers.active.players.localPlayer.avatar = root -- bind the live body
```
An avatar is **not** humanoid-only. The body can be anything — a humanoid, a
vehicle, an unrigged plane with a custom controller and shader. The defaults
adapt to the body: a **humanoid** body defaults to the shared humanoid Locomotion
(the `synty` clip preset); a **non-humanoid / unrigged** body gets **no
auto-animation** (you supply your own `controller` and `animation`). This is the
non-humanoid detection — an arbitrary animated model is never auto-driven by
humanoid locomotion — and it never blocks creating the avatar.
```luau
-- Non-humanoid avatar (e.g. a custom-controlled body), fully generic:
asset.create("avatar", "ship", { body = shipBundle, controller = { system = "ShipController" }, animation = false })
```
## Options
`asset.create("avatar", name, opts)`:
| opt | meaning |
|-----|---------|
| `body` (required) | the body `.bundle` ref |
| `controller` | movement: `true`/nil = standard kit, `false` = none, or a component name / `{ system, data }` |
| `animation` | a component name or `{ system, ... }` — **author your own locomotion here**; defaults to Locomotion |
| `locomotion` | clip preset for the default Locomotion (default `"synty"`) |
| `clip` | a single `.animation` ref — selects a one-clip `ClipPlayer` |
| `looping` / `speed` / `sourceRig` | `ClipPlayer` tuning (with `clip`) |
Author your own locomotion (keeps the standard movement):
```luau
asset.create("avatar", "my_hero", { body = body, animation = { system = "MyLocomotion" } })
```
`avatar.json`:
```json
{
"body": { "__ref": "<bundle guid>" },
"controller": true,
"animation": { "system": "Locomotion", "preset": "synty" }
}
```
The body's facing is read from its rig (the importer records a `forward` for each
body — `{0,0,1}` for a +Z Synty/FBX body, `{0,0,-1}` for a -Z glTF body), so
Locomotion turns the body to its movement direction regardless of how its source
authored it. No per-avatar facing knob.
## Use
```luau
local root = avatarRef:instantiate() -- spawn body + movement kit
avatarRef:setCharacter(root, asset.resolve("knight", "bundle")) -- swap the body, keep the behaviour
```
`:instantiate()` spawns the body and attaches the movement system bound to it.
`:setCharacter(root, body)` despawns the current body and spawns a new one in its
place; the Locomotion kit on the avatar root re-resolves the new body's rig, so
the look swaps while the behaviour is kept.
## In the Inspector
Selecting an avatar opens its **Avatar** section, read from `avatar.json`: its label when it has one, how it moves (`controller`: the standard mover, none, or the system it names), what animates it, and whether it is humanoid. It links the body the avatar wears, or says the avatar spawns no visible body, and offers to open `avatar.json` in the Code panel.
# avatarType
An avatar type describes a kind of body: a humanoid, a quadruped, a vehicle. It names the
roles and chains a rig of that kind maps onto, and it finds them in a skeleton. The builtin
library ships one, `@builtin::avatarTypes.humanoid`. A world adds its own the same way, as a
`<name>.avatarType/` folder.
A rig can be mapped for more than one type; its author's corrections are stored on the rig,
keyed by the type's guid, so mapping a skeleton for one type never overwrites another.
## The module
`init.luau` returns:
| Field | What it is |
|---|---|
| `name` | The type's name, e.g. `"humanoid"`. |
| `vocabulary.roles` | Every role the type can assign (`hips`, `lefthand`, ...). |
| `vocabulary.chains` | Every chain the type can assign (`spine`, `leftArm`, ...). |
| `vocabulary.required` | The roles and chains a rig must have for the type to claim it. |
| `qualify(structure)` | Maps a skeleton. `structure` comes from `modules.rigStructure`. |
`qualify` returns:
```luau
{
qualifies = true, -- the rig is this kind of body
confidence = 0.94, -- 0..1
reason = nil, -- one line, when qualifies is false
mapping = {
roles = { hips = "Hips", ... }, -- role -> bone name
chains = { leftArm = { "Clavicle_L", ... } },
secondary = { { root = "Hair_01", tip = nil, class = "hair", bones = { ... } } },
},
report = {
chains = { leftArm = { confidence = 0.97, bones = { ... } } },
missing = { "rightArm" },
ambiguities = { { role = "hips", candidates = { { bone = "Hips", score = 0.9 } } } },
contradictions = { "..." },
stale = { { role = "leftforearm", bone = "Elbow_L" } },
verdict = "humanoid: every required chain found",
},
}
```
## Using one
```luau
local humanoid = asset.resolve("@builtin::avatarTypes.humanoid", "avatarType")
local rig = asset.resolve("PolygonSyntyCharacter", "rig")
local q = rig:qualify(humanoid) -- the rig's effective mapping for this type
print(q.qualifies, q.mapping.roles.hips)
```
# workflow
A job whose shape is a program.
Some jobs are one thing an agent does. Others have a shape: a decision, then
several pieces built at once because they do not touch each other, then somebody
looking at the result and saying whether it holds. Written as instructions, that
shape becomes a list an agent has to carry in its head, and by the last step the
first is gone. Written as a workflow, the shape is code — it runs in the engine,
it decides its own phases and branches and fan-out, and nothing that answers it
is told what comes next.
## The shape on disk
<name>.workflow/
workflow.js the program — the primary file, and where all the decisions live
workflow.yaml what it is, when to reach for it, the phases it moves through
README.md
.metadata
## The program
`workflow.js` is JavaScript, run in the engine. Six things are given to it:
phase(name) name the stage the run is in
log(text) say something as it goes
agent(prompt, opts) ask for one agent's whole job; parks until answered
parallel(thunks) several asks that do not depend on each other
pipeline(items, ...) each item through every stage, independently
args whatever the run was started with
`agent()` is the only call that leaves the engine. It parks the run, puts the
request where whoever holds credentials can see it, and resumes with the answer.
Everything else — the loop that built those prompts, the branch on what came
back, the decision to fan out — is the program's, and stays in the engine.
`opts.schema` states the shape the answer must have:
'string' 'number' 'boolean' 'any' a value of that type
'string[]' or [ shape ] a list, every item of that shape
{ field: shape, 'note?': shape } a table with those fields; a name
ending in ? may be left out
`workflow.next` hands the schema over with the prompt. `workflow.answer`
refuses a value of any other shape, naming the field and the shape expected
there, and the request stays open to be answered again. `workflow.correct`
replaces an answer the program has not read yet, held to the same schema; the
program reads an answer within a moment of it arriving, and a correction after
that is refused as already consumed. Every list the schema
names reaches the program as an array, an empty one included. A schema written
outside this notation fails the run at the `agent()` call that carries it.
## Running one
local run = asset.resolve("<name>", "workflow"):start({ ... })
or through the `workflow` toolbox, which is what an agent uses:
`workflow.start`, then `workflow.next` / `workflow.answer` until it is finished.
A run that is waiting announces itself on tool responses until it is answered.
From the engine shell, the same run is driven with `zero workflow`:
zero workflow start --name [name]
zero workflow status
zero workflow next --runner <who you are> (claim the request it is waiting on)
zero workflow renew --request <id> (keep the claim while its work goes on)
zero workflow answer --request <id> --value <result>
zero workflow fail --request <id> --reason "<why>"
`next` names who is taking the request, and `answer`, `renew` and `fail` name
the request they act on by the id `next` returned.
## What a run is
A run lives in the engine, not in a session. Whoever started it can close the
tab, lose the connection or hand over to somebody else; the run stays parked
exactly where it was, and the next agent to ask gets the request that was
waiting. Each request is one subagent's whole job — the point is that no single
context has to hold the entire run.
## In the Inspector
Workflow: what the workflow is for and when to reach for it, the args it takes, its phases, its step budget when it declares one, and the size of workflow.js, with **Open** for workflow.yaml and workflow.js. Nothing here runs it.
# renderFeature
A **render feature** inserts custom GPU passes into the frame pipeline. The engine
provides one generic capability — a per-frame render-pass queue and a set of
pipeline-phase insertion points — and a feature is the authored Luau that decides
what passes to enqueue, and where, every frame.
## Authoring contract
A `.renderFeature` folder holds an `init.luau` that returns a feature module:
```luau
return {
setup = function(ctx) -- optional; runs once when the feature goes live
-- A "fragment" pass's `shader` names a POST EFFECT, not a `.shader`
-- guid directly — postprocess.add compiles the shader asset under
-- that name once, here. Enqueueing a name never passed to
-- postprocess.add runs the pass as a no-op every frame (the log
-- reads "effect '<name>' not compiled — pass skipped").
postprocess.add("my_effect", asset.resolve("my.shader.guid", "shader"), { enabled = false })
end,
render = function(ctx) -- required; runs every frame
-- enqueue one or more passes. The spec shape depends on `kind` (see
-- "Pass kinds" below): this is a "fragment" pass (full-screen shader over
-- input textures); a mesh effect (outline, x-ray) is a "geometry" pass
-- with `material` + `select` (see "Geometry passes").
ctx.enqueue {
phase = "afterTransparent",
shader = "my_effect",
inputs = { src = "@scene.color" },
output = myRenderTargetGuid,
}
end,
teardown = function(ctx) end, -- optional; runs once when the feature is destroyed
}
```
Optional `materials/` and `shaders/` subfolders hold shader source the feature
constructs GPU programs from. A feature constructs its GPU programs (it does not
reference `.material` surface assets).
## `ctx`
Built fresh each frame and passed to `setup` / `render` / `teardown`:
| Field | Meaning |
|-------|---------|
| `ctx.enqueue(spec)` | Queue one render pass for the current frame. |
| `ctx.viewport` | `{ w, h }` — the **main viewport's** size in pixels. |
| `ctx.time` | Seconds since boot. |
| `ctx.frame` | Monotonic frame index. |
| `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. |
| `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". |
## Settings
A feature declares the knobs it takes as `settings`, each a Field descriptor
with a default, the way a component declares its public fields:
```luau
local Fields = require("@builtin::modules.field")
local Field, NoSync = Fields.Field, Fields.NoSync
return {
settings = {
intensity = Field.number(1.0, NoSync, "How much of the effect reaches the image."),
quality = Field.enum({ "low", "high" }, "high", NoSync, "How many samples the pass spends."),
},
render = function(ctx)
local s = ctx.settings -- { intensity = 1.0, quality = "high" }, or what a caller set
...
end,
}
```
The engine holds one settings table per live feature — every declared default,
overridden by what it was handed — and passes it as `ctx.settings` on every
`setup` / `render` / `teardown`. A feature reads its knobs there and nowhere
else, so any caller tunes any feature by name:
```luau
local h = renderer.feature.create(ref, { settings = { intensity = 0.5 } })
renderer.feature.configure(h, { quality = "low" }) -- lays over the rest
renderer.feature.settings(h) -- { intensity = 0.5, quality = "low" }
renderer.feature.find(ref) -- the live handle, or nil
renderer.feature.schema(ref) -- the declared knobs, unrun
```
A knob the feature does not declare, or a value of the wrong shape, is refused
by name. A scene authors its features on one `RenderFeatures` entity — a list
of features, each with its settings — which adopts a feature already live
rather than stacking a second, and takes every one down on disable and destroy.
`render` runs **once per frame**; the passes it enqueues run **once per render
target** drawn that frame — the live viewport, every offscreen capture, every
RTT camera — each at its own resolution. So `ctx.viewport` is the main
viewport's size, not the size of the target a pass ends up drawing into. Size a
full-screen scratch RT with `screen = true` and let the engine track the drawn
target (see "Screen-sized targets") rather than deriving it from `ctx.viewport`.
## Screen-sized targets
`renderer.texture.create { screen = true }` marks a feature RT as full-screen:
before each render target's feature passes, the engine resizes it to that
target's resolution. Create it once — the engine owns its size from then on:
```luau
myRt = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
screen = true, format = "rgba16f", name = "my_effect",
}
```
A target that holds a picture of the scene is `rgba16f`, which is what the scene
target itself carries: linear light with headroom above the display's white and
no 256-step floor under a dark gradient. Omitting `format` on a screen-sized
target asks for the same thing. `format = "rgba8"` is for a mask, a weight or an
occlusion term, where 0..1 is the whole range — hand one of those back over
`@scene.color` and the frame loses every highlight and bands every gradient, and
the engine says so in the log.
`screenScale` (default `1.0`) takes a fraction of the drawn target's resolution,
for a scratch that runs below composite resolution (a half-res blur passes `0.5`).
A screen-sized RT is what makes a full-screen effect composite correctly at any
resolution. Deriving the size from `ctx.viewport` instead pins the RT to the main
viewport, and every differently-sized render target then composites a mismatched
scratch — the scene scaled into a corner with the rest black.
`screenSpace` names WHICH image a screen-sized RT follows:
| value | what it tracks |
|---|---|
| `"scene"` (default) | the scene render target, at whatever resolution the render scale asked for. Resized before EVERY render target's feature phases — the main frame and each offscreen one — and cleared to transparent before an offscreen render, so one sink never reads what another left behind |
| `"composite"` | the image the post-scene phases draw into. Resized on the presented frame only, and never cleared for an offscreen render, since none of those phases run there |
The two carry the same size until the render scale drops below 1. From there,
while the renderer presents the viewport itself, the scene reaches the display's
resolution through an upscale that runs before `afterScenePost` — so a
composite-space RT is the display's size while a scene-space one is the smaller
rasterized frame. Under a UI viewport panel the panel draws the scene target at
its own rect, nothing upscales beforehand, and both spaces carry the scene's
size.
A scene-space target is scratch: whatever a pass does not rewrite this render is
transparent black. A composite-space target survives an offscreen render
untouched, but it follows the presented frame alone.
## History targets
An accumulation across frames (temporal antialiasing, a temporal denoiser, any
pass that reads what it wrote last time) lives in a history target:
```luau
history = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
history = true, format = "rgba16f", name = "my_accum",
}
-- in render(ctx):
ctx.enqueue {
kind = "compute", program = myResolve,
inputs = { scene_color = "@scene.color", accum_previous = history.previous.guid },
buffers = { accum_state = history.state },
storage = { accum_out = history.guid },
phase = "afterLighting",
}
```
The passes a feature enqueues run once for every view the frame draws (the
viewport, each render-to-texture camera, each capture), so an accumulation has
to be one per view. A history target keeps one pair of images per view, sized to
that view: for the length of a view's render `history.guid` names the image the
render writes and `history.previous.guid` the image the same view's previous
render wrote. Another view never resizes, clears or overwrites them, and a
view's images are freed when it stops drawing. It follows `screenSpace` and
`screenScale` like any screen-sized target; a composite-space one is kept for
the viewport, the one view that draws the post-scene phases.
Before each render of a view the engine writes `history.state`, one
`vec4<f32>` a pass binds through `buffers`:
| field | holds |
|---|---|
| `x` | 1 when `previous` holds this view's previous image; 0 on the view's first render, its first after a camera cut or a change of size, or after a render of the view that ran without the target, and `previous` then reads transparent black |
| `y` | how many renders in a row have carried the history |
| `zw` | this render's sub-pixel projection offset, in pixels (`renderer.setProjectionJitter`) |
`renderer.setProjectionJitter` is the matching per-view sample sequence: every
view walks it by its own count of renders, so the sequence a temporal pass
expects is the one each view's renders sampled.
## Pass phases
`enqueue` runs a pass at a named pipeline boundary — a real seam between the
scene's discrete passes — ordered within a phase by `order`. Each phase is the
point where the scene colour holds a specific, nameable state:
| Phase | Scene colour there |
|-------|--------------------|
| `afterDepthPrepass` | the visibility raster written: `@scene.depth` holds this frame's complete opaque depth, and `@scene.motion` its opaque motion, before anything shades. Scene colour is not yet drawn; `@scene.colorHistory` holds the previous frame's lit colour, and the deferred g-buffer the previous frame's surfaces (`readsPrevious`) |
| `afterShadows` | shadow maps populated; scene colour/depth not yet drawn |
| `afterSky` | sky only; depth empty |
| `afterOpaque` | opaque drawn, before transparents. `@scene.depth` (and the deferred G-buffer) are populated. Forward: lit opaque. Deferred: opaque is in the G-buffer, so the colour is still sky only until the composite (use `afterOpaqueLit`) |
| `afterOpaqueLit` | the lit opaque scene, still before transparents, on **both** paths — the forward opaque draw, or the deferred lighting composite. The background a refractive or transmissive surface samples: the one phase whose colour holds what is behind such a surface without holding the surface itself |
| `afterTransparent` | transparents drawn, before the OIT composite |
| `afterLighting` | deferred-lighting + OIT composite done — fully lit, final geometry on **both** paths |
| `afterScenePost` | scene-layer post (DoF/MB/…) done, before UI |
| `afterUI` | scene + UI composited |
| `afterPost` | all-layer post done — the final image, before present |
The last three are the post-scene phases, and they work on the COMPOSITED image:
`@scene.color` there is the target the UI lands on, not the scene render target.
`@scene.depth` and `@scene.motion` still bind — they are the scene's own buffers
for the frame just drawn, which is what lets a pass at these phases reproject the
composite it is handed — but they keep the SCENE's resolution. Whenever the
render scale is below 1 on the presented frame, that is smaller than
`@scene.color`, so a pass here maps between the two by uv rather than by texel
index, and takes its own output size from the target it writes.
The `@scene.*` inputs (`@scene.color`, `@scene.depth`, …) bind the live frame
buffers; the deferred g-buffer channels (`@scene.normal`, `@scene.shaded`, …)
resolve only on the deferred path. Before the pass that shades has drawn — at
`afterDepthPrepass` — a g-buffer channel holds the previous frame's surfaces,
and a pass reading it there names the slot in `readsPrevious`
(`readsPrevious = { "scene_normal" }`); one that does not is held back rather
than handed a stale normal. `@scene.colorHistory` is the lit colour the target's
previous render ended with, kept by the engine per render target and never
cleared by a frame: what a pass tracing at `afterDepthPrepass`, against this
frame's depth, takes its light from — reprojected through the previous
view-projection `@frame.camera` carries. A capture drawn once, or a camera drawn
again after a pause, is drawn lit first when a pass reads the history, so its
first frame holds one.
Every `@scene.*` channel, what it holds, its format, the phase it is first
valid from, and the earlier spellings still bound to it:
| Name | Holds | Format | Valid from | Aliases |
|---|---|---|---|---|
| `@scene.color` | the scene's lit colour; the display composite at a post-scene phase | the scene target's format at a scene phase, the display composite's at a post one | every phase | — |
| `@scene.depth` | opaque depth, reversed (1.0 near, 0.0 far/empty sky) | `Depth32Float` — binds through a `texture_depth` compute slot, not `texture2d` | `afterDepthPrepass` on | — |
| `@scene.motion` | screen-space NDC velocity since the previous frame | `Rg16Float` | `afterOpaque` on | — |
| `@scene.normal` | world-space normal + the per-pixel surface-flag field | `Rgb10a2Unorm` | deferred path, `afterOpaque` on (previous frame's before — declare `readsPrevious`) | — |
| `@scene.shaded` | what a surface SENT — its shaded colour, linear and scene-referred | `Rgba16Float` | deferred path, `afterOpaque` on (previous frame's before) | `@scene.albedo` |
| `@scene.material` | what a surface IS — base colour (RGB565) + metallic + perceptual roughness | `Rgba8Uint` | deferred path, `afterOpaque` on (previous frame's before) | `@scene.mr` |
| `@scene.emissive` | radiance a pass stamped on the surface, added at the composite | `Rgba16Float` | deferred path, `afterOpaque` on (previous frame's before) | — |
| `@scene.ao` | scene occlusion a feature wrote, read back by shading | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.reflection` | traced reflection radiance (`.rgb`) + confidence (`.a`) | `Rgba16Float` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.colorHistory` | the lit colour the target's previous render ended with | `Rgba16Float` | every phase | — |
| `@scene.lights` | the per-frame punctual-light storage buffer: twelve vec4s per light, the light then its punctual shadow record | storage buffer | every phase | — |
| `@scene.environment` | the reflection-probe cube array | texture cube array | scene phases only | — |
| `@scene.environmentSampler` | the filtering sampler for `@scene.environment` | sampler | scene phases only | — |
| `@scene.reflectionProbes` | the environment buffer: the probe blend data naming which probe reaches a point, then the irradiance light-probe volumes | storage buffer | scene phases only | — |
`docs/topics/rendering.guide/guide.md` and `docs/topics/raytracing.guide/guide.md`
both point here rather than repeating this table.
**Two g-buffer channels describe the surface, and they answer different
questions.** `@scene.shaded` is what a surface SENT — the colour the geometry
pass shaded it to, linear and scene-referred, so a surface lit above the
display's peak reads above 1 there. `@scene.material` is what the surface IS:
the base colour it reflects, its metallic and its perceptual roughness, each in
[0, 1] and each independent of how brightly the surface happens to be lit. A
pass that multiplies incoming light by a reflectance — a bounce multiplier, a
Fresnel tint, an ambient floor — reads `@scene.material`; a pass that filters
the picture reads `@scene.shaded`.
`@scene.material` is an `Rgba8Uint` channel packing all three into 32 bits, so
its slot declares `sample: uint` and the module unpacks it:
```yaml
# bindings.yaml
- { name: scene_material, kind: texture2d, sample: uint }
```
```wgsl
#include "@builtin::shaderModules.gbuffer_material"
let m = zero_gbuffer_material(scene_material, coord);
let bounce = incoming * m.base_color;
```
The earlier spellings still bind: `@scene.albedo` resolves to `@scene.shaded`
(the SHADED lit colour) and `@scene.mr` resolves to `@scene.material` (the
material channel), so a feature written against either keeps resolving. The
engine logs the substitution once per spelling, naming the canonical one to
write going forward.
`@scene.motion` carries screen-space velocity: the NDC displacement each pixel's
surface underwent since the previous frame, so a still surface under a still
camera reads `(0, 0)`. Opaque geometry contributes it on both render paths:
the visibility raster writes it for every surface it records, and an opaque
surface whose depth state the raster cannot express writes its own where it
draws. A moving entity, a moving camera and an animated pose all reach it in
the viewport; transparents, particles and sky carry none. A surface a
material's `vertex()` hook displaces carries the displacement's own velocity. A render target's own camera and a
capture keep no view history, so velocity there is the entity's motion with no
camera term.
`@frame.camera` is a reserved **buffer** input carrying the camera CURRENTLY
being drawn: 10×`vec4<f32>` = the inverse view-projection (columns `[0..4)`,
column-major) + camera world position (`[4].xyz`) + the previous render's
view-projection (columns `[5..9)`), which projects a point into the picture
that render left. A compute pass declares a
`buffer` binding and binds it via `inputs = { name = "@frame.camera" }`, then
reconstructs a pixel's world position from `@scene.depth`:
```wgsl
let inv_vp = mat4x4<f32>(cam[0], cam[1], cam[2], cam[3]);
// ndc.z is the `@scene.depth` sample itself. Scene depth is reversed — 1.0 is
// the near plane, 0.0 the far plane and empty sky — and this matrix inverts
// that same range, so a sample goes in unmodified.
let wh = inv_vp * vec4<f32>(ndc, 1.0);
let world_pos = wh.xyz / wh.w;
```
Like `@scene.*`, the engine resolves it **per render target** — so the same pass
reconstructs against the live viewport's camera on screen and against an
offscreen capture's / RTT camera off screen. (Pack a camera matrix into your own
buffer instead and the offscreen render reconstructs against the wrong camera.)
> Render-feature passes run in the main viewport render **and** in offscreen
> captures / render-to-texture, each against its own camera. The `capture` tool's
> `source = "position"` / `"entity"` therefore run the pass queue too; using
> `@frame.camera` is what keeps those captures matching the live viewport.
### The environment
A compute pass reads the scene's captured surroundings — the reflection-probe
cube array, its sampler and the environment buffer (the probe blend data, then
the irradiance light-probe volumes) — through three reserved inputs, bound to
bindings of the shapes group(0) binds them in:
```yaml
bindings:
- { name: environment_map, kind: textureCubeArray }
- { name: environment_sampler, kind: sampler }
- { name: zero_environment, kind: buffer, access: read, element: ZeroEnvironment, array: false }
```
```luau
inputs = {
environment_map = "@scene.environment",
environment_sampler = "@scene.environmentSampler",
zero_environment = "@scene.reflectionProbes",
}
```
Named like that, `#include "zero::environment"` in the shader resolves the
environment at a world point along a direction — `zpbr_sample_environment(world_pos,
dir, lod)`, the probes whose radius reaches the point blended by rank and
proximity, each through its proxy volume, and the sky under them — exactly as a
material's environment term does, so a reflection a pass draws and one a
material draws agree about the room they are in. The three bind at the scene
phases; a post or UI phase carries none. A `textureCubeArray` binding takes
`@scene.environment` alone, and a fragment pass has no slot of that shape.
## Pass kinds
`enqueue` runs one of three kinds (the `kind` field; default `"fragment"`):
- **`"fragment"`** — a full-screen shader over input textures. The program is a
GPU **material** (or `shader`) the feature constructed; `inputs` bind live
textures (`@scene.*` or RT guids), `output` is the target RT (omit = the
phase's default scene target). Post-process, blur, edge effects.
**Writing named G-buffer channels (`outputs`).** Instead of the single `output`
RT, a fragment pass may declare an `outputs` array — one or more targets, each a
named engine channel (`@scene.shaded` / `@scene.normal` / `@scene.emissive` /
`@scene.color`) or an RT guid — each with its own blend mode:
```luau
ctx.enqueue {
kind = "fragment",
shader = myShaderKey,
outputs = {
{ target = "@scene.shaded", blend = "under" }, -- premultiplied dst-over-src
{ target = "@scene.emissive", blend = "additive" }, -- one fullscreen pass, two targets (MRT)
},
phase = "afterOpaque", -- deferred: G-buffer filled, before the lighting composite
}
```
Blend modes: `"replace"` (overwrite), `"alpha"` (source-over), `"additive"`
(sum), `"under"` (premultiplied dst-over-src — accumulates coverage-weighted
contributions). A `@scene.*` channel resolves only where it exists (the deferred
G-buffer at a pre-composite phase); a pass whose targets are all unavailable at
its phase is skipped (logged). `output` + `blend = true` remains the shorthand
for a single alpha-blended target. The shader's returned colour is written to
every target in the set.
A fragment shader returns `vec4<f32>`, so the channels it can target are the
float ones. `@scene.material` (and its earlier spelling `@scene.mr`) is
`Rgba8Uint`, which binds as `uint` — naming it as an output is refused by
name, with the channel's format and class in the log, and the rest of the
frame draws. A fragment pass's `inputs` reads through the same fixed float
slot, so naming `@scene.material` there is refused the same way; a compute
pass reads that channel through a `sample: uint` slot instead.
**What a pass with no `inputs` samples.** A fragment pass that declares no
`inputs` reads `@scene.color` — the shape of an effect that filters the scene
image. A pass that names `@scene.color` among its own `outputs` samples a 1x1
transparent texel instead, because the scene colour is that pass's render
target and one texture is a colour attachment or a sampled resource in a render
pass, never both. Declare `inputs = { src = "@scene.color" }` and write an RT
to read the scene image and write somewhere else in one pass.
- **`"compute"`** — a workgroup dispatch (`shader`, `storage`, `buffers`, `dispatch`;
see "Compute passes").
- **`"geometry"`** — draw scene geometry with a constructed pipeline. The program
is a **material** the feature built (`renderer.material.create`); the engine
draws the scene's render-objects with that material's pipeline + uniforms.
- **`"draw"`** — rasterize the feature's OWN geometry: `geometry` names a buffer
created with `usage = { "vertex" }`, `storage.index` one created with
`usage = { "index" }`, and `select` the one entity whose transform and
material the draw lands through. `params[0]` is how many indices to submit —
or name a buffer under `storage.indirect` (created with
`usage = { "indirect" }`, holding a `DrawIndexedIndirectArgs` block: index
count, instance count, first index, base vertex, first instance) and the count
comes from the GPU instead, so a compute pass that compacts geometry pays only
for what it kept and nothing waits on a read-back. `first_instance` must be 0;
the engine resolves the entity's per-instance data another way, because a
non-zero one needs a device feature WebGPU does not guarantee.
- **`"splat"`** — rasterize a compute buffer of particle records as instanced
camera-facing billboards into feature RTs (see "Splat passes").
### Geometry passes
A geometry pass re-draws the scene's meshes with a material you supply — the
generic primitive for mesh-space effects (the engine names none of them):
```luau
ctx.enqueue {
kind = "geometry",
material = myMaterial, -- the HANDLE renderer.material.create
-- returned (or its registry-key string)
geometry = "@geometry.opaque", -- which drawables: "@geometry.opaque" |
-- "@geometry.transparent" | "@geometry.all"
select = { entityA, entityC }, -- OPTIONAL: restrict to these entities
-- (entity refs); omit = every matching mesh
phase = "afterLighting", -- afterLighting = lit scene + valid depth
}
```
`select` restricts the draw to the given entities — the per-instance signal that
turns a whole-scene pass into a chosen-meshes effect. The **material** decides how
those meshes are drawn; you control three things:
- **Pipeline render-state.** `renderer.material.create` takes a `render` block —
`cull` (`back`/`front`/`none`), `depthWrite` (bool), `blend`
(`opaque`/`alpha`/`additive`) — so the pass can rasterize differently from the
surface pass:
```luau
local myMaterial = renderer.material.create({
shader = myShaderKey, -- a .shader you authored (identity, not guid)
render = { cull = "none", depthWrite = false },
properties = { outline_color = { 1, 0.4, 0, 1 } }, -- seed the shader's uniforms
}, "my_pass_mat") -- pass `myMaterial` (or "my_pass_mat") as the pass `material`
```
- **The shader.** A geometry `.shader` is a surface shader: author `fn vertex(v:
VertexData) -> VertexData` to move vertices (object-local `v.position` /
`v.normal`) and `fn fragment(input: FragmentData) -> vec4<f32>` for the colour.
- **Its properties.** A shader reads ONLY the uniforms IT declares in
`properties.yaml`, via `material.<yourProp>`. Referencing a field it didn't
declare (e.g. a StandardMaterial `material.base_color`) fails to compile and the
mesh renders **magenta** — declare the property or use a constant.
What effect those three produce (outline, x-ray, wireframe, highlight, …) is
yours to design — the engine just draws the selected geometry with your pipeline.
### Compute passes
A compute pass dispatches a `.shader` compute program over a workgroup grid:
```luau
ctx.enqueue {
kind = "compute",
shader = myComputeShaderKey,
storage = { outTex = myStorageRtGuid }, -- slot -> storage-texture RT guid
buffers = { particles = "my_particle_buf" },-- slot -> named compute buffer
inputs = { camera = "@frame.camera" }, -- slot -> @frame.*/@scene.* buffer
dispatch = { x = 64, y = 1, z = 1 },
}
```
**`dispatch` is optional.** Omit it and the pass is dispatched over what it
WRITES: a grid covering its first `storage` texture, at the `@workgroup_size` the
shader's entry point declares. With a screen-sized storage target that grid
tracks the render target being drawn, so a screen-space effect covers the live
viewport, an offscreen capture and an RTT camera without the feature knowing any
of their resolutions:
```luau
ctx.enqueue {
kind = "compute",
shader = myComputeShaderKey,
inputs = { scene_color = "@scene.color", cam = "@frame.camera" },
storage = { outTex = myScreenSizedRt.guid }, -- screen = true
phase = "afterLighting",
}
```
State an explicit `dispatch` for a grid that is not one thread per output texel
(a reduction, a particle sim), or when the shader's `@workgroup_size` is an
override/const expression the engine cannot read.
Each WGSL storage-buffer binding in the shader resolves its bound slot in this
order: an explicit `buffers` mapping (the handle a buffer's owner holds, or a
name), then `inputs` (`@frame.camera` / `@scene.lights` /
`@scene.reflectionProbes`), then — when a slot has neither — a buffer whose
engine-side name equals the slot's own name. `buffers`
is the seam a pass binds through: the buffers a shader works over are the ones
handed to it, whatever each is called. `storage` binds storage TEXTURES (RT
guids) the same way, one map per resource kind.
### Splat passes
A splat pass draws every record of an f32 buffer as a camera-facing billboard —
the raster primitive behind screen-space particle surfaces (the `fluidSurface`
system is built entirely on it):
```luau
ctx.enqueue {
kind = "splat",
phase = "afterLighting",
output = depthRt.guid, -- or `outputs` for the thickness+color MRT
splat = {
buffer = "my_particles", -- compute-buffer name
stride = 12, -- floats per record
posOffset = 0, -- float offset of the position
count = 200000, -- records to draw
radius = 0.3, -- world particle radius
channel = "depth", -- "depth" | "thickness" | "sprite" | "gaussian"
velOffset = 4, -- optional: velocity → screen-space stretch
stretch = 0.04, -- seconds of motion elongating the billboard
colorOffset = 8, -- optional (thickness): + per-particle RGB → MRT
weightOffset = 7, -- optional (sprite): per-particle intensity
minY = -60.0, -- records below this y collapse (parked/dead)
maxRadiusPx = 120, -- optional: cap on the projected pixel radius
},
}
```
The `"gaussian"` channel draws the engine's packed splat records — what
`renderer.splat.components` decodes a `.spz` or `.ply` capture into — as
elliptical-weighted-average Gaussians, and takes fields of its own:
```luau
splat = {
buffer = "cloud_records",
stride = 6, -- the packed record is six u32 words
posOffset = 0,
count = 1200000,
radius = 1.0, -- multiplies each splat's stored scale
channel = "gaussian",
orderBuffer = "cloud_order", -- back-to-front permutation; "over" needs one
shBuffer = "cloud_sh", -- optional: quantized higher-order SH
shStride = 24, -- u32 words of SH per record
shDegree = 3,
transform = model, -- object -> world, column-major, 16 floats
prevTransform = prevModel, -- where `transform` stood last frame
opacityScale = 1.0,
}
```
`transform` places the cloud: each Gaussian's covariance is conjugated by its
upper-left 3×3, so a non-uniform scale shears the cloud the way it shears a mesh.
`prevTransform` plus a second entry in `outputs` makes the channel write an MRT
pair — the colour into the first target, and the screen-space displacement each
splat underwent between the two placements into the second, premultiplied by the
same alpha the colour composites under. That second target therefore resolves to
`(coverage-weighted mean displacement, coverage)`, which is what folds a moving
cloud into `@scene.motion`. Naming one target, or leaving `prevTransform` out,
renders the colour alone.
The other three channels write different fragments: `"depth"` writes nearest-surface
linear view depth (R32Float, hardware-depth-tested on the target's own depth
buffer), `"thickness"` accumulates additive optical thickness (with
`colorOffset` and a two-entry `outputs` list it also accumulates
thickness-weighted color into the second target), and `"sprite"` accumulates a
soft additive disc scaled by `weightOffset`. Every channel discards fragments
behind opaque scene geometry by sampling the scene depth at the fragment's own
NDC. `maxRadiusPx` scales down billboards whose projected major radius would
exceed that many pixels, so particles crossing the near plane stay
droplet-sized instead of filling the screen. Targets clear at the pass;
`blend = true` on the spec loads them instead to accumulate over a prior
splat pass.
`renderer.feature.create(featureRef)` instantiates a feature and returns a live
handle (`featureRef` may be an `AssetRef<renderFeature>` or its identity string).
The handle appears under `/zero/runtime/generated_features/<guid>/`. Re-creating
the SAME feature asset replaces the live one (hot-reload after editing
`init.luau`) rather than stacking a duplicate.
- `renderer.feature.list()` → `{ {guid, identity} }` for every live feature.
- `renderer.feature.destroy(handleOrGuid)` (or `renderer.destroy(handle)`) tears
one down — by handle OR by guid string, so you can stop a feature even after
losing its handle (e.g. across separate `execute` calls).
## In the Inspector
Selecting a render feature opens its **Feature** section: whether the feature runs in this session, an Enable or Disable action, and its settings as typed controls. While it runs, the controls hold its live values and an edit reconfigures the running feature (`renderer.feature.configure` checks it against the schema first). Those edits are session state: they change the running feature only, they are not undoable (Ctrl+Z never reaches them), and Disable or a restart ends them; the feature's declared defaults are what the next Enable starts from. While it does not run, the controls show the declared defaults, read-only, and a write reaching it then is refused. A feature enabled, disabled or reconfigured from a script shows in the section as it happens. A feature that declares no settings says so.
# effect
A set of visuals packaged as one thing: every impact a weapon makes, every stage
of an explosion, the muzzle flash, impact and tracer of a gun. Each visual is an
entry the effect plays by name. The graphs, the parts they are built from, and
the shaders, materials, compute shaders and textures they use all live inside
the effect.
## The shape on disk
<name>.effect/
effect.yaml what it plays: entry name -> one graph, or a list of graphs played together
graphs/ the graphs its entries play
parts/ graphs those graphs use as nodes, each one whole piece of the look
shaders/ shaders and shader modules its materials draw with
materials/
compute/ compute shaders its graphs run
textures/
README.md what this effect shows, what each entry plays, what each input changes
.metadata
settings.yaml its values for the settings below
preview.png its default entry at a representative moment
`effect.yaml`, `graphs/`, `README.md` and `.metadata` are required.
```yaml
plays:
flare: "~.graphs.flare"
impact:
- "~.graphs.impactFlash"
- "~.graphs.impactDebris"
default: flare
```
Inside an effect `~.x` names the effect's own `x`: `~.graphs.flare`,
`~.parts.crack`, `~.shaders.lava`, wherever the effect sits.
## Graphs and parts
A graph under `graphs/` composes what one entry shows. A piece worth building
and looking at on its own (the crack of a fissure, the spray, the smoke) is a
graph under `parts/`, called as a node:
```lua
local crack = g["~/parts/crack"]({ length = length })
```
A part is a whole graph, so it previews and plays alone: the crack without the
smoke in front of it. An operation several effects use (a streak look, a smoke
puff) is a `.procNode` outside the effect, used the way a module is required.
## Playing one
```lua
local beacons = asset.resolve("beacons", "effect")
local shown = beacons:play("flare", { root = mast, offset = { 0, 0.9, 0 }, inputs = { size = 0.4 } })
shown:set("size", 0.6)
shown:onFinished(function() print("done") end)
```
`root` is the entity it plays on and follows; `inputs` go to every graph of the
entry that declares them; the handle answers `set`, `pause`, `resume`, `seek`,
`getTime`, `stop`, `isFinished` and `onFinished`. A play finishes when every
graph of its entry reaches the end of its timeline; a graph that states
`realTime` alone has no end, so a play of it runs until `stop()`, and a
simulation that runs once states its frames
(`g:timeline({ realTime = true, frames = 120 })`). Plays are kept ready, built
ahead of time: `beacons:warm("flare", 6)` keeps six ready for a burst. An
`Effect` component, or a drop into the viewport, places an entry in a scene.
`entries()` and `entry(name)` read what it plays; `setEntry`, `removeEntry`,
`renameEntry`, `setDefault` and `newGraph` change it, keeping every line of
`effect.yaml` they do not touch.
## Settings
`pool`: how many plays of each entry are kept ready (default 2).
## In search
Each asset inside an effect is found on its own and names the effect it
belongs to. The effect itself is found by its preview, its README and its
entries.
# Material (asset type)
A material is a named, configured instance of a `.shader`. The shader
defines the surface look (lighting model, available property fields,
texture slots); the material picks values for those fields and a
shader to bind to. Renderable entities reference materials, not
shaders, so the same geometry can wear different materials and the
same material can be reused across many entities.
Entities sharing one material can still differ in a value: every drawn
object carries four `vec4` lanes of its own that a surface shader reads
as `input.shader_data[lane]` and `renderer.instanceData.set` writes. Use
that for a dissolve at its own progress per subject, a hit flash at its
own age, a fill level per instance — a material per entity is for when
the LOOK differs, not when a number does.
> New to how a material relates to its shader, its textures, and the live GPU
> material behind it? Read `core/resource-model` first. It also covers the
> difference between an authored `.material` asset (this type) and a runtime GPU
> material made with `renderer.material.create`.
## When to use one
- You want a named surface configuration an entity wears by referencing it
from its `Model` component (`material = "@.../<Name>"`).
- You want runtime property tweaks (`asset.resolve(ref):setProperty(...)`) to
affect every entity using the material at once.
- You want to publish a curated look (`Gold`, `RedGlow`,
`BrickWall`) other authors can reuse without re-typing shader
bindings.
If you need a brand-new lighting model or a custom visual effect, you
need a `.shader` first; the material wraps it.
## Where it lives
- Source: `/zero/source/.../<Name>.material/`
- Identity: `<Name>` (the `.material` suffix strips).
- Folder shape:
- `mat.yaml` — canonical material spec (shader + property values).
**Required.**
- `preview.png` — the material's rendered shader-ball still, its
persisted visual description. **Required.** Rendered when the
material is staged (`zm add`) with its preview missing or stale, and
by `generatePreviews`; it syncs, publishes, feeds image-based search,
and gives browsers a thumbnail.
- `README.md` / `.metadata` — optional prose + tags, indexed when an
author writes real ones.
- `textures/` — optional folder for embedded textures. Validator
allows the folder; its interior is unrestricted.
- `shaders/` — optional folder for a co-located custom shader.
Same rule.
## How to create one
```luau
asset.create("material", "<Name>")
-- Creates: /zero/source/<Name>.material/
-- mat.yaml (shader binding + property scaffold)
-- preview.png (rendered when the material is staged with `zm add`; the
-- picture lands as a change the next `zm add` stages)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("material", "<Name>", { folder = "materials" })
```
Pass the shader and initial values through `asset.create`, then tune with
`setProperty` and keep what you tuned with `saveDefinition`:
```luau
local mat = asset.create("material", "<Name>", { shader = "@builtin::shaders.pbr" })
mat:setProperty("base_color", { 0.8, 0.6, 0.1, 1 })
mat:setProperty("roughness", 0.3)
mat:saveDefinition() -- writes the tuned values into mat.yaml
```
This mints the `.material` asset and returns a handle you tune with
`setProperty`. A set is a runtime change: it reaches the GPU material and every
entity wearing it, and `saveDefinition` is the call that writes it into
`mat.yaml`, so a property driven every frame costs no file write and leaves the
authored file as its author wrote it. A purely runtime `asset.create` lives only
for the session.
For an ephemeral, runtime-only GPU material that is not an asset at all, use
`renderer.material.create` instead (see `core/resource-model`).
## How it operates
1. **Property reflection.** The bound shader's uniform struct fields
become the material's configurable properties — no manual property
declarations needed. `naga` introspects the shader at load.
2. **Property values.** `mat.yaml` groups values by type, each block
keyed by the shader's field names: `properties:` holds scalars and
colors/vectors, `ints:` holds integer-typed fields, `bools:` holds
boolean-typed fields, and `textures:` holds texture slots. Omitted
fields take the shader's default. A scalar is a bare number
(`roughness: 0.5`); a color or vector is an array
(`base_color: [1, 1, 1, 1]`). `shader:` is the shader's identity
string. This is the shape every material the engine writes uses. A
`saveDefinition` writes the changed values into the file where they
already stand and leaves the rest of it — its comments, the order of
its keys and blocks, the spelling of its literals — untouched. The older
`floats:` / `colors:` blocks (with `{ r, g, b, a }` map colors) still
load for materials hand-authored that way.
3. **Render state.** `render:` holds how the mesh is drawn rather than
what the shader reads: `blend` (the equation the fragment composites
with, also spelled `type`), `cull`, `depth_write`, `depth_compare`
and `topology`. The `.shader` type README's "The render block"
section lists every value each key takes, and `asset.create`'s
`render` argument takes the same keys and values.
4. **Application.** An entity wears a material by referencing it from its
`Model` component (`material = "@.../<Name>"`). Materials affect every entity
that references them; runtime `asset.resolve(ref):setProperty(...)` changes
propagate to all of them immediately, and last until the next mode change
unless `saveDefinition` writes them into `mat.yaml`.
5. **Texture binding.** Texture slots accept `color:r,g,b,a` for
solid colors, `default:white` / `default:black` / `default:normal` for the
engine's own fallback texels, `@builtin::textures.<name>` for builtins,
`path/to/image.png` for file textures, or a render-target handle
for camera renders. The GPU texture cache reads the `color:` and
`default:` forms from the string itself, so a slot written in one names no
asset and carries nothing with the material when it travels; every other
form names a texture asset the slot depends on.
A texture in `base_color_texture` is multiplied by `base_color`: every
built-in surface shader declaring both draws the texture's colour times
`base_color`, channel by channel. Under the default white `base_color` the
texture shows as itself, and a coloured `base_color` tints it. The two
read a colour differently: `base_color` is linear, and the slot reads its
texels as sRGB-encoded, a `color:` value's included, the way it reads an
image. A colour stated in both places is therefore multiplied by a darker
copy of itself: `color:0.62,0.14,0.05,1` in the slot decodes to
`0.34, 0.017, 0.0039`, so beside `base_color` `0.62, 0.14, 0.05` the
surface draws `0.21, 0.0024, 0.0002`, far darker than either. State a
solid colour once, as `base_color`, and leave the slot at its default
white.
6. **Hot reload.** Editing `mat.yaml` repacks the GPU uniform buffer
on the next frame; visible immediately.
7. **Inspector.** `type.yaml` names `inspector: { type: "inspector.luau" }`,
and `inspector.luau` declares the material's sections beside the generic
ones: `shader` (the bound shader, swappable), `properties` (each shader
field as its typed control) and `textures` (each texture slot as an asset
chip). They read the material through `mat:getShaderRef()` (the bound
shader's ref, `~` expanded) and `mat:getTextures()` (slot name →
`{ ref, name }`: the bound texture's guid and the id the material names
it by). An edit there is an authoring write: `mat:writeProperty(name,
value)` and `mat:writeTexture(slot, texture)` write the value into
`mat.yaml` (and drop the session's own value for it, so the material
reads what the file holds), and `setShader` rewrites the file; inside an
undo operation each file write is recorded, so undo puts `mat.yaml` back.
`setProperty` / `setTexture` stay runtime writes that last until the next
mode change.
## Discovery
- `asset.list("material")` — every registered material.
- `asset.inspect("<name>")` — shader binding, property values,
source path, this type README.
- `ls /zero/source/<Name>.material` lists the files the folder holds.
- `asset.resolve("<name>"):getProperties()` — the property fields exposed by
the bound shader, each at the value it currently holds: what `mat.yaml`
authored until something writes to the material, and the written value from
then on, whichever call wrote it. That is the value the surface is drawn
with. Read them back rather than guessing names; which fields exist comes
from the shader.
- `asset.resolve("<name>"):getDefinition()` — the authored `mat.yaml` bytes,
the value the material rests at.
- `asset.resolve("<name>"):getShader()` — the shader the material binds.
## Authoring conventions
- Use lowercase, descriptive names (`brushed_steel`, `red_glow`,
`tarmac_wet`). Avoid shader-name suffixes in the material name —
the binding lives in `mat.yaml::shader`.
- Drive every property the shader exposes; defaults are a fallback,
not a contract for which fields exist.
- Embed textures alongside the material (`textures/` subfolder) when
they're used only by this material; reference shared textures from
`@builtin::textures.*` or a library.
## Common pitfalls
- **Property names must match the shader's uniform struct exactly**
(case-sensitive). Misnamed properties silently get the shader's
default.
- **`base_color_texture` multiplies `base_color`.** A `color:` texture holding
the same value as `base_color` multiplies the colour by its own
sRGB-decoded value, so the surface renders far darker than the value
written. Write a solid colour as `base_color` alone.
- **Broken shaders break the material.** A material whose shader has a
parse error renders as the magenta checkerboard. Inspect the shader
first if the material looks wrong.
- **`setProperty` targets the material, not the entity.** Changes affect
every entity that references the material.
- **`setProperty` is a runtime change.** It reaches the GPU, not the file:
call `saveDefinition` to write the current values into `mat.yaml`. For a
per-entity override that no other entity sees, give the entity its own copy
with `Model:applySessionMaterial(renderer.material.create(...))`.
- **Renaming the folder changes the identity.** Update every `Model`
component and `asset.create` callsite that references it.
## Related types
- `.shader` — defines what properties exist; required before a
material can bind to it.
- `.preset` — captures a component configuration; conceptually
similar to a material, but for components instead of shaders.
# Toolbox (asset type)
A toolbox is a namespace folder that groups related `.tool/` children
plus shared helpers. Toolboxes are the addressing layer for tools —
every tool's identity is `<toolbox>.<name>`, so the toolbox name
appears in every callsite. Toolboxes also own a `shared.module/`
helper module that the toolbox's tools `require(".shared")` for
common utilities (result envelopes, validators, formatters).
## When to use one
- You have two or more related tools that belong together (an `anim`
toolbox with `play` / `stop` / `list`; an `assets` toolbox with
`compose` / `validate`).
- You need a shared helper module exclusively used by a tool set.
- You want a clean dot-namespaced identity for your tools
(`my_tools.foo`, `my_tools.bar`).
If you only have one tool and no shared helpers, you still need a
toolbox — it's the required parent.
## Where it lives
- Source: `/zero/source/.../<Name>.toolbox/`
- Identity: `<Name>` (the `.toolbox` suffix strips).
- Folder shape (container-style — open child set):
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- `shared.module/` — optional shared helper module
(`init.luau` + `README.md`).
- `<x>.tool/` — any number of `.tool/` children.
The validator permits unlisted children (`allow_unlisted: true`) so
tool subfolders don't need to be declared per-name.
## How to create one
```luau
tools.createToolbox({ name = "<Name>", description = "..." })
-- or the generic scaffold:
asset.create("toolbox", "<Name>")
-- Creates: /zero/source/<Name>.toolbox/
-- README.md (instance README template)
-- shared.module/ (ok / fail result-envelope constructors)
-- `folder` places it in a subfolder of /source; `into` nests it in a
-- resolved `.package`:
asset.create("toolbox", "<Name>", { folder = "tools" })
```
Then add tools under it:
```luau
local box = asset.resolve("<Name>.toolbox")
asset.create("tool", "<toolName>", { into = box })
```
## How it operates
1. **Registration.** Writing into a `.toolbox/` folder indexes the
toolbox. It becomes the parent namespace for any `.tool/`
children.
2. **Tool identity composition.** Each child `.tool/`'s identity is
`<toolbox>.<tool>`. Listing the toolbox's tools enumerates the
children.
3. **Shared helpers.** Tools inside the toolbox pull
`shared.module/` in via `require(".shared")` (relative require
from the tool's `init.luau`).
4. **Hot reload.** Editing `shared.module/init.luau` reloads every
tool in the toolbox (they all `require` it). Editing the toolbox
folder structure (adding / removing tools) reflects in
`tools.list` immediately.
## Discovery
- `asset.list("toolbox")` — every registered toolbox.
- `asset.inspect("<name>")` — child tools, source, this type
README.
- `ls /zero/source/<Name>.toolbox` lists the files the folder holds.
- `tools.list()` — every tool across every toolbox.
## Authoring conventions
- **Per-tool implementation lives in each `<x>.tool/init.luau`.**
The tool's full function body — argument validation, the call
into engine APIs, the return value — goes in `init.luau` with
`--!desc` / `--!arg` / `--!return` / `--!example` annotations
above the function. **Every exported function is declared
`typed function`** — the keyword compiles to the runtime argument
check, so a plain `function` accepts any input and reports success
on garbage. Do NOT make `init.luau` a one-line forwarder onto a
function defined in `shared.module/`.
- Keep `shared.module/` thin: result envelope constructors
(`shared.ok(value, formatted)`, `shared.fail(message, exitCode)`),
argument validators, common formatters — anything genuinely used
by more than one tool. Per-tool logic does NOT belong here.
- Group by domain, not by surface — `assets` toolbox holds asset
operations, `entity` toolbox holds entity operations. Tools that
feel unrelated probably want different toolboxes.
- Document the toolbox's surface in `README.md` — what problem space
it covers, who calls into it, any shared invariants.
## Common pitfalls
- **Missing parent toolbox.** Tools cannot exist outside a toolbox.
Always scaffold the toolbox first.
- **Cross-toolbox shared.** Each toolbox has its own
`shared.module/`. Don't try to share helpers across toolboxes; if
you need cross-toolbox helpers, factor them into a standalone
`.module`.
- **Toolbox identity.** Strip the `.toolbox` suffix in identity
references (`my_tools`, not `my_tools.toolbox`).
## Related types
- `.tool` — the required child(ren) of a toolbox.
- `.module` — for cross-toolbox utilities.
## In the Inspector
Tools: how many tools the box holds, whether it ships a shared module, what each tool does, and a link to each tool.
# Compute shader (asset type)
A `.computeShader` is a GPU compute (GPGPU) program with a **zero-scaffolding**
authoring contract: you write only `@compute fn main(...)` plus a declarative
`bindings.yaml`, and the engine GENERATES every `@group/@binding` declaration —
storage buffers, textures, samplers, storage textures, and a `params:` uniform —
expands `#include`s, naga-validates the result, and registers it. The single
source of truth for the binding layout is `bindings.yaml`; there are no
hand-written `@binding` lines to keep in sync.
> New to how content lives across the CPU and GPU? Read `core/resource-model`
> first: it covers the asset / CPU / GPU forms every resource takes, the upload
> path, and how compute fits the performance ladder (`core/performance`).
## Folder shape
A `.computeShader` is a folder asset:
```
<name>.computeShader/
shader.wgsl # the WGSL body — only `@compute fn main` + helpers (required)
bindings.yaml # the binding + params schema (required)
README.md # a one-paragraph description of THIS shader (required)
.metadata # asset metadata
```
Each file carries a committed `.meta` sidecar pinning its stable guid. The
identity is `<name>` (the `.computeShader` suffix strips).
Resolve the shader once, then dispatch through the reference:
```lua
local carve = asset.resolve("carve", "computeShader")
carve:dispatch({ buffers = { heights }, workgroups = { 64 } })
```
`asset.resolve` is what records your script's dependency on the shader, so the
shader travels with the world your script lives in — packed, pulled, or
published. It compiles on first dispatch; there is no setup step.
## bindings.yaml
One ordered `bindings:` list — the binding index is the list position
(0, 1, 2, …) — plus an optional `params:` scalar-uniform block. `kind` defaults
to `buffer` when omitted.
```yaml
bindings:
- { name: clouds, kind: storage3d, format: rgba16f } # texture_storage_3d<rgba16float, write>
- { name: occupancy, kind: texture3d } # texture_3d<f32>
- { name: smp, kind: sampler } # sampler
- { name: out_tex, kind: storage2d, format: rgba16f } # texture_storage_2d<rgba16float, write>
- { name: U, kind: buffer, access: read, element: f32 } # var<storage, read> U: array<f32>
- { name: Uniforms, kind: buffer, access: read, element: VolumeUniforms, array: false } # var<storage, read> Uniforms: VolumeUniforms
params:
- { name: scale, type: float, default: 2.0 }
- { name: count, type: int, default: 0 }
```
| `kind` | extra keys | generated WGSL declaration |
|---|---|---|
| `buffer` (default) | `access: read \| read_write` (default `read_write`), `element: <wgsl type>` (default `f32`), `array: true \| false` (default `true`) | `var<storage, ACCESS> NAME: array<ELEMENT>;` (or `… NAME: ELEMENT;` when `array: false`) |
| `texture3d` | — | `var NAME: texture_3d<f32>;` |
| `texture2d` | `sample: float \| uint \| sint` (default `float`) | `var NAME: texture_2d<f32>;`, or `<u32>` / `<i32>` for the other classes |
| `texture_depth` | — | `var NAME: texture_depth_2d;` — the one sampled shape with no `sample:` of its own; a depth-aspect channel (`@scene.depth`) binds here, not through `texture2d` |
| `storage3d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_3d<FMT, ACCESS>;` |
| `storage2d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_2d<FMT, ACCESS>;` |
| `sampler` | — | `var NAME: sampler;` |
| `textureCubeArray` | — | `var NAME: texture_cube_array<f32>;` — the environment cube array, bound to `@scene.environment` by a render feature's pass |
| `vertices` | `access: read \| read_write` (default `read_write`) | `var<storage, ACCESS> NAME: array<u32>;` plus the mesh's layout uniform and the `zeroVertex*` accessors |
| `acceleration_structure` | — | `var NAME: acceleration_structure;` (hardware ray tracing) |
- **Eight storage buffers per shader** — the WebGPU guarantee, and what the
engine asks every device for. `buffer` and `vertices` bindings spend that
budget; textures, samplers, storage textures and `params:` do not. An
`acceleration_structure` brings engine-owned buffers with it — **three** where
the device has hardware ray query (the tables `zeroHitSurface` / `zeroMaterial`
read) and **five** on the software backend (those, plus the scene triangles and
the hierarchy over them) — so a traced pass has three slots of its own on the
backend web users get. Over budget, the engine refuses the shader and logs
which buffers it declared.
- A `buffer` defaults to `array<ELEMENT>`. Set `array: false` for a single
NON-array storage buffer — a struct binding (e.g. `element: VolumeUniforms`,
`array: false` → `var<storage, read> NAME: VolumeUniforms;`). The struct
definition itself lives in `shader.wgsl`, not `bindings.yaml`.
- **A sampled texture binds under the class its FORMAT puts it in**, so
`sample` states that class and the generated `texture_2d<..>` matches it. An
integer channel — `@scene.material`, which is `Rgba8Uint` — is `uint`;
everything else is the `float` default. Bind an integer channel to a `float`
slot and the engine refuses the pass and names both classes, because the
device would otherwise reject the bind group and invalidate the pipeline.
- A storage texture's `access` decides both the generated declaration and the
layout the engine registers, so the two always agree. It defaults to `write`,
the access every target grants every storage-compatible format. `read_write`
is granted on `r32f` alone; declaring it on any other format is refused at
the compile, with the reason on `compute.programState`. A pass that needs to
read a wider target reads it through a separate `texture3d` / `texture2d`
binding, or through a second storage binding declared `read`.
- `format` tags (storage textures): `r8`, `r16f`, `r32f`, `rgba8`, `rgba16f`,
`rgba32f`. Storage textures only allow storage-compatible formats
(`r32f` / `rgba8` / `rgba16f` / `rgba32f`).
- An `acceleration_structure` binding resolves to the scene acceleration
structure when the shader runs as a render-pass with ray tracing enabled
(`renderer.setRaytrace(true)`). Declaring one makes the engine emit the helper
functions the body can call:
`zeroTraceClosest(origin, dir, t_min, t_max) -> ZeroHit` (struct: `hit, t,
instance, primitive, bary, attr`, where `instance` is the hit object's render
slot), `zeroTraceAny(origin, dir, t_min, t_max) -> bool`
(terminate-on-first-hit, for shadow/occlusion rays), and
`zeroHitSurface(hit) -> ZeroSurface` (`normal, uv, material`) +
`zeroMaterial(index) -> ZeroMaterial` (`base_color, emissive, metallic,
roughness`) to shade what a hit landed on. The same surface works on both backends — hardware
ray query and the software/compute path — so the shader doesn't branch on
`renderer.raytraceCapability()`. Bind it from a render-pass, which is where
the scene acceleration structure exists.
`params:` declares scalar uniforms (`type: float | int`). When non-empty the
engine appends a `ZeroComputeParams` uniform as the trailing binding (read it in
WGSL as `params.<name>`) and tunes its values at runtime with
`shaderRef:setParam(prop, value)`.
## The kernel ABI: `columns`, counted and appended outputs, `specialize`, `determinism`
One shader asset can serve many shapes of data. `bindings.yaml` states the shape
with these extensions, and the engine's compile path lowers them to the plain
bindings and WGSL above (`modules/compute_abi`, whose README has the whole
surface):
```yaml
workgroup: 64 # the size the body declares (default 64)
bindings:
- { name: cols, kind: columns, access: read } # a table of columns in one binding
- { name: src, kind: buffer, access: read, element: T }
- { name: dst, kind: buffer, access: read_write, element: T, count: "len(src)" }
- { name: hits, kind: buffer, access: read_write, element: vec4<f32>, capacity: "n * 4", append: true }
specialize:
- { name: T, options: [f32, i32, vec2<f32>, vec3<f32>, vec4<f32>] }
- { name: FOLD, options: [add, min, max] }
- { name: BODY, kind: source, default: "0.0" } # text that replaces the identifier
determinism: exact # or float_order
```
- A `buffer` of a scalar or vector element gets `NAME_get(i)`, `NAME_len()` and
(unless `access: read`) `NAME_set(i, v)`. A `vec3` element is stored as a flat
scalar array, so a column of vec3 keeps its 12-byte stride. `zero_n()` is the
dispatch size.
- `columns` binds a table of columns (`compute_abi.table`) as one storage buffer;
`cols_f32(c, i, lane)`, `cols_vec3(c, i)` and the rest read it.
- `count` / `capacity` give the size, in elements, of an output the run
allocates. `append: true` adds a live counter binding, `NAME_count`, with
`NAME_store(slot, v)`, `NAME_set_count(n)` and, under `determinism: float_order`,
`NAME_append(v)`.
- `specialize` parameters are compile-time: type options become `alias NAME`,
named options become `const NAME` and `NAME_<option>`, `kind: source` text
replaces the identifier. Each specialization compiles once.
- `determinism: exact` refuses `NAME_append`: an exact output is written at ranks
the kernel computed.
Dispatch such a shader through its program:
```lua
local variant = shaderRef:program():variant({ specialize = { T = "vec3<f32>" } })
local run = variant:run({ n = 64, inputs = { src = srcBuffer } })
local values = require("@builtin::modules.compute_abi").read(run.outputs.dst.buffer)
```
`shaderRef:program()` answers the same program, with the variants it has lowered and compiled, for as long as
`shader.wgsl` and `bindings.yaml` hold the bytes they held when it was made. A write to either file, from any origin
(`vfs.contentVersion` moves), makes the next `program()` a new one, and a dispatch through it runs the new text. The
schema `getBindings()` answers is the one the program was made over.
## Writing a mesh's vertices — `kind: vertices`
A mesh's vertices are raw bytes on the GPU, and the engine stores a mesh in one
of two layouts: 92 bytes a vertex with every attribute a `f32`, or 32 bytes a
vertex with normals and tangents quantized to bytes and UVs to shorts. Which one
a mesh got depends on the mesh.
Declare `kind: vertices` and the shader is handed both the buffer and the layout
that mesh is in, plus accessors that address it:
```yaml
bindings:
- { name: verts, kind: vertices } # the mesh, writable
- { name: heights, kind: buffer, access: read, element: f32 }
params:
- { name: lift, type: float, default: 1.0 }
```
```wgsl
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x >= zeroVertexCount()) { return; }
var p = zeroVertexPosition(id.x);
p.y = p.y + heights[id.x] * params.lift;
zeroSetVertexPosition(id.x, p);
zeroSetVertexNormal(id.x, vec3<f32>(0.0, 1.0, 0.0));
}
```
```lua
carve:dispatchOnVertices({ model = meshRef:handle().guid, buffers = { heights }, workgroups = { 64 } })
```
The accessors, over a binding declared `read_write`:
| read | write |
|---|---|
| `zeroVertexCount() -> u32` | — |
| `zeroVertexPosition(i) -> vec3<f32>` | `zeroSetVertexPosition(i, vec3<f32>)` |
| `zeroVertexNormal(i) -> vec3<f32>` | `zeroSetVertexNormal(i, vec3<f32>)` |
| `zeroVertexTangent(i) -> vec4<f32>` | `zeroSetVertexTangent(i, vec4<f32>)` |
| `zeroVertexUv(i) -> vec2<f32>` | `zeroSetVertexUv(i, vec2<f32>)` |
| `zeroVertexColor(i) -> vec4<f32>` | `zeroSetVertexColor(i, vec4<f32>)` |
| `zeroVertexNodeIndex(i) -> u32` | — |
| `zeroVertexWord(i, offset) -> u32` | — |
`access: read` gives you the readers only — a `var<storage, read>` binding
cannot be assigned to, so the writers are left out rather than handed to you
broken.
Once a pass has written a mesh's vertices, the engine bounds that mesh by what
the pass wrote: it reduces the vertices to an AABB every frame and culls against
that, so geometry a pass moves across the scene needs no oversized placeholder
to survive culling. `renderer.mesh.boundsSource(guid)` reports `"compute"` for
such a mesh and `"geometry"` for one still bounded by what it was created with.
A shader declares at most one `vertices` binding; the accessors are generated
for that mesh. It can be declared anywhere in the list — the mesh is bound by
the dispatch, and `buffers` fills the other storage slots in declaration order.
The tangent's `w` carries handedness, and quantized normals/tangents come back
in -1..1 while quantized UVs and colours come back in 0..1, so the values are
the same ones a surface shader sees whichever layout the mesh is in.
## shader.wgsl
Write only `@compute fn main` (and any helpers / `#include`s). The names declared
in `bindings.yaml` are in scope — `data`, `out_tex`, `params.scale`, … — with no
`@group`/`@binding` lines of your own.
```wgsl
// @domain: compute
// Bindings are declared in bindings.yaml — do NOT write @group/@binding here.
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x < arrayLength(&data)) {
data[id.x] = data[id.x] * 2.0;
}
}
```
## Dispatch & runtime
Everything a compute shader does, it does through its reference:
| method | what it does |
|---|---|
| `ref:dispatch(opts)` | `{ buffers, workgroups, params? }` — bind one buffer per declared storage binding, in order |
| `ref:dispatchOnVertices(opts)` | `{ model, buffers?, workgroups, params? }` — bind the mesh `model` names to the `vertices` binding, `buffers` filling the rest |
| `ref:dispatchEx(opts)` | `{ resources, workgroups }` — for shaders mixing textures, samplers and storage textures: one `{ kind, name }` per declared binding, in order |
| `ref:setParam(prop, value)` | write one `params:` scalar uniform |
| `ref:createBuffer(name, opts)` | `{ type, len, usage? }` — a GPU buffer owned by this shader |
| `ref:buffer(name)` | the buffer this shader last made under `name` |
| `ref:getBindings()` | the parsed `bindings.yaml` schema, read and parsed again only after the file is written |
| `ref:getSource()` / `ref:setSource(wgsl)` | read / overwrite `shader.wgsl` |
| `ref:compile()` | compile now instead of on the first dispatch |
| `ref:status()` | what the engine did with this shader's dispatches, one record per target |
The `params:` uniform is engine-owned and takes no entry in `buffers` or
`resources`, and neither does a `vertices` binding's layout.
`setParam` writes the uniform every later dispatch reads. A dispatch that
passes `params = { name = value }` reads those values instead, in a copy of the
uniform only it binds, with every name it leaves out at the value the shader
holds — so one shader dispatched twice in a frame over different data reads
different values each time:
```lua
lift:dispatch({ buffers = { a }, workgroups = { 4 }, params = { height = 1.0 } })
lift:dispatch({ buffers = { b }, workgroups = { 4 }, params = { height = 3.0 } })
```
A name the shader does not declare fails that dispatch, and the failure names
what it does declare.
### `dispatchEx` resources
Each `resources` entry fills the binding at its position. Its `kind` says what
the resource is, in the words `bindings.yaml` uses, and the binding decides how
it is read. A slot takes the kind it is declared with; a `texture2d` slot also
reads a storage texture, a side of a history pair or the scene depth, and a
`storage2d` slot also writes this frame's side of a history pair:
| binding's `bindings.yaml` kind | `resources` entry | `name` |
|---|---|---|
| `buffer` | `{ kind = "buffer", name = buf }` | a buffer handle from `ref:createBuffer` |
| `texture3d` | `{ kind = "texture3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` |
| `storage3d` | `{ kind = "storage3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` made with `storage = true` |
| `storage2d` | `{ kind = "storage2d", name = target }` | a storage texture handle from `ref:createStorageTexture2D` |
| `storage2d` | `{ kind = "history_curr", name = history }` | a history pair from `ref:createTextureHistory`: this frame's side |
| `texture2d` | `{ kind = "texture2d", name = tex }` | a handle `ref:copyBufferToTexture` returns, or a texture asset's guid once `texRef:handle()` has made it GPU-resident |
| `texture2d` | `{ kind = "storage2d", name = target }` | a storage texture handle, read as a texture |
| `texture2d` | `{ kind = "history_prev", name = history }` / `{ kind = "history_curr", name = history }` | a history pair: the previous frame's side or this frame's |
| `texture2d` | `{ kind = "scene_depth" }` | none: the frame's scene depth |
| `sampler` | `{ kind = "sampler", name = smp }` | a sampler handle from `ref:createSampler` |
`texture3d` and `storage3d` name the same resource, a 3D texture, so either one
fills either slot. The engine's own spellings name the same resources and keep
working: `texture_3d` for `texture3d` and `storage3d`, `texture_2d` for
`texture2d`, and `storage_2d` for `storage2d`. Any other `kind` is refused at the
call, naming every kind it accepts. A `vertices` binding is filled by
`ref:dispatchOnVertices`, and `texture_depth`, `textureCubeArray` and
`acceleration_structure` bindings by a render feature's pass.
```lua
local march = asset.resolve("volume_march", "computeShader")
-- bindings.yaml: density (storage3d), out_tex (storage2d), U (buffer)
march:dispatchEx({
resources = {
{ kind = "storage3d", name = density },
{ kind = "storage2d", name = target },
{ kind = "buffer", name = uniforms },
},
workgroups = { 8, 8, 8 },
})
```
`workgroups` is `{ x, y, z }`, `{ x }`, or a bare `x`, and every dimension it
leaves out is 1. A zero in any dimension is refused: the dispatch is dropped and
recorded as a failure, so it surfaces in `ref:status()` and `compute.failing()`
with the reason. A count derived from how much data there is passes through
`math.max` first, so an empty set dispatches one workgroup rather than none:
```lua
carve:dispatch({ buffers = { heights }, workgroups = { math.max(1, math.ceil(#points / 64)) } })
```
### Buffers and readback (the CPU side)
A buffer is created through the shader that owns it and comes back as a handle.
Pass the handle to a dispatch — including another shader's — to bind it there:
```lua
local double = asset.resolve("@builtin::shaders.compute_double", "computeShader")
-- `type` is the element the shader declares, `len` how many of them.
local data = double:createBuffer("data", { type = "f32", len = 4, usage = { "readback" } })
data:write({ 1.0, 2.0, 3.0, 4.0 }) -- :writeU32 for integer words, :writeBytes for packed bytes
double:dispatch({ buffers = { data }, workgroups = { 1, 1, 1 } })
local pending = data:read() -- starts an async GPU->CPU readback
-- a frame or two later, drain it (nil until it has arrived):
local out = pending:result() -- :resultU32 / :resultBytes read the same bytes another way
data:destroy() -- free it when done
```
`type` is one of `"f32"`, `"vec3"`, `"vec4"`, `"quat"`, `"mat4"`, and `usage`
adds `"readback"`, `"vertex"`, `"index"` or `"indirect"` on top of the storage a
buffer always has. An `"indirect"` buffer holds a draw's arguments where the GPU
reads them, so a shader that compacts geometry writes the drawn count into the
same dispatch that produced it and a render feature's `kind = "draw"` pass
submits exactly that — the `renderFeature` asset type's README documents that
pass and the `storage.indirect` name it reads.
The handle's key is the shader's guid plus the name you gave it and
a serial, so two shaders that both want a buffer called `data` get one each —
and so do two callers asking this same shader for one. `ref:buffer(name)`
returns the last one made under that name, which is how two callers share one
on purpose.
A buffer that no shader computes — a vertex or index run that is only ever
drawn — is allocated straight from the primitive instead:
`substrate.createBuffer({ name = ..., type = ..., len = ..., kind = "gpu", usage = { "vertex" } })`.
The first dispatch of a shader compiles it, so the very first readback can still
reflect the un-run shader; dispatch again once it is compiled, or `ref:compile()`
to pre-warm. This create/write/dispatch/readback loop is the CPU side of the
resource model in `core/resource-model`.
### Is it compiled?
`ref:compile()` queues the compile; the pipeline is built on the render side
frames later, so that call cannot say whether it produced a program.
`compute.programState(ref)` is where that lands:
```lua
if compute.programState(carve) == "ready" then carve:dispatch(opts) end
local state, reason = compute.programState(carve)
if state == "failed" then print(reason) end
```
- `"absent"` — the engine holds nothing under this key and nothing is in
flight: never asked for, or released.
- `"pending"` — a compile was asked for and has not reached the device. A
recompile of a resident program reads pending too, because what it produces
is a different program from the one bound now — which is what makes this the
precondition to wait on after an edit.
- `"ready"` — compiled and resident, so a dispatch naming it binds it.
- `"failed"` — the most recent compile produced no program, and the second
return says why.
A dispatch issued while the program is `"pending"` is held behind the compile
and dropped if it never lands, so a readback taken before `"ready"` reports the
buffer as it was. Wait for `"ready"`, not for a count of frames.
### Did it run?
A dispatch is recorded into a command encoder frames after the call that asked
for it returned, so that call's `true` means "queued", not "ran". `ref:status()`
is where the outcome lands — one record per target, cumulative:
```lua
for _, d in ipairs(carve:status()) do
print(d.target, d.ok, d.dispatches, d.failures, d.lastError)
end
```
`target` is the mesh guid for a `dispatchOnVertices` and the buffers it bound
for a dispatch that writes only those, so two systems driving one shader over
their own buffers read as the two passes they are. `ok` is the most recent outcome; `lastError` says
why the last failure failed and is kept after a recovery. An empty result means
nothing has dispatched this shader at all. `compute.failing()` answers the same
question across every shader at once.
A failing dispatch also posts a notice, so a pass that stops running reports
itself rather than waiting to be found.
### Running one every frame
A `kind = "compute"` substrate job queues one dispatch per frame:
```lua
jobs.register({
phase = "main",
executor = {
kind = "compute",
shader = asset.resolve("carve", "computeShader"),
buffers = { "heights" },
workgroups = { 64 },
},
})
```
## Registration & hot reload
Writing `shader.wgsl` or `bindings.yaml` fires the `.computeShader` assetType's
`onChange`, which calls `__compute.compile` — that generates the binding
declarations, expands `#include`s, naga-validates, and registers. This happens on
create and on every edit, so saving recompiles with no world reload. A shader
with invalid WGSL (a type mismatch, an undefined name) **fails to compile** with
the reason logged (`[compute] Compile of '<name>' failed: …`) and is **not**
registered. You don't need to register a shader before dispatching it — the first
dispatch auto-compiles it on use. `ref:compile()` remains as an optional explicit
pre-warm, only to avoid the one-frame first-dispatch warm-up in a
latency-critical spot.
## What compute is holding, and why a key names nothing
Every buffer, volume, storage target, history pair and sampler a dispatch can
bind is filed under a key, and `compute.observe()` lists all of them with what
each costs:
```lua
local r = compute.observe()
print(r.totals.count, r.totals.bytes)
for _, res in ipairs(r.resources) do
print(res.key, res.kind, res.bytes, res.owner.name)
end
```
A row carries the key verbatim — the same string a dispatch names it by and a
dispatch-failure message prints — plus its `kind`, its `bytes`, its extent and
`format` where it has them, the `usage` bits it was created with, and the frame
it was created on. `owner` is read back out of the key
(`<shader-guid>::<name>#<serial>`), so a resource nothing has ever dispatched
over still names the shader that made it. `compute.resources(ref)` narrows to
one shader's — including the `<shader-guid>::__params` uniform the compile
created for a `params:` block, which the shader owns like any other resource.
`r.totals.bytes` is the `compute` figure of `renderer.gpuMemory()` — the two are
read off the same registries, so a listing accounts for the category exactly.
The same reading is served at `/zero/runtime/compute`.
When a key names nothing, `compute.diagnose(key)` says which of the states the
inventory distinguishes it is in, from the closed set `compute.absentReasons()`
enumerates:
| reason | what the inventory read |
|---|---|
| `resident` | a resource is filed under exactly this key; the row is on `resource` |
| `replaced` | the owner holds the same name at a different serial — `current` names the live key |
| `nameUnused` | the owner holds resources, none under this name |
| `ownerAbsent` | no live resource carries this key's owner |
| `unowned` | the key carries no owner segment, and nothing is filed under it |
| `notPublished` | no renderer has published an inventory, so no key can be answered for |
So a key out of `[compute] dispatch '…' failed` resolves against what exists,
and a typo reports which part of it the engine could not match rather than
coming back empty.
A reason is the inventory at the moment the call read it. The reading is
republished on a frame where a registry gained or lost an entry, so a resource
created and diagnosed inside one script sees the reading from before it was
made; wait a frame and ask again.
## Discovery
- `asset.list("computeShader")` — every registered compute shader.
- `asset.inspect("<name>")` — status, source, parse errors, this README.
- `computeRef:getBindings()` — the parsed `bindings.yaml` schema
(`{ bindings, params }`).
- `compute.programState(ref)` — whether the program is compiled, still
compiling, or failed, and why.
- `compute.observe()` — every GPU resource compute holds, and what it costs.
- `compute.diagnose(key)` — whether a key names a live resource, and why not.
- `profiler.gpuFrame()` — what each dispatch of this shader spends on the GPU.
A dispatch is timed under `compute.<identity>` — the same identity
`asset.resolve` takes, so a timing row names the shader that produced it.
## Common pitfalls
- **Compute shaders don't render** — verify output via a buffer readback or a
debug pass, not a screenshot.
- **`ref:compile()` returns before the program exists** — the pipeline is
built on the render side; `compute.programState(ref)` says when it is
`"ready"`, and a dispatch issued before that is dropped.
- **A dispatch call returning true means queued** — ask `ref:status()` whether
it ran.
- **A destroyed buffer is refused where it is bound** — a handle outlives its
storage, and `buf:alive()` reports which.
- **Binding order is the contract** — `buffers` and `resources` bind in
`bindings:` list order; reordering the list reorders the bindings.
- **Don't write `@group`/`@binding` in `shader.wgsl`** — the engine owns them;
re-declaring is the fastest way to a layout mismatch.
- **Don't infer a mesh's vertex stride** — declare `kind: vertices` and use the
accessors. A wrong stride writes positions correctly and normals into the
wrong word, which renders as flat lighting rather than as broken geometry.
- **Storage-texture format must be storage-compatible** — `r32f` / `rgba8` /
`rgba16f` / `rgba32f`; others are rejected at compile.
- **A key that comes back empty is not the same as one that failed** —
`compute.diagnose(key)` separates a name never used from a generation that
was replaced, and names the live key in the second case.
## Related types
- `.shader` — render-domain shaders (surface, sky, post-process, screen) and the
legacy `@domain: compute` fallback.
## In the Inspector
Selecting a compute shader opens its **Compute** section: whether its program is ready (and why not), how many dispatches it has run and failed in this session (and the last error), tables of the bindings and params its `bindings.yaml` declares, and openers for `shader.wgsl` and `bindings.yaml`.
# texture
An **image asset** — the raw bytes of a `png` / `jpg` / `jpeg` / `hdr` /
`ktx2` / `webp` / `bmp` / `tga` file. Loose image files under a
`textures/` directory classify as `texture`.
> New to how a texture exists as an asset, as CPU-side pixels, and as a live GPU
> texture (and how `renderer.texture.*` and render targets move between them)?
> Read `core/resource-model` first.
`texture` is a first-class assetType (not a bare plural-dir category) so
that:
- a texture has a stable asset **identity** and an explicit `asset_type`
link, and
- a material that references a texture records a real `.refs` edge to it
— which is what lets the CPU-residency system cascade from a material to
the textures it actually uses.
## CPU residency vs GPU residency
A texture can be resident two fundamentally different ways, and they must
not be conflated:
- **CPU residency** (this assetType): the raw image **bytes in memory** —
readable, hashable, decodable. You can operate on the bytes.
- **GPU residency**: those bytes uploaded to the device as a
`wgpu::Texture` the renderer binds/samples. Byte-level reads are **not
possible** on the GPU variant — that is simply how the device works. GPU
residency is managed separately (`TextureRefCounts` → `drop_texture`)
and is **not** part of this assetType.
Same texture identity, two separate residency states, two separate
operation sets, two separate reference counts. See
`docs/specs/runtime-asset-copying.md`.
## Internal layout
A `.texture/` is permissive (`allow_unlisted: true`). `asset.create("texture",
name, ...)` and the **texture importer** (which creates through it when a loose
raster image lands in `/source/`) produce this shape:
```
<name>.texture/
source.<ext> the retained source raster — see below
source.ztex the full-resolution texels a cook dropped some of — see below
settings.yaml the texture's settings — see below
data.ztex canonical pre-encoded + pre-mipped payload (ZTEX magic)
.metadata what data.ztex holds and was encoded from
```
`asset.create` keeps a copy of the image bytes it was given as `source.<ext>`;
the importer moves the uploaded image in under its own name instead
(`foo.png` stays `foo.png`). Either way it is the texture's retained source:
rewriting it re-encodes `data.ztex` from the new pixels, and a rewrite carrying
the bytes `data.ztex` was already encoded from changes nothing.
`data.ztex` is the **preferred primary**: when present the renderer resolves
and uploads it verbatim — no re-mip. When absent the primary falls through to
a raster image in the folder, so a container holding only an image file reads
that image.
(`data.tex` is the pre-rename legacy payload name — still resolved for
existing assets; new content writes `data.ztex`.)
That fallthrough takes the lowest-named raster image in the folder and never
the generated `preview.png` thumbnail, which is rendered from the payload. A
container that lost its encoded payload and holds no other image has no
primary: `asset.diagnose(ref)` reports `noPrimaryFile`, `asset.validate(ref)`
reports `texture.no_payload`, and `renderer.texture.loadCpu` refuses it.
`asset.primaryFile(ref).path` names the file the resolution landed on; the
asset-system guide covers `diagnose`.
#### `settings.yaml` settings
A texture's settings are declared in `settings.luau` and live in its
`settings.yaml`. `asset.create` stamps them when the texture is made, and
`texRef:setSettings({ ... })` (or `asset.setSettings(ref, patch)`) changes
them. Editing an encode-relevant one re-runs the encode against the retained
source and rewrites `data.ztex`. A texture whose settings were stored under an
earlier schema reads with the same meaning, and its first local edit rewrites
them into `settings.yaml` under the fields below.
```lua
local tex = asset.create("texture", "hero_albedo", {
bytes = png, ext = "png",
settings = { maxDimension = 1024 },
})
tex:setSettings({ uastcRdo = "medium" })
```
| key | values | default | meaning |
|-----|--------|---------|---------|
| `textureType` | `color` / `normalMap` / `mask` / `sprite` | `color`, or guessed from the name | what the texture holds, recorded in the payload. `normalMap`: tangent-space normals — when `generateMipmaps` builds the chain, every level of it, the base included, is renormalised to unit length; with `generateMipmaps = false` the one stored level is the source as given, and the chain the GPU builds from it at upload is a plain box filter. `mask`: linear data (roughness, metallic, occlusion, height, masks). `sprite`: a 2D image with transparency. A new texture's type is guessed from its name — `_normal` / `_nrm` / `_n` / … → `normalMap`, `_rough` / `_metal` / `_ao` / `_height` / `_mask` / … → `mask` — unless it is given. |
| `colorSpace` | `srgb` / `linear` | follows `textureType`: `srgb` for `color` and `sprite`, `linear` for `normalMap` and `mask` | how the stored values are read when sampled. `srgb` for albedo/emissive/base-color, UI and sprites; `linear` for normal/RM/AO/height/mask data. |
| `compression` | `uastc` / `rgba8` / `rgba16` / `rgba32f` | a new texture: `uastc`, a `sprite` `rgba8` | what the texels are stored as — see "What each compression stores" below. |
| `effort` | `fastest` / `fast` / `thorough` | `fastest` | how long a `uastc` encode searches for each block — see "Block compression" below. |
| `uastcRdo` | `none` / `low` / `medium` / `high` | `none` | how far a `uastc` encode moves from the source to make a payload that compresses smaller on disk and over the network — see "Block compression" below. |
| `generateMipmaps` | `true` / `false` | `true` | bake the full mip chain into `data.ztex` at encode time. |
| `maxDimension` | integer, `1` to `8192` | a new texture: `4096` | the longest side the encoded texture may have; a larger source is downsampled to fit, and a `uastc` texture's longest side is the largest power of two within it. A value past 8192 is refused. |
| `filter` | `linear` / `nearest` | `linear` | sampler filtering recorded in the payload. A material slot and a UI image widget sample the texture with it. A post-process effect's texture property, a render pass's `@texture` input and a compute shader's `texture_2d` binding sample through a sampler of their own (the effect's `postprocess.setSampler`, the pass's, the compute shader's named `sampler` binding), which this setting does not change. |
| `wrapU` | `repeat` / `clamp` / `mirror` | follows `textureType`: `clamp` for `sprite`, else `repeat` | how a material samples the texture past its left and right edges: tiled, the edge texel held, or mirrored. Recorded in the payload. |
| `wrapV` | `repeat` / `clamp` / `mirror` | follows `textureType`: `clamp` for `sprite`, else `repeat` | the same, past its top and bottom edges. |
| `anisotropy` | `world` / `1` / `2` / `4` / `8` / `16` | `world` | samples taken along a surface seen at a grazing angle. `world` follows the `render.anisotropy` world setting (`renderer.setAnisotropy`); a number fixes it for this texture, clamped to what the device supports. A `nearest` texture samples with 1. A write may give the number itself (`anisotropy = 8`); it is stored as the string. Recorded in the payload. |
| `alpha` | `input` / `premultiplied` / `none` | `input` | what the encode does to alpha. `input`: kept as the source has it (straight alpha). `premultiplied`: colour multiplied by alpha — decoded to linear light, multiplied and re-encoded for an `srgb` texture, multiplied as stored for a `linear` one — the source a material with the `premultiplied` blend mode (`src + dst * (1 - src.a)`) composites. `none`: every texel opaque, colour kept. |
| `alphaIsTransparency` | `true` / `false` | follows `textureType`: `true` for `sprite`, else `false` | fill every fully transparent texel with the average colour of its non-transparent neighbours, spreading outward, so bilinear filtering and mip averaging never pull black into the edge of a transparent area. Alpha stays 0. Runs before `alpha` and before the mips. |
| `keepCpu` | `true` / `false` | `false` | keep the decoded pixels in the CPU store after the GPU upload — see below. |
The type's colour space, `alphaIsTransparency`, `wrapU` and `wrapV` are
stamped when the texture is created, and a later write that changes
`textureType` moves them with it — unless the same write names them. A texture whose settings predate
`textureType` reads as `color`, with `alpha = input` and no transparency fill,
which is what its payload holds.
A cook that drops texels — a `maxDimension` smaller than the source, or a
`uastc` cook resampling a side to a power of two — keeps the full-resolution
input as `source.ztex` (one RGBA8 level) when the container holds no source
image, so raising `maxDimension` later re-encodes from every texel. A cook
that drops nothing keeps nothing extra. A texture made from raw pixels whose
cook dropped nothing keeps its payload as its only source, so a settings
change re-encodes from that payload read back with straight alpha: what an
earlier encode discarded stays discarded, after `alpha = none` its alpha is
opaque, and a `uastc` payload re-encoded is the blocks' texels, not the
pixels first given.
A new texture's settings start from the texture type's own defaults —
`uastc` with a `maxDimension` of 4096; `rgba8` for a `sprite`; a 16-bit PNG
or `.hdr` source left to the schema's `rgba8` unless a layer names a
compression — and a world's Preset Manager rows
for `texture` override them (a world that ships at 2048, say), then an
importer's settings, then the `settings` the create names.
`filter`, `wrapU`, `wrapV` and `anisotropy` say how the texture is sampled,
not what its texels are. A write that changes only those rewrites the
payload's header (`renderer.texture.withSampler`): every level keeps its
bytes, and no preview is rendered, because no pixel changed. Every material
slot samples through its own texture's state, so two textures on one material
can wrap and filter differently. UI image widgets honour `filter` and draw each
image over its own bounds, so the wraps apply to materials. A post-process
effect, a render pass `@texture` input and a compute shader sample through
samplers of their own, so none of the four settings reaches them. A texture whose
payload predates wrap and anisotropy reads `repeat` / `repeat` / `world`,
which is how it has always been sampled.
`keepCpu` is a lifecycle setting, not an encode input — it never re-runs the
encode. It acts on an already-materialised texture right away instead: `true`
loads the decoded pixels into the CPU store when the texture is GPU-resident,
`false` drops a resident CPU copy.
The `data.ztex` payload format is `zero_texture::blob` (`ZTEX` magic +
32-byte header + mip levels); the CPU encoder is exposed to Luau as
`renderer.texture.*` and consumed by the texture importer and this assetType.
#### What each compression stores
| `compression` | In `data.ztex` | On the GPU | Limits |
|---|---|---|---|
| `uastc` | UASTC 4x4 blocks, whole mip chain, one byte per texel, each level compressed for storage. | Transcoded at upload to a block format the adapter samples: `Bc7RgbaUnorm[Srgb]` where it samples BC textures (desktop native, desktop WebGPU), ASTC 4x4 where it samples ASTC and not BC (phones, a browser on one), ETC2 RGBA8 where it samples only ETC2, each one byte per texel; RGBA8 at four bytes per texel on an adapter that samples none of them, and for a texture with a side under four texels. | each side is resampled to the nearest power of two (halfway rounding up), nearest-neighbour for a `nearest` texture. |
| `rgba8` | From an image with `generateMipmaps = false`, a `maxDimension` the image fits within, `alpha = input` and `alphaIsTransparency = false`: the source PNG / JPEG / WebP itself, decoded at load. Otherwise raw 8-bit RGBA with the encoder's box-filtered mip chain. | `Rgba8Unorm` / `Rgba8UnormSrgb`, four bytes per texel. | none |
| `rgba16` | Raw 16-bit unsigned normalized, one level. An image is decoded at its own depth: a 16-bit PNG keeps every bit, an 8-bit channel `v` is stored as `v * 257`. The frames of an animated image are decoded at 8 bits. | `Rgba16Unorm` where the adapter grants 16-bit normalized textures (native); half float (`Rgba16Float`, about 11 significant bits) where it does not (every browser). | one level, no `maxDimension`, `linear` only. |
| `rgba32f` | Raw 32-bit float, one level. An image channel is stored as its value over the channel's maximum. | `Rgba32Float`. Where the GPU filters 32-bit float, every consumer samples it. Where it does not (every browser): a material slot draws the shader's declared default; a UI image draws nothing; a render pass naming it as an `@texture` input is skipped; a compute shader that declares no sampler binds it and reads it with `textureLoad`, and one that declares a sampler refuses the dispatch — each logging once, naming the texture and its format. CPU reads (`:load()`, `renderer.texture.decode`) return every bit on every device. | one level, no `maxDimension`, `linear` only. |
A high-precision compression turns `generateMipmaps` off, `maxDimension` to
8192 and the colour space to `linear` when the same write does not name them,
and refuses a write that names a contradicting value.
A payload of BC7 blocks, written before `uastc` existed, stays as it is:
`Bc7RgbaUnorm[Srgb]` where the adapter samples BC textures, re-encoded as it
loads into ASTC 4x4 or ETC2 where the adapter samples those instead, and
decoded to RGBA8 where it samples none. Its settings read
`compression = uastc`, what an encode of it now asks for, while
`texRef:info()` reports the `bc7` payload it holds.
#### Block compression
`compression = "uastc"` stores every mip level as UASTC blocks — sixteen bytes
per 4x4 texels — a format no GPU samples directly but every one can be handed:
at upload each level is transcoded to a block format the adapter samples, BC7
on a desktop GPU and ASTC 4x4 on a phone's (ETC2 on one that samples ETC2
alone), so one payload is resident at one byte per texel on each, and RGBA8 on
an adapter that samples none; `renderer.textureMemory().blockFormat` names the
format this adapter holds it in. Only the levels a device keeps are
transcoded: under a texture-size cap (`renderer.setMaxTextureSize`) a texture
is uploaded from the first level of its chain within the cap. Compression is
lossy, which makes it the choice for colour, normal and detail maps; `rgba8`
holds a texture exactly, which is what pixel art and a mask whose exact codes
matter need.
`effort` is how long the encode searches for each block. `fastest` tries one
candidate for an opaque block, `fast` takes about 6 times as long and
`thorough` about 17 times, each landing closer to the source texels. What the
GPU holds is the same size at every effort, and so is the time a load takes.
`uastcRdo` trades accuracy for a payload that compresses smaller: `none`
encodes each block as close to the source as the encoder finds, and `low`,
`medium` and `high` let a block move further from the source when a nearby
block's bytes would let the payload compress better. What the GPU holds is the
same size either way; what moves is the size of `data.ztex` on disk and over
the network, and the encode time, which a pass more than doubles.
The encode runs on the CPU when the texture is created or a setting that
decides its texels changes. A call from a task that can yield cooks off the
frame and the task waits for it, so the world keeps running: a 1024x1024
texture with its mip chain takes about a second on a desktop CPU.
A texture whose settings predate `compression` (stored before it was a
setting) is healed by its first local edit: a `nearest`-filtered one becomes a
`sprite` in `rgba8`, an `rgba16` or `rgba32f` one keeps its format, and every
other one becomes `uastc` and is re-encoded; an older "no cap" becomes a
`maxDimension` of 8192. Loading one changes nothing, and an edit arriving from
another session or a texture installed from a library is never healed. A
texture whose settings say `rgba8` is never compressed.
## Reading an asset from its ref
`texRef:settings()` reads the container's settings with every schema default
filled in and `texRef:setSettings({ maxDimension = 1024 })` patches them;
`texRef:load()` decodes the payload's pixels into the CPU store for per-pixel
access, `texRef:handle()` puts the texture on the GPU under the asset's own
guid, and `texRef:preview()` renders it as a swatch.
`texRef:info()` reads the compiled `data.ztex` payload's header: the format it
was compiled to — also as its `compression` and `colorSpace` — the
`textureType`, `alpha` and `alphaIsTransparency` it was encoded under, its width and height, its mip and array-layer counts, the
sampler recorded in it (`filter`, `wrapU`, `wrapV`, `anisotropy`), and, for an animated sequence, each layer's
display time and the length of one pass:
```lua
local info = texRef:info()
print(info.width, info.height, info.format, info.mipCount)
```
It answers off that payload's own header, so a compiled texture reports how big
it is for a header read where `load()` decodes its pixels and `handle()` uploads
them. A container whose primary is a source image answers `(nil, err)`, and
`load()` reads its size. The `compression` and `colorSpace` it reports are what
the payload holds; the settings table holds what the encode was asked for.
## In the Inspector
Selecting a texture opens its **Texture** section right below the asset's
identity, then its Settings. The section draws the encoded texture through the
texture's own sampler, so a `filter = "nearest"` texture reads crisp at every
zoom. The zoom row offers **Fit** and each integer zoom (1×, 2×, 4×, 8×) whose
drawn size fits 512 px; a 128 px texture offers up to 4×, and one wider than
512 px offers Fit alone. Below the view, the section lists every field of the
`data.ztex` header (`texRef:info()`) — size, format, mip levels, filter, layers,
and a sequence's frames and duration — and the GPU memory the encoded mip chain
takes across its layers. The filter and the other encode settings change in
the Settings section; the Texture section reports the re-encoded result.
# Service (asset type)
A **service** generates content you don't have yet — a 3D mesh, an image, a PBR
material, a sound effect, a humanoid animation, a navigable splat world — from the
inputs each operation declares, landing it as an asset in your world. When
nothing in `asset.list` fits what you're building, a service is where new content
comes from.
A `<name>.service/` is a **declaration**, not code. The asset type ships the whole
runtime — the metered invoke, the submit → poll → download → write pipeline, the
async generation handle, error handling — in its `shared.module/`. An instance only
declares its surface: which provider **offering** it meters, and the **operations**
it offers. There is no HTTP, polling, credit, or secret code in a service.
## Using a service
Every service is used the same way, whatever it generates:
```luau
local mesh = asset.resolve("mesh_gen", "service")
mesh:operations() -- callable operations, each with its inputs + credit cost
mesh:cost() -- credits the next run costs (estimate)
mesh:balance() -- credits you have
local g = mesh:invoke({ prompt = "a wooden treasure chest" })
--> { id, task, asset_path, operation } -- async: the run is still going
local row = tools.use("services", "status", { id = g.id }) -- poll until it settles
-- once row.status == "completed", row.asset is the spawnable asset
```
`:invoke` returns immediately with a handle; the run finishes in the background. The
`services` toolbox (`status`, `jobs`) is the agent-facing way to track a run to
completion, and a completed row's `asset` is the asset to spawn — see the
generating-assets-and-content guide. The handle's `asset_path` is where the run
directs the raw generated file, which the importer turns into the asset that row
names.
A run outlives the engine that started it. The gateway keeps the job and its
result for hours after the charge, and the run keeps its own record in the world
— what it was asked for, the job doing the work, and the step it had reached — so
when the world next loads, every run that did not finish is picked up where it
left off and lands its asset the way an uninterrupted run does. Nothing is
submitted, or paid for, a second time, and nothing is asked of the caller.
A service with several operations selects via `input.operation`
(`mesh:invoke({ operation = "from_image", image = "/zero/source/.../ref.png" })`);
a single-operation service just takes its input.
## Authoring one
```luau
-- <name>.service/init.luau
local Service = asset.containing(__FILE__).modules.shared
return Service.define({
name = "<name>",
description = "Generate <thing> from a text prompt.",
offering = "<provider>/<name>", -- the offering ZeroMind meters
output = { kind = "mesh", ext = "glb", dir = "/zero/source/generated/meshes" },
operations = {
generate = {
description = "What this makes, agent-facing.",
input = { prompt = { type = "string", required = true } },
cost = 5,
steps = { … }, -- the pipeline (see below)
result = { url = "$url" }, -- the framework downloads + writes it
},
},
})
```
An operation takes exactly the fields it declares in `input`, plus the `operation`,
`asset_path` and `durable` the framework itself reads. A call carrying any other field is
refused by name — ahead of the credit pre-flight and ahead of any endpoint — with
the fields the operation does take named in the message, so a field the steps have
no `$ref` for costs a message rather than a run. An operation that declares no
`input` states nothing about its surface and takes any field.
An input declaring `enum = { "2k", "4k", "8k" }` accepts those values and no
others, and the set is published on the input so a reader learns it from the
listing rather than from a refusal. A value outside it is refused with the same
timing as an undeclared field — before the credit pre-flight, before any
endpoint. That timing is the point where a pipeline spends per step: a value the
last step's upstream rejects is one the earlier steps were already charged for.
An input declaring `dimensions` takes an image size as a `WIDTHxHEIGHT` string
in pixels, inside every bound the declaration states: `multipleOf` (each edge),
`maxEdge`, `minPixels` / `maxPixels` (width times height) and `maxAspect` (the
long edge over the short one). The words `also` lists (`also = { "auto" }`) are
accepted beside a size. It is refused with the same timing for any other value,
and the refusal names every bound, so a size the provider would refuse costs a
message:
```luau
size = {
type = "string",
dimensions = { multipleOf = 16, maxEdge = 3840, minPixels = 655360, also = { "auto" } },
}
```
A set may hold strings or numbers (`enum = { 24, 30, 60 }`), and a value matches
only a member equal to it: the number `30` and the string `'30'` are different
values, and the refusal quotes strings and leaves numbers bare so it reads that
way. Whenever the provider honours a fixed set of values for an input, the set
is its `enum` and the input's `desc` says what the choice does to the result,
so the values a reader learns and the values the call accepts are one list.
An input declaring `min` / `max` accepts numbers inside that span and is refused
with the same timing for a figure outside it. Either bound stands on its own:
`min` alone is a floor, `max` alone a ceiling. Both are published on the
input beside `enum` and `default`. A span an upstream honours belongs here for
the same reason a value set does: a figure the pass that reads it refuses is one
every earlier pass has already been paid for.
### Declaring the pipeline
`steps` is an ordered list of metered calls. Each step:
- `call` — the offering's logical endpoint name.
- `body` / `params` / `headers` — templated. `"$name"` injects an input or a prior
step's bound value; `"${name}"` interpolates inside a string (a missing value
drops the key); `"$name?"` is optional. `{ fromFile = "$path", dataUri = "image/png" }`
sends a local asset; `{ firstOf = { a, b } }` uses the first present value;
`{ scale = "$n", by = 1000 }` multiplies a number; `{ truncate = "$text", to = 64 }`
clamps a string to at most that many characters, for an upstream that caps a
field's length; `{ whenSet = "$n", use = true }` sends `use` when `$n` was
named and drops the key when it wasn't, for an upstream that reads one field
only while a companion flag is on — naming such a field alone is otherwise
accepted, charged for, and ignored.
- `poll` — when the call submits a job: `{ endpoint, param }` plus optional
`idFrom` / `statusFrom` / `done` / `fail` / `doneWhen` / `failWhen` / `progressFrom`
overrides (sensible defaults cover the common providers).
- `bind` / `bindFrom` — name the value later steps reference; `bindFrom` extracts it
(a dotted path, a fallback list `{ "a", "b" }`, or an array-find
`{ find = "assets", where = { type = "x" }, get = "url" }`). For a polled step the
default bind is the submitted job id.
`result` is either `{ url = "$bound" }` (download the URL and write it) or
`{ bytes = "$bound" }` (write bytes a step returned directly).
`output` sets where the asset lands (`<dir>/<safe(prompt)>.<ext>`); a caller's
`asset_path` overrides it. The run writes the file at that path and imports it
like any other, so the completed row names the asset the importer produced. A
path ending in an asset type's extension (`clips/door.soundClip`) names that
asset: the file is written beside it under `output.ext` (`clips/door.mp3`) and
imported into it. Two destinations keep the written file as the result: one
inside another asset's folder, which is that asset's own content (a `.package`
holds assets of their own, so a file inside one imports as usual), and a file
no importer claims. The derived name is a
truncation of the request, so several runs can derive one name — the same line
under two voices, two prompts that open on a shared phrase. The framework hands
each run a name no other run holds and no file in `<dir>` already spends,
appending `_2`, `_3`, … when it must, and the handle's `asset_path` is the name
that run will write. So a set of related generations can run at once and each
result is readable at its own path. The written file is then imported, and the
name is derived by the rule the importer names an asset with, so the name a run
reserves is the name its finished asset carries.
Read `mesh_gen` as the worked template:
`asset.resolve("mesh_gen","service"):getDefinition()`.
## Discovery
- `asset.list("service")` — every registered service.
- `asset.resolve("<name>","service"):info()` — offering, output, operations.
- `asset.resolve("<name>","service"):operations()` — each operation's inputs + cost.
## Related types
- `.module` — reusable library code you `require` and call.
- `.tool` — an agent-callable function that composes multiple engine steps.
- `.component` — per-entity behaviour.
## In the Inspector
Service: what the service does and each operation it offers, with its credit cost and inputs, parsed from its declaration without running it. Invoking an operation spends credits, so it is not offered here.
# serviceRun
The durable record of one service generation — what was asked for, which
gateway job is doing it, and what state that job reached.
A generation is charged when it is submitted and then runs for minutes on the
gateway, which keeps the job and its finished result for hours afterwards. The
engine running the generation is the part that does not last: it can be
restarted, rebuilt or closed while the provider is still working. A run asset is
what survives that, so the answer to "what did I start, and where did it get to"
outlives the process that asked.
Every run carries the `jobId` its work is running under. That is the handle the
result is reached by when a run's engine did not live long enough to collect it
— `services.attach(jobId)` finishes a job that was already paid for, at no
further cost.
## Shape
`run.json` holds the record, and the same fields are mirrored onto `.metadata`
so a run is findable by query without being opened:
- `id` — the run handle `services.generate` returned
- `service`, `operation`, `prompt` — what was asked for
- `jobId` — the gateway job the work is running under
- `status` — `submitted` / `polling` / `completed` / `failed`
- `assetPath` — what it produced, once it has
## Reading them
`services.jobs()` lists runs and `services.status(id)` reads one. Both answer
from these records, so both keep answering after a restart.
## In the Inspector
Run: which service and operation the run asked for, the status it reached, its gateway job, its error when it failed, and a link to the asset it produced. The ref answers `record()`, `jobId()` and `finished()`.
# Scene (asset type)
A scene is a saved, loadable snapshot of an entity scenegraph inside a
world: the entity hierarchy, transforms, components, lighting, and a
declared `player` intent, plus an auto-discovered startup script. A scene
is the unit of "level" or "screen" — a title screen, a lobby, a gameplay
area, and an end-of-game summary each get their own scene.
Scenes load as **layers**. One root scene is active at a time; additional
scenes can load additively as overlays on top of it. Each scene owns its
own multiplayer relay room. Switching scenes is a local call: the client
that makes it leaves the old scene's room and joins the new scene's room.
## When to use one
- You want a savable, re-loadable snapshot of an entity scenegraph plus
its lighting and player setup.
- You want a runnable starting state for a level or screen.
- You want a scenes-as-data flow: `layers.load("lobby")`, edit live, then
`layers.active:save()` to publish the edits back to the scene.
For a reusable entity assembly (a prop, a vehicle, a UI panel) that many
scenes spawn into themselves, use a `.bundle`. A scene is a whole-world
snapshot; a bundle is one prefab that lives inside scenes.
## Folder shape
A scene asset is a folder ending in `.scene`. Its identity is the folder
name with the suffix stripped (`Lobby.scene` → `Lobby`).
- `scene.json` — the scenegraph: `entities[]`, lighting, and the
top-level `player` intent. **Required.** Written by the engine — a build,
a save, a human dragging something in. Not hand-edited.
- `build.luau` — what the scene is made of, written as code. Runs while you
author; saving bakes its result into `scene.json` (see Building a scene).
- `entrypoint.luau` — the startup script. Auto-discovered as a sibling of
`scene.json`; define lifecycle callbacks here (see The entrypoint).
- `<name>.<type>/` — an asset the build makes, authored here by `build.asset`
(see The assets a build makes), alongside `.build.assets`, which records
which `build.luau` produced each of them.
- `prefabs/` — optional subfolder for scene-local bundles.
- `scripts/` — optional subfolder for scene-local Luau helpers, required
from `entrypoint.luau`.
- `README.md` — optional per-scene notes about THIS scene. Author one only
when there is scene-specific detail worth recording; the general scene
model lives here, in `guides { path: "types/scene" }`.
`scene.json` is version 7. It carries `"format": "scene"`,
`"version": 7`, an `entities[]` array, and a top-level `"player"` string
intent.
## The `player` intent
Every scene declares how it handles players with a top-level `player`
field in `scene.json`:
- `"spawns"` — the scene carries an authored player setup, and the engine
spawns a player for each connecting user from it. This is the default
for a freshly created scene.
- `"none"` — the scene spawns no player and authors no camera. Author your
own Camera entity for the view (menus, UI-only screens, cinematics).
### How `"spawns"` works
A `"spawns"` scene authors two things in `scene.json`:
1. A **PlayerPrototype** — an entity carrying the `PlayerPrototype`
component, whose `body` field names a child entity (the body). The
body carries an avatar (an `Asset` pointing at an avatar, e.g.
`@builtin::avatars.humanoid`). A `CameraRig` child carries a `Camera`
with a camera behavior (e.g. `orbital_follow`). The prototype root is
authored `PrototypeOnly` so it exists as a clonable template.
2. A **PlayerSpawn** — an entity carrying the `PlayerSpawn` component,
whose `prototype` field names the PlayerPrototype to instantiate and
whose transform is where players appear.
The scaffolded scene groups these under two organizing entities,
`PlayerSetups` (holding the prototype) and `Spawns` (holding the spawn),
so the authoring tree stays legible.
On each user join — entering play, and each subsequent connect — the
engine runs the spawn for that user:
- It clones the PlayerPrototype subtree.
- The clone root becomes the user's **internal identity** — a registry-only
entity named `user` carrying the `UserIdentity` component. The identity
is the anchor for who the player is; it has no world presence.
- The body named by `PlayerPrototype.body` is adopted as the user's
**avatar** — their visible presence in the world — and placed at the
PlayerSpawn's world transform. Move the PlayerSpawn (or drag it in the
editor) to set where players appear.
- The `CameraRig`'s Camera follows the bound avatar.
The player prototype is live in edit mode so you can see and adjust it. In
play mode it is deactivated and marked internal — it stays a clonable source while
each user gets their own clone.
### Reaching the live player
The player surface lives on the root scene's registry,
`layers.active.players`:
- `players.localPlayer` — this client's player, a curated handle.
- `players.localReady` — `true` once the local player's avatar is bound
(or the scene opted its avatar out).
- `players:list()` / `players:count()` — the players connected in this
scene's room.
- `players:get(userId)` — a connected player by account id.
- `players:ownerOf(avatar)` — the player whose body is a given avatar.
A player handle is a data record about who the player is, plus a link to
their body:
- `player.avatar` — the body's entity ref. Act on the body through it
(`player.avatar.position`, raycasts, rig access).
- `player.isLocal` — whether this client owns the player.
- `player.ready` — whether a live avatar is bound.
- `player.userId` / `player.identity` / `player.displayName` — the
player's account identity.
- `player.avatar = ref` — bind a live body entity as the player's body
(assign nil to clear). To use a `.bundle` / `.avatar` asset, spawn it
into the world first, then bind the resulting entity.
The player's identity entity is the internal anchor; the handle exposes the
body (`player.avatar`) and the player's data, and reaching for
`.entity` / `.id` / `.component` raises with a redirect to `player.avatar`.
## Building a scene
`build.luau` declares what the scene holds. It is ordinary engine code —
`entity.spawn`, `component.add`, transform writes, `for` loops, a `require`
of a module that computes a layout — and what it creates is what ends up in
the scene.
```lua
function content()
for i = 0, 4 do
local crate = entity.spawn("crate")
crate.localPosition = { i * 2, 0.5, 0 }
crate.component.add("Model", { model = asset.resolve("cube", "mesh") })
end
end
```
The build runs while you author, in **edit** mode, and what it created lands in
the live scene. Saving the scene bakes it into `scene.json`, which is what makes
the entities durable content: a human can select and inspect them, they
replicate, and they are there when the world opens without `build.luau` running
at all. Play mode never runs it — in play the entities load from `scene.json`
like anything else the scene holds.
**Editing the file rebuilds the scene in place.** Writing `build.luau` is the
signal; there is nothing to reload, and the rebuild saves. An entity keeps the
id it had, so a reference to it — a spawn naming a prototype, another entity's
component naming this one — survives every rebuild. Add a crate to the loop and
the other four do not move.
The write returns as soon as the file is on disk and the rebuild finishes behind
it, so what it landed comes back as a notice:
```
[info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main",
editorOnly="1" }
```
An edit saved while a rebuild is still running is an edit to code that rebuild
has already read, so it gets a rebuild of its own once that one finishes, and
says which it was:
```
[info] a write to build.luau arrived during a rebuild and was rebuilt after it
{ content="7", scene="scenes.main", editorOnly="1" }
```
Several edits saved during the same rebuild get the one run after it, which
reads the file as it stands then.
A scene that declares a build also runs it when it **loads** in edit, so the
scene shows what the code says now, including an edit made while the world was
closed. A load whose `.build.state` records the current script reads
`scene.json` as the build and runs nothing. When the load does run it, a
world's own scene saves the result, unless the scene holds unsaved edits: those
stay the author's to keep or discard, and the file write waits for their save.
A library scene (one under `/libs/`, the `@builtin` library included) is read
by its load: the build lands in the live scene and its files stay as the
library states them. Play reads `scene.json`, so it comes up without that build
until `:build()` saves it.
### The two surfaces
- `content()` — the scene's own entities. Present in play.
- `editorOnly()` — entities present while authoring and absent in play. They
carry the `EditorOnly` participation the runtime deactivates and hides when
play begins, and they are baked too, so a collaborator opening the world sees
the same ones. Anything an author needs to see and a player does not goes here
— an alignment guide, a spacing marker, a debug volume.
Both are optional. A scene with neither has no build.
### What a rebuild touches
Only the entities the build itself placed. Anything a human dragged in, or a
tool placed directly, is invisible to a rebuild and never moved or removed.
Within what it owns, the build is authoritative: an entity the code stopped
emitting is despawned, a component it stopped adding is removed.
The build writes its own name and each entity's place in the hierarchy onto the
entity, and `scene.json` records that pair beside the entity's name and
transform — which is why a rebuild after a reload, in a later session, lands on
exactly the entities it placed the first time without anything having been
remembered.
### When the file did not change
`:build()` runs the build against what it resolves right now — for the case
where something the builder *reads* changed and the file did not: a module it
requires, an asset it resolves. After a write it is unnecessary; the write has
already run it.
```lua
layers.active.asset:build() -- rebuild and save
layers.active.asset:build({ save = false })
```
It answers with how many entities each surface placed —
`{ content = 6, editorOnly = 1 }` — and with nil for a scene that has no
`build.luau`. Called while a build for that scene is already running, it returns
at once with `{ inFlight = true, scene, trigger, startedBy, message }` naming
that build instead of starting a second one; `inFlight` is what tells the two
answers apart.
An operation the bake cannot hold is **refused** rather than applied. A build
accepts what its records carry: entity lifecycle, transforms, hierarchy, names,
visibility, active state, participation mode, network scope, attributes, and
components with their public data. Anything else raises while the build runs,
naming the operation and the build it answered to, instead of leaving the scene
depending on something no reload brings back. When that happens the previous
build stays exactly as it was. A runtime resource a build needs — a mesh it
generates, a texture it writes — is made as an asset instead, below. Everything
else a refusal names goes outside the builder, or into a component the builder
attaches, which runs at play.
### The assets a build makes
`build.asset(type, name, produce)` makes an asset the build's content names — a
mesh a lathe produces, a texture a pattern writes. `produce` takes nothing and
returns the creation parameters `asset.create` takes for that type; the call
returns the asset's `AssetRef`, which is what a component field holds.
```lua
function content()
local tower = build.asset("mesh", "tower", function()
local positions, indices = lathe(profile, 16)
return { positions = positions, indices = indices }
end)
entity.spawn("tower").component.add("Model", { model = tower })
end
```
The asset is authored inside the scene's own folder — `Lobby.scene/tower.mesh`
— and the scene records which `build.luau` produced it in `.build.assets`. So
`produce` runs when the build script changed and never otherwise: a reload
re-runs the build and reuses the asset, while editing the profile re-authors
`tower.mesh` **in place**, keeping its path and its guid. That is what holds the
reference — `scene.json` names assets by guid.
For a part of a scene that several scenes place — or that one scene places many
times with different settings — see `guides { path: "types/sceneModule" }`,
which is the same idea with declared `inputs` a placement sets.
`guides { path: "core/scenes-as-code" }` covers both.
## The entrypoint
`entrypoint.luau` is the scene's **runtime** — what happens while the game is
being played. What the scene *is* comes from `build.luau` above; nothing here
has to construct it.
`entrypoint.luau` is auto-discovered as a sibling of `scene.json`. The
loader runs it in a fresh environment and folds its top-level
`function name(...)` declarations into the matching scene lifecycle event.
Define the callbacks the scene needs — the recognised set:
- `onLoad()` — the scene loaded in **play** mode. Gameplay-start hook,
runs on every connected client.
- `onHostLoad()` — the scene loaded in **play** mode, on the client that
owns the scene's synced content (the relay room creator; offline and
single-player count as host). Fires once. Entities spawned here — and
anywhere downstream — become synced automatically, so this is where
shared world content is spawned: it runs on exactly one peer, and every
other peer receives the entities from the relay snapshot.
- `onEditLoad()` — the scene loaded in **edit** mode. Custom per-scene
authoring tools. Writing this file while the scene is loaded in edit mode
reloads its layer, so the new `onEditLoad` runs after the previous load's
`onUnload`.
- `onUnload()` — before the scene's entities are torn down. Extra cleanup;
engine-managed teardown (entity despawn, resource release) runs
separately.
- `update(dt)` — per frame in play mode, while the gameplay clock
runs.
- `editorUpdate(dt)` — per frame in edit mode, running or paused.
Play-paused ticks neither hook. The scene loader partitions these
strictly on mode; a component's hooks of the same name read
`engine.paused` instead, so the two rules differ — `man components`
has that table.
- `localPlayerReady(player)` — once the local player's avatar is ready.
Gameplay wiring for the local player: attach state, bind UI, swap the
avatar. The avatar is already placed at the PlayerSpawn, so this is for
behavior, not positioning.
- `playerJoined(player)` — a remote player joined this scene's room. Use
for per-player UI (nameplates, greetings). The local player arrives
through `localPlayerReady`.
- `playerLeft(eid)` — a remote player left this scene's room. Receives the
departed entity's id (the entity is already despawned).
Each scene's entrypoint runs in its own environment, so two scenes can
declare the same top-level names without clashing. Keep each callback
short; push per-scene logic into `scripts/` modules and `require` them.
## Layers
Scenes load through the `layers` namespace.
- `layers.load(ref, opts?)` — load a scene. `ref` is a scene AssetRef or
identity string. Without `opts.additive`, this is a **root** load: it
replaces the current root scene. `opts`:
- `additive` — load as an overlay alongside the current root instead of
replacing it.
- `persistent` — keep an additive overlay mounted across mode flips and
root swaps.
- `origin` — a `{x, y, z}` world offset for the overlay's entities.
- `deferred` — spread the entity spawn across frames (for
thousand-entity scenes); the load signals complete only once the
scene has settled.
- `layers.active` — the current root scene proxy (nil before any load).
- `layers.list()` — every loaded layer (root + additive overlays).
- `layers.find(ref)` / `layers.is_loaded(ref)` — look up a loaded layer by
ref.
- `layers.onLoad(cb)` / `layers.onUnload(cb)` / `layers.onBeforeLoad(cb)` —
subscribe to every scene load / unload (distinct from a scene proxy's
own `:on_load` / `:on_unload`, which fire only for that scene).
A root scene carries the `players`, `camera`, and `settings` surfaces;
additive overlays inherit the root's players and lighting and do not carry
their own.
### The scene proxy
`layers.active` (and `layers.find` / `layers.list` entries) returns a
scene proxy:
- Fields: `.guid` (canonical identity), `.name`, `.path`, `.asset`,
`.additive`, `.visible`, `.state` (`"loading"` → `"loaded"` → `"ready"`
→ `"unloading"`), `.ready`, `.players`, `.camera`, `.settings`,
`.entrypoint`.
- `.camera` — a proxy over the scene's primary camera entity; read and
write the live Camera component through it, and
`.camera.behaviors._list()` enumerates the available camera behaviors.
- `:save(opts?)` — publish the live scenegraph to canonical `scene.json`
(see Saving). A convenience that forwards to the scene ASSET's `save`
(`self.asset:save(opts)`): the proxy is the runtime view and owns nothing
on disk, so persistence lives on the asset.
- `:reload()`: unload and reload the same scene (a runtime respawn). A scene
with a `build.luau` runs its build again and saves the scene, so `scene.json`
holds what the reload built and the next play loads it; a library scene's
rebuild lands in the live scene alone.
- `:clearDirty()` — discard unsaved edits and respawn from canonical.
Forwards to the scene asset's `discard` (`self.asset:discard(opts)`).
- `:sceneAsset()` — the durable `AssetRef<scene>` this live layer maps to.
- `:promoteDirty()` / `:writeDirty()` / `:hasDirty()` — manage the dirty
overlay directly.
- `:unload()` — despawn the layer and free its slot.
- `:onReady(cb)` — fire once the scene reaches `ready` (latched: a late
subscriber fires immediately).
## Multiplayer & relay rooms
Every scene has its own relay room, keyed by the world guid, the boot
profile, the mode, and the scene guid. Switching scenes with
`layers.load` runs a room transition — leave the old room, tear down,
join the destination scene's room — all on the client that made the call.
Teardown of the old scene never leaks to peers in the new one.
In play mode connected to a relay, the scene's entities are
host-authoritative: only the room creator instantiates them (marked
synced), and every joiner receives them from the relay snapshot rather
than spawning their own. This is why shared world content belongs in
`onHostLoad` — spawning it in `onLoad` would run on every peer and
duplicate it. Each player's own avatar spawns per-user from the
PlayerSpawn on every client.
Edit mode and offline boots spawn locally and never auto-sync.
## Loading and saving
**Loading** — `layers.load(ref)` for a root scene:
1. Despawns the current root scene's non-persistent entities.
2. Instantiates the entities from `scene.json` (including the player
prototype and spawn for a `"spawns"` scene).
3. Applies lighting and sky.
4. Runs `entrypoint.luau` and fires lifecycle callbacks as their events
occur.
**Saving** — persistence lives on the scene ASSET. `sceneRef:save()`
writes the scene's current state back to canonical `scene.json`; when the
scene is loaded it captures the live scenegraph, and when it is not loaded
it promotes the pending dirty overlay. `layers.active:save()` is the
convenience form — it forwards to the active layer's mapped asset
(`layers.active.asset:save()`). Writing canonical is the only path that
does so: edit ↔ play cycles never save, so hitting play to test never
overwrites the scene. Between saves, live edits accumulate in a per-scene
dirty overlay that the loader merges on top of canonical.
`sceneRef:discard()` throws the overlay away and restores the saved state
— deleting the overlay, and respawning the live layer when the scene is
loaded. It works whether or not the scene is loaded, because the overlay
belongs to the asset, not the runtime layer. `layers.active:clearDirty()`
forwards here. Saves capture entity data, not the entrypoint script —
edits to `entrypoint.luau` and `scripts/` are always preserved.
`opts.to` on `save`/`discard` targets a different scene ("save as"),
taking either a bare name (`"level_2"`) or a full VFS path.
**What a record states.** A component's record in `scene.json` holds the
fields that instance's configuration states: the keys of the table it was
added with (a `build.luau` call's own init table, or the record it was
loaded from) and every field written since, through code, a tool or the
inspector. A field nothing set stays out of the record and takes the
component's declared default each time the scene loads, so changing that
default reaches every entity that left the field to it. To have an entity
follow the default again, remove the field from its record. A field set on a
live entity after its record was made is a change the scene review names
(`sceneAuthoring.changes` lists it as `+ Type.field = value`), and accepting it
writes the field into the record. A scene saved
before records were stated this way holds every field; those values load
and save as they are, since a stored value cannot be told apart from one an
author chose, and a hot reload that changes a default one of them shadows
names it. A stored field the component no longer declares is named by a
`[component.add]` warning when the record loads and left out of the next
save.
## Lighting
Lights are ordinary entities: a directional light, an ambient light, and
a sky are entities carrying `Light` / `ProceduralSky` components in
`scene.json`. Author, move, and tune them like any other entity. If a
scene is missing any of {directional light, ambient light, sky}, the
loader adds a temporary default for the absent one so a scene never loads
dark or skyless; the defaults are never saved into the scene.
Scene-level lighting state that is not an entity — clear color and sky
descriptor — lives under `layers.active.settings.lighting` (`clear_color`,
`sky`); writing those fields updates the engine live.
## Modes
Scenes load in both edit and play mode (see `man modes`). The mode
governs behavior:
- An entrypoint's `update(dt)` runs in play while the gameplay clock
runs, and its `editorUpdate(dt)` runs in edit. A component's hooks of
the same name follow the clock rather than the mode — `man
components` has the four states that produces.
- Player prototypes are live in edit and deactivated + internal in play,
where each user instead gets a clone. `EditorOnly` entities follow the
same edit-live / play-internal toggle.
- `onLoad` / `onHostLoad` fire on a play-mode load; `onEditLoad` fires on
an edit-mode load.
## How to create one
```luau
asset.create("scene", "<Name>")
-- Creates /zero/source/<Name>.scene/ with:
-- build.luau where this scene's content is written. A new one starts
-- with the sun / ambient / sky lighting and the "spawns"
-- player setup, commented for editing — everything else the
-- scene comes to hold is written here too.
-- scene.json what that code produces, baked.
-- entrypoint.luau commented lifecycle-callback stubs.
```
A freshly created scene has a player with a following camera on the first press
of play. It carries no ground, so the first thing to author is what the player
stands on — a `content()` line away in `build.luau`.
## Discovery
- `asset.list("scene")` — every registered scene.
- `asset.inspect("<name>")` — entity count, lighting summary, source path,
and this type README.
## Authoring conventions
- Keep static layout in `scene.json` — geometry, lights, props, the player
prototype and spawn.
- Keep dynamic setup in `entrypoint.luau` lifecycle callbacks — event
listeners, gameplay state, services attached to spawned entities.
- Spawn shared, synced world content from `onHostLoad`; spawn each
player's own gameplay wiring from `localPlayerReady`.
- Set the world's startup scene in `/.world_settings` — that is the scene
the world boots into.
- Y is up; +Z is forward.
- Renaming the folder changes the scene's identity — update every
`layers.load` callsite and the world's startup-scene field.
## Related types
- `.bundle` — reusable entity hierarchies that scenes spawn into
themselves.
- `.service` — cross-scene background work that outlives a scene load.
- `.world_settings` — picks the startup scene and world-level renderer /
physics options.
## In the Inspector
Selecting a scene opens its **Scene** section, read from `scene.json` without loading the scene: how many entities it holds, how many of them are roots (and their names), how players join and the file's format version when it states them, and whether the scene has edits not yet saved.
# Preset (asset type)
A preset is a named set of typed values for one declarer's settings
schema: the texture assetType's, an importer's, a component's, any asset
that declares its own settings. Capture the settings something has now,
then apply them to anything the same declarer governs, instead of setting
the same values by hand each time.
## When to use one
- The same settings recur across many assets or entities (e.g. "pixel
art": every sprite texture with `filter = nearest` and no mipmaps; a
tuned locomotion set for every character of one rig).
- Designers swap configurations without editing code.
- A configuration needs a stable name other content can refer to.
If you're capturing a whole entity assembly, use a `.bundle`. If
you're factoring shared logic (not configuration), use a `.module`.
## Where it lives
- Source: `/zero/source/.../<Name>.preset/`
- Identity: `<Name>` (the `.preset` suffix strips).
- Folder shape:
- `preset.yaml` — the target and the values. **Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields (`title`,
`description`). **Required.**
## The document
```yaml
target: { __ref: "8cc28fc8-ed63-48ee-83a6-15f4192e27e1", type: assetType, name: texture }
values:
filter: nearest
generateMipmaps: false
```
- `target` names the declarer by a guid envelope: `__ref` is its guid;
`type` and the plain `name` tell a person reading the file what it
points at.
- `values` holds only the fields this preset sets. Fields it leaves out
keep whatever the asset or component has.
A component preset has the same shape, its target the component:
```yaml
target: { __ref: "18dfece3-fe1b-4630-b7ad-0996f5043a2e", type: component, name: Locomotion }
values:
walkSpeed: 1.4
runSpeed: 2.5
```
## How to create one
```luau
-- Capture what an asset has now:
local p = preset.capture("hero_sprite", "pixel_art")
-- Capture a component's live values on an entity:
local tint = preset.capture({ entity = id, component = "Model" }, "red_tint")
-- Both land at /zero/source/presets/<name>.preset/ (an absolute `.preset`
-- path lands where it says; `{ overwrite = true }` re-authors an existing
-- preset, keeping its guid).
-- Or author it directly:
asset.create("preset", "pixel_art", {
target = "@builtin::assetTypes.texture", -- an identity or a guid
values = { filter = "nearest" },
})
```
Each checks every value against the target's schema and refuses the whole
write on any violation, naming each one.
## How to use one
- `preset.values(p)` returns `(values, report)`. Every value is checked
against the target's current schema: valid fields are returned, and
each invalid one is listed by path in `report.rejected`.
- `preset.apply(p, into)` writes the valid values into an asset the
target governs, or into a component on an entity named
`{ entity = <id>, component = <name> }` whose component is the target.
A struct group merges field by field; any other field is written whole.
Applying to something another declarer governs raises, naming both.
- `preset.setValues(p, values)` replaces the whole values table, checked
first. Inside an undo operation the write is recorded into it, so undoing
the operation puts back what `preset.yaml` held.
- A preset is a snapshot, not a live binding: applying it writes values
once.
```luau
preset.apply("pixel_art", "enemy_sprite")
preset.apply("synty", { entity = id, component = "Locomotion" })
local values, report = preset.values("synty")
```
## Defaults for new things — the Preset Manager
A world's Preset Manager rows make a preset the starting point for what is
created from then on:
```luau
local p = preset.capture("hero_sprite", "pixel_art") -- or asset.create("preset", …)
preset.addDefault(p, { filter = "sprites/**" }) -- new things only
```
Each row names a declarer, a preset for it, and a filter. For a declarer,
the first row whose filter matches the new thing's path applies. The rows
live in `.world_settings` as `[[presets]]` blocks, sync with the world, and
are edited in the Settings panel's **Preset Manager** section.
**The layers a new thing's settings take**, each over the ones before it,
field by field (a struct group merges field by field):
1. the schema's declared defaults;
2. the type's own `settingsDefaults`;
3. the first matching Preset Manager row;
4. the creating importer's settings for the type;
5. the values the caller passed.
A component takes its `public` defaults, then the row, then the values the
caller passed.
**Rows change only new things.** A row's values are stamped into what is
created while it stands. Editing or removing a row changes nothing that
already exists, and opening a world applies nothing to its saved content. A
re-import or an `overwrite = true` re-authoring keeps the settings the asset
already holds.
**The three creation moments, and what each filter reads:**
| Moment | The row's declarer | The filter reads |
|---|---|---|
| `asset.create` | an assetType whose instances share its schema | the new asset's path under `/source` (`sprites/hero.texture`); a runtime asset reads the path the same call would give a durable one |
| an import | an importer | the source file's path under `/source` at its first import (`sprites/hero.png`) |
| `component.add` | a component | the entity's hierarchy path, names from the root down joined with `/` (`level/props/crate`) |
A component takes a row when it is added in edit mode, and in any mode
inside a scene build (a scene's `build.luau`, a `SceneModule` placement). A
component put back from existing content (a saved scene, a peer's record, a
template, a bundle's hierarchy, what a component's own code adds outside a
build) takes none. A rebuild restates a component only when its code states
it differently, so a row edit alone changes nothing a build already placed.
**Checking what applies:**
- `preset.defaults()` lists the rows in order, each resolved, with every
problem that keeps it from applying.
- `preset.defaultFor(declarer, path)` returns the values a new thing at
`path` would take from the rows, and the row that gives them.
## In the Inspector
Selecting a preset shows, beside its identity:
- **Target** — the declarer as an asset chip and the guid the preset names
it by, with a notice when the target changed since the preset pinned it
or does not resolve.
- **Values** — every field of the target's current schema as its typed
control, the way the target's own Settings section shows it. An edit is
checked against that schema, written with `preset.setValues`, and is one
undo step. A stored value the schema refuses is named with the reason.
Beneath the fields, **Apply to selection** writes the preset into every
selected asset its target governs and into the target component on every
selected entity, as one undo step.
A preset still in the component-only form shows its values read-only, with
a note that its next local edit converts it.
Every asset's and component card's Settings section offers **Save as
preset**, which captures the values it shows as a preset targeting their
declarer and selects it, and **Apply preset…**, which lists the presets
targeting that declarer and applies the one picked.
## How the target stays bound
- The preset resolves its target by the envelope's guid, and the preset's
`.refs` pins that guid together with the target's checksum, so the link
survives the target being renamed or moved. The envelope's `name` is
never an identity, so the guid is the preset's one link to its target.
- Every read re-checks the values against the target's schema as it is
now. `report.pinned` is true once `.refs` pins the target;
`report.targetChanged` is true while the target's checksum differs from
the one pinned, and a field the target dropped or retyped is then
rejected by name while the rest still apply.
- A `target` written as an identity string is accepted on read, resolves
by identity and reads as unpinned; the preset's next local edit
rewrites it as the envelope.
## Discovery
- `asset.list("preset")` — every registered preset.
- `asset.inspect("<name>").detail` — `target`, `targetGuid`, `format`,
`values`, `rejected`, `pinned`, `targetChanged`.
- `asset.validate("<name>")` — `preset.target_unresolved` when the target
does not resolve, `preset.value_rejected` for each value its target
rejects.
## Authoring conventions
- Name presets by the configuration they capture (`pixel_art`,
`hdr_skybox`, `synty`), not by the declarer.
- Keep `values` to the fields that define the configuration; fields left
out stay as each asset or component has them.
## Common pitfalls
- **Hand-edited values.** A value the target's schema rejects is
reported, not applied, and every edit of the file warns naming it.
- **A table-valued component field** (a `Field.table`) is written whole
by `preset.apply`, so a preset holding one provides every key of it.
## Related types
- `.assetType` / `.importer` / `.component` — the declarers whose
settings a preset holds.
- `.bundle` — for multi-component / multi-entity assemblies.
# Test Suite (asset type)
A **test suite** is a registrable asset that bundles one group of
automated engine tests. Each `<name>.testSuite/` folder holds an
`init.luau` whose body registers a suite (and its tests) against the
test framework this **type** ships in its `shared.module/`, reached
with `asset.containing(__FILE__).modules.shared`, plus a `README.md`
describing what the suite validates.
Test suites are the engine's regression net. Every Luau-facing system —
FFI bindings, components, the renderer, the VFS, multiplayer, the input
stack — ships its coverage as one or more `.testSuite` assets. Because a
suite is an ordinary registrable asset, a new system or package adds its
own tests by dropping a `.testSuite` folder next to its code; nothing
central (the runner, the shell script, CI) has to be edited.
## When to use one
- You added or changed a Luau-facing capability and want a permanent
regression guard for it.
- You fixed a bug — add a test that reproduces it so it can't silently
come back (the `bug_regression` suite is the canonical home for
one-test-per-issue guards).
- A package or system ships behavior that should be validated on every
CI run.
If you just want to *manually* exercise something once, use `execute`
directly — don't author a throwaway suite.
## Where it lives
- Built-in engine suites: `src/lua/lib/tests/suites/<name>.testSuite/`
(VFS: `/zero/source/libs/@builtin/tests/suites/<name>.testSuite/`).
- Package / system suites: anywhere under the package, e.g.
`…/voxelEngine.package/tests/voxel_grid.testSuite/`.
- Identity: the folder stem (`strip_suffix: true`), e.g. `vfs`. Suite
**names must be unique** across the whole tree — the runner and CI
key on the stem.
## Folder shape
```
<name>.testSuite/
├── init.luau # registers the suite via Test.describe / Test.it
├── README.md # what this suite validates + how to run it
└── .metadata # agent-editable tags + free-form fields
```
Suites may also ship fixture files (helper `.module` folders, sample
data) alongside `init.luau` — `allow_unlisted: true` permits them.
## How to construct a new suite
1. Create `<name>.testSuite/init.luau`. Reach the framework the type
ships, then declare the suite with `Test.describe(name, fn)` and
each test with `Test.it(name, fn)`. Documentation is authored as
doc-comments the engine's doc parser extracts statically: a
top-of-file `--!desc` for the suite, and a `--!desc` (what the test
checks) plus `--!pass` (the condition that must hold) directly above
each `Test.it`.
```lua
--!desc Spawn / despawn / exists / find over the entity API.
local Test = asset.containing(__FILE__).modules.shared
Test.describe("Entity Lifecycle", function()
--!desc entity.spawn(name) creates an entity and returns its proxy.
--!pass The returned id is a non-empty string and entity.exists(id) is true.
Test.it("spawn returns a stable string id", function()
local id = entity.spawn("probe").id
Test.expect(type(id)).toBe("string")
Test.expect(entity.exists(id)).toBe(true)
end)
end)
return true
```
2. Create `<name>.testSuite/README.md` describing the suite (what system
it covers, notable edge cases, how to run just this suite).
3. That's it. No registration step, no runner edit. The next test run
discovers the suite via `asset.list("testSuite")`.
See `template/` for a copy-ready skeleton (the templater fills in the
`[name]` markers).
## How to run tests
- **All suites** (writes `/source/tmp/test_results.md` + `.json`;
refused in play mode). A bare `run()` covers the world-authored
suites; `"*"` adds the baked `@builtin` library:
```lua
return tools.use("tests", "run", "*")
```
- **One suite directly** (instance-direct — runs only this suite):
```lua
return asset.resolve("vfs", "testSuite"):run()
```
- **From the shell / CI**: `./scripts/run_luau_tests.sh` (all) or
`./scripts/run_luau_tests.sh <name>` (one). `--list` prints every
discovered suite.
- **From inside the engine** (agent loop): the `tests` toolbox —
`tools.use("tests", "list")`,
`tools.use("tests", "run", { suite = "vfs" })`,
`tools.use("tests", "compare", before, after)` to diff two runs and
surface NEW failures. See the toolbox README.
## Discovery commands
```lua
asset.list("testSuite") -- every registered suite, as AssetRef handles
asset.inspect("vfs") -- summary for one suite
asset.resolve("vfs", "testSuite") -- handle { guid, identity, path, type }
tools.use("tests", "list") -- { count, suites = { { name, identity, path, origin, testCount? } } }
```
## Authoring conventions
- **One suite per asset.** Keep a suite focused on one system; large
systems split into multiple `.testSuite` assets (e.g. `zinput_state`,
`zinput_events`, `zinput_actions`).
- **No `await()` inside `Test.it()`.** The framework runs synchronously;
for multi-frame behavior use the per-test context `t.waitFrames(n)`
(see the framework README).
- **Clean up.** Entities the runner can't attribute are despawned
automatically, but prefer `Test.afterEach` for deterministic cleanup.
- **Write fixtures via `Test.tmpPath`.** Any file a test writes to the VFS
must go under its per-test sandbox: `Test.tmpPath("Foo.component/init.luau")`
→ `/zero/source/tmp/tests/<suite>/<test>/...`. That root is under
`/source/tmp/` (excluded from world saves + multiplayer sync, so it never
clogs the synced VFS) and is torn down per-test and again at end-of-run,
regardless of pass/fail/crash. Call it INSIDE the test body. For a fixture
shared across tests in one block, write under `Test.TMP_ROOT` directly
(survives per-test cleanup, still swept at end-of-run). Never hand-roll a
bare `/source/<name>` path — it persists and syncs.
- **Idempotent.** A suite must produce the same result run twice and
must not depend on ordering between suites.
- **Never silence the LSP.** No `--!nocheck` / `---@diagnostic disable`
in a suite — fix the underlying type/global instead.
## Common pitfalls
- **Duplicate stem.** Two `.testSuite` folders with the same stem
collide; the runner warns and skips the duplicate, and `--list` fails.
Pick a unique name.
- **Forgetting `return true`.** Harmless but conventional — every suite
ends with `return true`.
- **Deferred mutations.** `despawn` / `setParent` / scene clears apply
next frame; verify their effects with `t.waitFrames` or a follow-up
query, not in the same frame.
## Related types
- **`.module`** — reusable Luau library (a suite often requires the
system module under test).
- **`.tool`** — agent-callable function; the `tests` toolbox tools are
`.tool` assets.
- **`.component`** — script component; component behavior is frequently
what a suite exercises.
## In the Inspector
Tests: how many tests the suite declares and their names, parsed without running it, and **Run**, which runs this suite alone in edit mode and reports its passed, failed, skipped and quarantined counts.
# text_diff
Pure-Luau line-diff helper used by `world.diff` / `world.show` and the
`zm diff` / `zm show` shell commands. LCS-based; produces structured
hunks (op-tagged lines, not unified-diff text) so AI consumers can
pattern-match on `op` instead of parsing `+`/`-`/` ` prefixes.
## Exports
- `M.diff(oldText: string?, newText: string?, opts: DiffOpts?) -> FileDiff` — diff two strings, return the structured per-file shape.
- `M.added(newText: string?, opts: DiffOpts?) -> FileDiff` — pure-add convenience (equivalent to `M.diff("", newText, opts)`).
- `M.removed(oldText: string?, opts: DiffOpts?) -> FileDiff` — pure-remove convenience.
- `M.toUnifiedText(fileDiff: FileDiff) -> string` — render structured diff back into unified-diff text.
- `M.toStatLine(fileDiff: FileDiff) -> string` — `git diff --stat`-style one-line summary.
- `M.SIZE_CAP_BYTES: number` — per-file size cap (256 KB). Files larger than this return a size-only summary with `is_text=false`.
Types:
- `DiffLine = { op: string, text: string }` — one tagged line. `op` is `"+"`, `"-"`, or `" "` (context).
- `DiffHunk = { old_start, old_count, new_start, new_count, lines: { DiffLine } }` — git-style hunk.
- `DiffOpts = { context: number?, path: string?, action: string? }`.
- `FileDiff = { path?, action?, is_text, added?, removed?, hunks?, size_old?, size_new? }`.
## Usage
```luau
local TextDiff = require("@builtin::modules.text_diff")
local d = TextDiff.diff(oldBytes, newBytes, { path = "foo.luau" })
if d.is_text then
print(TextDiff.toStatLine(d)) -- "modified foo.luau +3 -1"
print(TextDiff.toUnifiedText(d))
else
print(string.format("oversize: %d -> %d bytes", d.size_old, d.size_new))
end
```
## Notes
- The per-file size cap (`M.SIZE_CAP_BYTES = 256 * 1024`) mirrors the
spacetime `text_blobs` inline threshold. Anything above that lives in
the bucket as binary anyway, so the diff library never sees it as
text in practice; the cap is belt-and-suspenders for callers that
bypass the routing.
- Default context window is 3 lines (matches `git diff -U3`). Override
via `opts.context`.
- Hunk header line numbers follow git's `@@ -0,0 +1,N @@` shape for
pure additions (and the mirror for pure deletions).
- Trailing newline handling: a final `\n` doesn't produce an empty
trailing element. Matches POSIX `wc -l` semantics and most diff tools.
# inputMap assetType
A control scheme, expressed as an asset. A `<name>.inputMap/` folder whose
`init.luau` returns the map record, and whose **controls are the
`<name>.inputBinding/` child folders beside it** — the same containment a
`.toolbox` has with its `.tool` children. Containment records the
reference, so a scene carrying its map carries every control it declares.
```
racer.inputMap/
init.luau -- what the map is, and how it composes
boost.inputBinding/
init.luau
steer.inputBinding/
init.luau
```
```luau
-- racer.inputMap/init.luau
return {
name = "racer",
description = "Throttle, steering and boost.",
-- The group these controls belong to, and the groups this map stands
-- down while it is live. Declaring neither composes with everything.
group = "vehicle",
suppresses = { "player" },
}
```
Each control carries `kbm`, `gamepad` and `touch`; the `inputBinding`
assetType covers the record shape.
## Reading it
A controller activates the map it needs and subscribes to the controls it
drives. Nothing is live until something asks for it.
```luau
public = {
inputMap = Field.assetRef("inputMap", "@builtin::inputMaps.default", NoSync, "The controls this component reads."),
speed = Field.number(5, NoSync, "World units per second at full deflection."),
jumps = Field.number(0, NoSync, "How many times the jump control was pressed."),
}
local controls
function awake()
controls = public.inputMap:activate()
controls.move:onInput(function(v, dt, active)
if not active then return end
local p = public.entity.position
local step = public.speed * dt
public.entity.position = { p.x + v.x * step, p.y, p.z - v.y * step }
end)
controls.jump:onPressed(function() public.jumps += 1 end)
end
function onDestroy()
public.inputMap:deactivate(controls)
end
```
What `activate` returned is this holder's **claim** on the map. Keep it and
hand it back: releasing the claim disconnects the subscriptions made
through it, and the map stays live for whoever else holds it.
A control the map does not declare reads as `nil`, so a typo raises at the
subscribe call. A controller written against more than one map tests for
an optional control first — `if controls.crouch then controls.crouch:onInput(...) end`.
Several maps can be live at once, and the player's surface is the union of
them. `group` / `suppresses` are how one map stands another down — a car
takes the player over by naming the `player` group, and walking resumes the
moment the car releases. `Zin.scheme.live()` reports each live map's
`group`, `suppresses` and `suppressedBy`, and `heldBy` — who opened each
activation still standing on it, so a control that goes quiet under a
suppression leads to the activation doing it rather than to the map.
## Whose keys a map reads
A key belongs to the surface it was pressed on. In the editor, where the
scene shares the window with panels, the scene holds the keys pressed while
it was the active input context — the last click landed on the viewport, or
play just started. A key pressed after a click on a panel is the editor's,
and a game's controls never see it. A map reads the scene's keys unless it
declares otherwise:
```luau
return {
label = "Editor",
group = "editor",
surface = "editor", -- every key no focused widget took
}
```
`surface = "editor"` is for controls that belong to the editor around the
scene — its hotkeys, its viewport camera — and answer wherever the author
last clicked. Pads and touch belong to no panel and read the same on either
surface. `Zin.scheme.live()` reports each map's `surface`.
## Ref methods
- `:activate(label?)` — load every `<name>.inputBinding/` child, validate
them, add them to the live binding set, and return the handles keyed by
control name. Every fault across every child is reported in one error.
Activating a map already live adds a holder, so two components sharing
one map read one set of controls — each through its own handles, which
are the claim it releases by. Every activation reads the children again,
so a binding added, edited or removed since the map came up reaches the
running set here and reaches the holders already standing on it. `label`
names this activation in `Zin.scheme.live()`.
- `:deactivate(claim)` — release one holder's claim, disconnecting every
subscription that claim made. The map stays live while another holder
remains; the last one out takes the controls out of the live set. Name
no claim and the caller's own most recent one goes.
- `:controls()` — `{ name, label, kind, classes, problems }` per child,
read without activating anything, so an authoring tool can show a map's
whole surface and everything wrong with it before it goes live.
- `:record()` — the raw record its `init.luau` returns.
- `:effective()` — the materialized effective map, without activating it.
- `:bindingsFor(name, class)` — the bindings a named entry has for one
device class in this map's effective form.
## Writing one
The `inputAuthor` toolbox writes a map and its controls together, filling
in canonical defaults for a control whose name it recognises:
```luau
tools.use("inputAuthor", "map", "racer", { "throttle", "steer", "boost" },
{ group = "vehicle", suppresses = { "player" } })
tools.use("inputAuthor", "check", "/zero/source/inputMaps/racer.inputMap")
```
`asset.create("inputMap", name, { record = ... })` bakes a record into both
shapes a map is read in — `init.luau` beside one `<name>.inputBinding/`
child per entry, each carrying all three device classes, a class the record
had nothing for written as `false` with the reason beside it. That is the
hook `Zin.map.bake(name)` drives to turn the active effective map into an
editable asset.
The engine's built-in schemes live at `@builtin::inputMaps.default`,
`.editor`, `.editorMeta`, `.vehicle` and `.flight`.
## In the Inspector
Controls: whether this map is the one taking input now, how many controls it declares, and each control's name, label, kind, device classes and problem count.
# Shader module (asset type)
A `.shaderModule` is a block of WGSL that other shaders **include** rather than
copy — a lighting model, a set of colour-space helpers, one package's shared
prelude. It declares no entry point and is never dispatched or drawn on its own
account; it exists to be expanded into the shaders that name it.
## Folder shape
```
<name>.shaderModule/
module.wgsl # the WGSL — helpers, structs, constants (required)
README.md # what THIS module provides (required)
```
Each file carries a committed `.meta` sidecar pinning its stable guid, and the
folder carries one of its own.
## Including one
A shader names a module by identity, and the identity is what records the
dependency — so a shader that is packed, pulled or published carries the modules
it includes with it:
```wgsl
#include "~.colour" // a module in the same package
#include "@builtin::shaderModules.pbr_shading" // one from the builtin library
```
A missing module is a hard error at compile: a shader that names an interface
which no longer exists fails loudly rather than compiling against a stale copy.
Each module is expanded at most once per shader, so two shaders that both
include the same module — or a module that includes another — produce one copy,
not a duplicate-definition error.
## Writing one
Write only what other shaders need in scope: functions, structs, constants. A
module may reference a binding its includers declare, which is how a package's
prelude can read that package's uniform block.
```wgsl
const LUMA: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
let lo = c / 12.92;
let hi = pow(max(c + vec3<f32>(0.055), vec3<f32>(0.0)) / 1.055, vec3<f32>(2.4));
return select(hi, lo, c <= vec3<f32>(0.04045));
}
```
## Answering to another name
A module declares extra names it answers to with `@alias` lines in the header of
`module.wgsl`:
```wgsl
// @alias: colour_helpers
// @alias: @mypack::shaderModules.colour
```
Each becomes an alias on the asset, so the name resolves everywhere an identity
does — `asset.resolve`, an `#include`, and the publish gate alike. That is what
lets a module be renamed without breaking the shaders already written against
its old name: content persists the source it was authored with, so a name that
stops resolving is a world that stops publishing.
Only the header is read — the scan stops at the first line that is not a
comment, so a directive cannot hide in the module body. A name another asset
already holds is refused and reported, since an alias extends the identity
namespace rather than taking a name out of another asset's hands.
## Registration & hot reload
Writing `module.wgsl` registers the module under every name the asset answers to
— its guid, its identity, and any alias — so a shader includes it by whichever
name it holds. Saving re-registers it and the shaders that include it recompile,
with no world reload.
## Discovery
- `asset.list("shaderModule")` — every registered module.
- `moduleRef:getSource()` — the module's WGSL.
## Related types
- `.shader` — render-domain shaders (surface, sky, post-process, screen).
- `.computeShader` — compute programs.
## In the Inspector
Selecting a shader module opens its **Module** section: how many lines it holds, the aliases a shader `#include`s it by, and an opener for `module.wgsl`.
# `.font` asset type
A `.font` is a first-class font asset: font-file bytes (TTF / OTF / WOFF /
WOFF2) converted into a guid-anchored asset via
`asset.create("font", name, { bytes = … })`.
A font is a **general CPU resource** usable by any text surface. The
`onRegister` hook calls the engine `font.register(name, bytes)` primitive,
which installs the parsed face into **both** the 2D/3D text system (`text.*`)
and the egui UI text system, under the family name the font file itself
reports. A registration is what puts the face in the database; whether
`fontFamily = "<name>"` selects it is the separate question of whether the
shaper matches that name, and `font.reconcile()` answers it per family:
```lua
for _, f in ipairs(font.reconcile()) do
if not f.selectable then
print(f.family .. " is registered but shapes as " .. f.shapedWith)
end
end
```
`text.face(handle)` gives the same answer for one label. A family the shaper's
database holds is selectable under its own weights and for the glyphs its faces
cover: a row that reads `familyCoveredNoGlyph` names a family the shaper picks
whose faces have no glyph for the text asked of it. `topics/text` covers reading
a label that came out in the wrong face.
Fonts are CPU resources (not GPU), so the primitive lives in the `font.*`
namespace, the CPU analogue of `renderer.texture.create`.
## Layout
```
<name>.font/
data.zfnt the baked payload `asset.create("font", ...)` writes
face.json optional: family group, role, aliases, on-demand entries
```
## Editing a font's files
A write to a file the registration reads (`face.json`, `data.zfnt`, or a raw
font file in the folder) installs the font again from what the folder now
holds. The names the new `face.json` gives it (its group and each alias) select
it on every text surface from then on, and a name the earlier descriptor gave it
and the new one does not stops selecting it; a changed `group` moves the face to
that group. Text laid out under a name the edit decides is laid out again, and a
`Text3D` label draws it again on the next frame. For an on-demand face the
same holds for the font and coverage files its entries name: the entries are
declared again from their coverage files, and an entry already installed is
registered again from its font file with the names the descriptor now gives.
## On-demand faces
A face whose file is large and whose script most sessions never draw is
declared by the codepoints it covers instead of being read at boot. Its
`face.json` lists the font files of the folder under `onDemand`, each beside a
coverage file:
```
NotoSansCJK.font/
face.json { group, role, aliases, license, onDemand = [ { name, file, coverage }, ... ] }
kana.otf a font file (TTF / OTF)
kana.coverage the codepoints it maps: "3000-30ff,ff01-ff5e,..."
...
OFL.txt the license the files are distributed under
```
`onRegister` reads the coverage files and calls `font.declare(name, coverage,
{ file, family, role, aliases })` for each entry; no font file is read. The first
time a label or a `text.*` object meets a character an entry covers and no
installed face draws, the engine requests that entry: its file is read without
blocking the frame and registered with `font.register`, and from then on every
text surface draws the character from it. `font.onDemand()` reports each entry
as `declared`, `requested`, `installed` or `failed`, and `font.prefetch(text)`
requests the entries a text needs before it is drawn.
`font.coverage(bytes)` writes a coverage file from a font file's character map.
Splitting one large face into several entries (by script, and by how common a
character is) means a session reads only the part its text reaches: the
built-in `NotoSansCJK.font` is cut that way by `scripts/fonts/build_cjk_fallback.py`,
and a page of Japanese reads its kana and common-ideograph entries alone.
Every registered face, on-demand or not, is a per-glyph fallback for every
family the UI holds: a character the selected family has no glyph for is drawn
from the first face that has one.
## In the Inspector
Selecting a font opens its **Font** section: the family the face registers under, its role and aliases from `face.json`, whether the text system has the family registered and, when it holds it, how many faces and which weights. Below the facts, a sample line is drawn in the family at 14, 20 and 32 px.
# population
A hardware-instanced population at rest: one mesh drawn at every transform
of a baked placement, as ONE draw call per variant at any instance count.
The asset is the recipe — which `.mesh` and material each variant draws with,
plus the instance matrices as bytes. Its `instantiate` method is what turns
that recipe back into a live draw, so a scene records ONE entity for a
population of a million instances instead of a million entities.
## Layout
```
<name>.population/
population.json { version, total, variants: [ { mesh, material | materialKey, count, offset } ] }
transforms.bin total × 64 B — little-endian f32, column-major mat4 per instance
```
`offset` counts INSTANCES, not bytes: variant *k*'s matrices start at
`offset × 64` bytes of `transforms.bin` and run for `count × 64`. Each matrix
is column-major, which puts its translation at floats 13/14/15 of the block —
the layout the engine reads a transform buffer as `array<mat4x4<f32>>`. The
matrices are taken in the space of the entity drawing the population, so it
draws where the recipe placed it relative to that entity and moves with it.
`mesh` and `material` are asset references (`{ "__ref": "<guid>" }`), so the
geometry and material a population draws travel with it in the dependency
graph. A variant drawing with a material the renderer's registry holds but no
asset backs names it in `materialKey` instead.
## Putting one in a scene
```lua
local pop = asset.resolve("forest", "population")
pop:instantiate(nil, { position = { 0, 0, 0 } }) -- one entity, one draw call
```
That spawns an entity carrying the `Population` component, which owns the live
GPU buffers and draw registrations for as long as the entity lives — a reload
replaces them rather than stacking a second set. The same contract is what
`Asset { source = <population> }` drives, which is how a baked procgen bundle
carries a population: a root record plus one child holding the reference.
## Building one
`proc`'s `population.write` sink persists a `Population` value:
```lua
local pop = proc.registry.get("instances.draw").eval({}, { instances = iset }, {}).population
proc.registry.get("population.write").eval({}, { population = pop }, { name = "forest" })
```
Or through `asset.create` directly, with each variant's matrices as a flat
`count × 16` column-major float array:
```lua
asset.create("population", "forest", {
variants = { { mesh = meshGuid, material = materialGuid, transforms = flat } },
})
```
## Reading and drawing one by hand
```lua
local recipe = pop:spec() -- { version, total, variants }
local live = pop:draw() -- allocate buffers + register draws
print(live:count(), live:drawCalls())
live:destroy() -- drop the registrations, free the buffers
```
The value `:draw()` returns OWNS those resources. Hold it and release it —
a registration nobody holds can be neither enumerated nor dropped afterwards.
## In the Inspector
Selecting a population opens its **Population** section: how many instances it places, across how many variants, and a table of each variant's mesh, material, instance count and offset, with a link to each variant's mesh.
# 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.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure.
## 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.
# loadingScreen
The screen players see while your world loads, as an asset: a
`<name>.loadingScreen/` folder whose `screen.yaml` states the title, a line of
text or rotating tips, a background picture, a logo, the colours and how the
load's progress is drawn, with its pictures beside it. The world names the one
it shows in its settings, and every boot of the world draws it on native, web
and Android.
## Make one and show it
```luau
local screen = asset.create("loadingScreen", "title", { folder = "branding" }) -- /zero/source/branding/title.loadingScreen/
vfs.write(screen.path .. "/screen.yaml", [[
title: "Skyward"
text: "The islands are waking up"
tips:
- "Hold Shift to sprint."
- "Wind currents carry you further."
background: background.png
logo: logo.png
colors:
background: "#0b1626"
accent: "#7ad3ff"
text: "#f2f7ff"
progress: bar
]])
world.loading_screen = screen -- writes [world] loading_screen = "branding.title"
```
Put the pictures in the folder (`upload_file`, `vfs.write`, or a generated
image saved there), then push the world (`zm add . && zm commit -m '...' &&
zm push`). The screen is part of the world's content: it is versioned and
published with it like everything else, and an unset `world.loading_screen`
(`world.loading_screen = nil`) brings back the engine's own loading screen.
`.world_settings` holds the choice as an asset identity:
```toml
[world]
loading_screen = "branding.title"
```
## `screen.yaml`
Every key is optional. A key left out keeps the engine's own loading screen
look: the origozero.ai palette, the world's cover picture as a card, its title,
and a progress bar with the percentage under it.
| Key | Type | What it states |
|---|---|---|
| `title` | text | Drawn large in the middle. The world's title when left out. |
| `text` | text | One line under the title. |
| `tips` | list of text | Lines shown one at a time under the text, each for `tipSeconds`. A single text counts as a list of one. |
| `tipSeconds` | number | Seconds each tip stays up (default 6). |
| `background` | picture | Fills the whole window behind everything, cropped to cover it. |
| `logo` | picture | Drawn above the title, 96 pixels tall. |
| `cover` | true / false | Whether the world's cover picture shows as a card above the title (default true). |
| `status` | true / false | Whether the line naming the step the load is at shows (default true). |
| `progress` | `bar` / `percent` / `none` | A bar with the percentage under it (the default), the percentage alone, or no progress. |
| `colors` | mapping | `background` (the window), `accent` (the status line and the bar), `text` (title and text), `muted` (tips and the percentage), `track` (the bar's empty part). Each is `#rgb`, `#rrggbb` or `#rrggbbaa`. |
A picture is a file name inside the screen's folder (`background.png`) or a
path from the world's source root (`/source/art/key.png`). PNG and JPEG both
work. A key the type does not take, a colour that is not a colour and a value
of the wrong kind are each named in `ref:spec().problems` and in the
Inspector, and the screen keeps the default for that key.
## When it shows
The engine shows the screen from the moment it knows which world it is
loading, before the world's content has synced: it reads the world's
published `.world_settings`, `screen.yaml` and pictures from ZeroMind first,
which is what a player opening the world sees. A player sees the screen the
world's latest push states, so a change to it reaches players with the next
`zm push`, and a world that has pushed nothing yet shows its screen once its
own content is in place. Once the world's own content is in place, the screen
is read again from it, so an editor sees the screen their working copy states.
The screen stays up until the window shows the world's first frame, so the
handover from the screen to the world shows no black frame. The world's first
frame follows the world's `onWorldLoad` returning: work that runs for the
whole session goes in a component, a service or a `task.spawn` that
`onWorldLoad` starts, and an `onWorldLoad` that keeps running holds the
screen up for as long as it runs.
A world that names no loading screen, or names one whose `screen.yaml` is
missing, shows the engine's own loading screen.
## See it
`screen:preview(seconds)` draws the screen over the whole window exactly as a
boot of the world draws it, for `seconds` (default 15): the progress fills and
the tips change on the screen's own clock. Capture it while it is up:
```luau
world.loading_screen:preview(20) -- then: capture { source = "window" }
world.loading_screen:preview(0) -- takes it down early
```
## From a script
```luau
local read = world.loading_screen:spec() -- { spec, problems }
print(read.spec.title, read.spec.progress, #read.problems)
print(world.loading_screen:isShown()) -- true: the world names it
```
## In the Inspector
Loading screen: the title, text, number of tips, pictures, whether the cover
card and the status line show, how progress is drawn and the colours, whether
the world shows this screen while it loads, every problem that kept a key out,
**Preview**, which draws the screen over the window for 15 seconds as a boot
does, and **Show while the world loads**, which names this screen in the
world's settings.
# `rig` asset type
A skeleton, as a composite asset. A rig is its own primitive — not a mesh and
not an animation. The folder `<name>.rig/` carries:
- **`rig.json`** — the readable skeleton document, the asset's *primary*.
Consumers reference the `.rig` asset's guid, never this inner file. It holds:
- **`bones`** — ordered bones, each with a `name`, a `parent` index (-1 for a
root), the `node` index it maps to, its `rest` local transform
(translation / rotation / scale relative to the parent — the bone's offset and
length), and its `inverseBind` matrix (16 floats). The `inverseBind` is what
skinning reads.
- **`bind`** — where the rig's bind pose, the pose retargeting reads anatomy
from, comes from: `"skin"` (its inverse binds are a skin's bind, as a model
import writes), `"rest"` (it has none: its inverse binds restate its rest, as an
animation-only import's rest is the clip's first frame), or `{ "__ref": <rig
guid> }` (a skinned rig of the same skeleton whose bind it shares; an
animation-only import names one when the world holds it). A rig with no `bind`
reads its own inverse binds.
- **`overrides`** — what an author set by hand, keyed by avatar type guid:
`{ [typeGuid] = { roles = { [role] = boneName | false } } }`. `false` leaves a
role empty. Carried across a re-import of the rig's source file.
The format is JSON, not binary, because a rig is small structural metadata an
agent inspects and corrects — the bulk binary `.mesh`/`.animation` carry their own
decode paths, but a rig is meant to be read.
## How a rig maps onto an avatar type
Which bone is the hips, the left hand, a hair strand, is derived from the bones
whenever it is asked for, by the avatar type (see the `avatarType` asset type) —
never stored. The skeleton's structure decides it, for any naming and in any pose
the rig rests in, and the author's overrides are laid over the result.
```luau
local rig = asset.resolve(rigGuid, "rig")
local q = rig:qualify() -- the builtin humanoid type; pass another type to ask it
print(q.qualifies, q.reason) -- whether it is a humanoid, and why not
print(q.mapping.roles.hips) -- the bone filling a role
print(q.report.verdict, #q.report.stale)
```
| Method | Returns |
|---|---|
| `:doc()` | The decoded `rig.json`. |
| `:structure()` | The skeleton's structure (`modules.rigStructure`). |
| `:qualify(avatarType?)` | Whether the rig qualifies as the type, the effective mapping, and the report (confidence per chain, missing chains, ambiguities, name contradictions, overrides naming bones the rig lacks). |
| `:mapping(avatarType?)` | `:qualify(avatarType).mapping`. |
| `:isHumanoid()` | Whether the rig qualifies as the builtin humanoid. |
A skinned `.mesh` references a `.rig` (the mesh keeps only per-vertex skin
weights; the skeleton lives here). An `.animation` references its source `.rig`.
Retargeting maps a clip from its source rig onto a body's rig through the roles
both rigs fill.
## In the Inspector
Selecting a rig opens its **Skeleton** section: the bone count, the number of roots, whether the rig qualifies as a humanoid with its verdict and confidence, and the bone hierarchy, indented by depth.
# sceneModule — a part of a scene, authored as code
A `.sceneModule` is a recipe for scene content: a folder whose `init.luau`
declares the inputs a placement may set and returns the function that builds
the content. Placing one runs the builder and lands what it built in the scene
as ordinary entities — named, selectable, movable, saved in `scene.json`, and
replicated like anything else an author placed by hand.
```
CoinPusher.sceneModule/
init.luau -- declared inputs + the build code
Coin.mesh/ -- an asset the build makes (see The assets a build makes)
.build.assets -- which init.luau produced each of them
README.md
.metadata
```
The entities are not baked into the folder — the scene holds those. What the
folder holds is the code, and the assets that code makes.
## The builder is ordinary engine code
```lua
inputs = {
seed = Field.number(0, NoSync),
coinCount = Field.number(40, NoSync),
stroke = Field.number(0.8, NoSync),
}
return function()
local base = entity.spawn("base")
base.component.add("Model", { model = asset.resolve("PusherBase", "mesh") })
local pusher = entity.spawn("pusher", { parent = base })
pusher.component.add("PusherDrive", { stroke = inputs.stroke })
math.randomseed(inputs.seed)
local coinMesh = asset.resolve("Coin", "mesh")
for i = 1, inputs.coinCount do
local coin = entity.spawn("coin_" .. i, { parent = base })
coin.localPosition = { math.random() * 1.6 - 0.8, 0.5, math.random() * 2 - 1 }
coin.component.add("Model", { model = coinMesh })
end
end
```
Real loops, real conditionals, real locals, real `require` — `entity.spawn`,
`component.add`, and transform writes are the same calls they are anywhere
else. The builder **authors**; components **behave**. A coin pusher's machine,
coins, and colliders are construction, so they belong in the builder;
`PusherDrive` is runtime logic, so it stays a component the builder attaches.
The builder runs inside a capture scope, which records what it created and
holds it to the operations that end up in the scene. A build accepts an
operation exactly when a scene record carries its result; anything else is
refused by name while the build runs — never applied and then dropped, so
nothing the builder appears to do goes missing later.
A refusal is cheap, so try the thing you are unsure of. The refused call never
lands, the build is abandoned whole, and the previous build stays in the scene
untouched — one rebuild tells you the answer and costs nothing.
`guides { path: "core/scenes-as-code" }` states the rule and works through
placing an asset that expands into a hierarchy, such as a `.bundle`.
Anything the entry script pulls in uses an absolute require
(`require("@builtin::modules.json")`): the script is compiled into its own
environment, which is what gives `inputs` its meaning below.
That environment holds `inputs` and `build`, and falls through to the engine's
global one for every other name, so a builder reaches everything a script
reaches anywhere else — `entity`, `asset`, `Transform`, `math`, `require`,
`vfs`, `task`, `tools`, `world`, `string`, `table`, `os`, `Field`, `NoSync`.
`Transform.quatFromAxisAngle(ax, ay, az, angle)` and
`require("@builtin::modules.json")` behave inside the builder exactly as they
do outside it, so the engine's own maths and modules are the ones to reach
for. A toolbox is reached with `tools.use("wld", "mode")`, the same call it
takes anywhere.
## Inputs
`inputs` follows the component `public` convention exactly. The table literal
**declares** the fields with the same `Field.*` constructors components use,
and a read of `inputs.<name>` inside the builder returns the **resolved** value
for the placement being built — the param override when the placement sets one,
else the declared default.
```lua
inputs = {
-- a placement that sets nothing builds with 0
seed = Field.number(0, NoSync),
style = Field.enum({ "brass", "steel" }, "brass", NoSync),
lit = Field.bool(true, NoSync),
}
```
The replication mode is the one every component field names, on the same
constructors. The placement carries the whole resolved set in one `params`
field, which is what replicates, so an input declares `NoSync`.
Declare `inputs` as a global, the way a component declares `public`. Reading a
name the module never declared raises and lists the ones it does, so a typo
says so instead of silently building with nothing.
## The assets a build makes
Some of what a module states is an asset rather than an entity — the coin mesh
above is one. `build.asset(type, name, produce)` makes it: `produce` takes
nothing and returns the creation parameters `asset.create` takes for that type,
and the call returns the asset's `AssetRef`, which is what a component field
holds.
```lua
local coinMesh = build.asset("mesh", "Coin", function()
local positions, indices = disc(0.4, 24)
return { positions = positions, indices = indices }
end)
local coinGold = build.asset("material", "CoinGold", function()
return {
shader = "pbr",
properties = {
base_color = { 1, 0.84, 0.28, 1 },
metallic = 1,
roughness = 0.25,
},
}
end)
return function()
for i = 1, inputs.coinCount do
entity.spawn("coin_" .. i).component.add("Model", {
model = coinMesh,
material = coinGold,
})
end
end
```
The first argument is the type, so a module makes every kind of asset its
content names, not only geometry. A material's overrides go in **one
`properties` table**, colours as `{r, g, b, a}` arrays — `mat.yaml` groups them
on disk under `floats:` / `colors:` / `ints:` / `bools:`, which reads like a set
of creation keys and is not one; passing a section name is refused with the
shape to use.
The producer owns what it makes. Editing a generated asset at runtime — setting
a property on the live material, hand-editing its files — leaves it in a state
the next produce does not know about. Edit the producer and rebuild.
The asset is authored inside the module's own folder — `CoinPusher.sceneModule/
Coin.mesh` — and the module records which `init.luau` produced it in
`.build.assets`. So `produce` runs when the entry script changed and never
otherwise: every later placement and rebuild reuses the asset, while editing the
disc re-authors `Coin.mesh` **in place**, keeping its path and its guid. That is
what holds the reference — `scene.json` names assets by guid.
This is the answer to a refusal that names a runtime resource:
`renderer.mesh.create` makes a GPU mesh that lives as long as the session, which
no record can hold, and the same geometry made as an asset is held by every
record that names it.
## Placement
A sceneModule defines `instantiate`, so it is accepted anywhere a
scene-instantiable asset is: an `Asset`-style field gated by
`Field.instantiableRef`, a viewport drop, a tool argument.
```lua
local pusher = entity.spawn("pusher_0")
pusher.component.add("SceneModule", {
source = asset.resolve("CoinPusher", "sceneModule"),
params = { seed = 0 },
})
```
`SceneModule` is the placement component: it holds the module the placement is
bound to and the params it sets, and it is what re-runs the build. Placing the
same module twice with different params yields two different results from one
asset, each with its own stable ids. See its README for the full field set.
## Rebuilds hold ids
Editing `init.luau`, or changing a placement's params, re-runs the builder in
edit mode and **reconciles** the result: an entity the previous build placed is
updated in place, one the build no longer emits is removed, and a new one is
spawned. Same entities, same ids, updated contents — so a reference to a built
entity survives every rebuild.
A change is what rebuilds. A placement that already holds a build runs nothing
when the scene loads or the mode flips — the entities are there, holding what
the last bake gave them. `SceneModule:rebuild()` forces a rebuild for a change
nothing else reports, such as a module edited while the world was closed.
In play nothing runs and nothing instantiates. The entities are already in
`scene.json` and load as authored content; the placement component is inert.
## Ref methods
- `ref:build(params)` — run the builder and return the records, leaving the
scene untouched.
- `ref:inputs()` — the declared inputs, sorted: `{ name, kind, default, values? }`.
- `ref:getInitScript()` — the entry script source.
- `ref:instantiate(target?, opts?)` — the uniform placement call.
## In the Inspector
Selecting a scene module opens its **Inputs** section: a table of the inputs the builder declares, each with its kind, default and allowed values, and an opener for `init.luau` in the Code panel. A placement sets their values on its SceneModule component.
# assetType (asset type)
The `assetType` is the **type of types** — the meta-type that every
`<typename>.assetType/` folder is an instance of, including itself. A
`<typename>.assetType/` folder declares a new asset type called
`<typename>`: its on-disk shape, its identity rule, and the structural
contract instances of the type must satisfy.
This type is self-hosting. `assetType.assetType/` conforms to its own
schema — a `type.yaml` plus a `README.md` — so the type system is
defined in terms of itself rather than a hidden engine special-case
(the same way a C compiler is written in C). Every asset in the engine,
including each `.assetType` definition, now resolves to a registered
assetType: a `.material` resolves to `material.assetType`, and
`material.assetType` resolves to `assetType.assetType`, which resolves
to itself.
## Why it exists
Assets used to be mapped to their type *implicitly*, by matching the
folder suffix against a name-keyed registry. That match carried no
stored link: nothing on a `Foo.material` recorded *which*
`material.assetType` it was written against, so two worlds shipping a
same-named type could silently disagree. Making `assetType` a real,
resolvable asset closes that gap — the link from an asset to its type is
now an explicit reference pinned in the asset's `.refs` sidecar
(`via: "asset_type"`), exactly like every other dependency.
## Where it lives
- Source: `/zero/source/.../<typename>.assetType/`
- Identity: `<typename>` (the `.assetType` suffix strips from the
identity; the folder retains the suffix on disk).
- Folder shape:
- `type.yaml` — the structural spec the validator reads. **Required.**
- `README.md` — type-level documentation. **Required.**
- `about.yaml` — three short plain-language texts saying what the type
is for (see "Say what your type is for" below). Every built-in type
ships one.
- `behavior.luau` — optional behavior/scaffolding module.
- `template/` — optional canonical placeholder body the templater
copies into a new asset of the type.
- `<name>.module/` — optional shared code the type ships to **every
instance** of it, conventionally `shared.module/` (see below).
## Shared code its instances reach (`asset.containing` + `.modules`)
A type ships code every instance of it uses by declaring the modules in
its own `behavior.luau`, as a map of tracked `require`s:
```luau
-- inside <typename>.assetType/behavior.luau
M.modules = { shared = require(".shared") } -- the sibling shared.module/
```
An instance reaches it with one location-independent line:
```luau
-- inside any foo.<typename>/init.luau
local api = asset.containing(__FILE__).modules.shared
```
`__FILE__` is the chunk's own VFS path; `asset.containing` resolves the
calling asset, and `.modules.<name>` follows the instance's pinned
`typeRef` (the type's **guid**, recorded in the instance's `.refs` as
`via = "asset_type"`) to the module its type declares. Because
resolution follows that link rather than a category name, the same line
in an instance of a different type resolves to that type's module, and
identically-named modules in two types never collide. `asset.typeRef(target)`
reads that guid for any target; `asset.resolve(asset.typeRef(target))`
gives the full `AssetRef<assetType>`. See `assetTypes/README.md`
§ "Shared code: type-owned modules" for the full mechanism.
## How to create one
Authoring a new asset type is just creating a `<typename>.assetType/`
folder under `/zero/source/`. The engine registers `<typename>` as a
category **the moment the folder is written** — no engine restart, no
Rust change, and it works for built-in (`@builtin/assetTypes/`) and
user-defined types identically. Once `<typename>` is registered,
`<name>.<typename>/` folders are recognised as assets of that type and
resolve their `asset_type` link back to this definition.
Creating a `<name>.<typename>/` folder *before* its
`<typename>.assetType/` exists fails fast: the suffix has no registered
type, so the folder can't be a valid asset. Author the type first.
## Say what your type is for (`about.yaml`)
Every type carries a small `about.yaml` beside its `type.yaml`, and the README
you write for the type documents how to author an asset of it. Both are
required, and both are meant to be written as you make the type, while you know
what it is for. `about.yaml` answers three questions in plain words, one key
each:
```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. Name the whole range
of things it covers, in the words a game maker would use for them.
- **`function`** is how it works today: what an asset of the type is made of and
what the engine does with it.
- **`usage`** is what a person or an agent does with one: how they pick it, place
it, call it, or hand it to something else.
A few habits keep it useful. Write about the type as a whole, so the text holds
for every asset of it, and leave out any one asset's name. Say what the type
does right now. Stay with words a game maker would say, and mention a file name
or a call only where a game maker would know it. The limits are in bytes:
`intent` 800, `function` 1500, `usage` 1200. Each is generous, and a few
sentences usually say it.
Why bother: agents working in a world read these three texts to learn what your
type is for, so they reach for it when it fits and use it the way you meant. People
searching find the type by what they want to make, and the three texts let them
tell at a glance whether it is the one they need.
`asset.create("assetType", name)` scaffolds the file with all three keys, and a
README whose first paragraph is a `[[describe]]` note. Each value starts with
`[[describe]]` followed by a note on what to write; replace the whole value with
your own words. A value or a README line that still starts with `[[describe]]`
counts as not written yet, which the push's check of each asset it carries against
its type reports, naming the file. A type you leave as it was is not asked, so
older types stand.
Many types at once, or one you would rather not write by hand: `services
describe` lists the types that lack these texts and what filling them costs, and
`{ mode = "all" }` writes them into the same files, where you edit them like
anything else you wrote.
Where the texts show up: `asset.inspect("<typename>", "assetType")` returns them
as `detail.about`, `assetTypeRef:getAbout()` returns them as a table with the
keys `intent`, `function` and `usage`, the type's `types/<typename>` guide page
ends with an "About this type" section holding them, and the Inspector's Type
section lists them at the top. The guide page is this README plus that section,
so a README that explains the type well and an `about.yaml` that says what it is
for read well together.
## Ask your assets to say what they are
A type can ask each of its assets to carry a description: a file, written by the
author or generated, that says what that asset is and what it is for. The people
and agents who find an asset read it to decide whether it fits, and the author
knows what it is for at the moment of making it.
**1. Declare the file with a `described` check.** This is the whole requirement:
```yaml
files:
required:
- path: "README.md" # any file name works
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
With that in place:
- An asset whose file is missing, empty, or still has a line starting with
`[[describe]]` does not meet the type's requirements. `asset.validate` names it,
`zm status` and `world.publishBlockers()` list it, and a push that carries it is
refused with `message`.
- `services describe` finds it (`mode = "find"` lists it and the price) and can
write the description for it (`mode = "all"`). It writes only this file.
For a YAML file that holds several texts, name the keys and their limits in bytes,
the way this type does for `about.yaml`:
```yaml
content:
- check: "described"
keys:
- { key: "intent", max_bytes: 800 }
- { key: "usage", max_bytes: 1200 }
message: "Write intent and usage."
```
`headings` names sections a Markdown file must have. `assetTypes/README.md` has the
full check.
**2. Optionally, steer what gets generated with a `describe:` block:**
```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>"
```
`guidance` says what a description of your type covers, and `examples` names assets
whose descriptions show the shape you want. Without the block, generation still
works from the general describing guide and the check's `message`.
An example is an asset of your type in the library whose description is a true,
written one, never a scaffold's placeholder, and never the asset being described.
When the library has none, leave `examples` empty rather than name one that is not.
A type whose assets the model cannot perceive (a sound it cannot hear, a motion it
cannot see) says so in `guidance`: the description comes only from what the asset's
own files state, such as its name and the `.metadata` where a generation service
records the prompt that made it, and when they state nothing the model answers
`cannot` with that reason. `services describe` then fails that one asset with the
reason and leaves its file as it was.
**3. Start the file unwritten in your template.** Put a heading and one line that
starts with `[[describe]]` and a short note on what to write, in
`template/<file>`, so a new asset starts unwritten rather than with text that only
looks written. Do not put example content in it: every new asset carries the
template verbatim, and the same text on many assets makes them impossible to tell
apart in search.
Types whose assets say what they are through their own content (a mesh, a texture,
a sound) leave this out: declare nothing and nothing is asked.
## The `behavior.luau` contract
`behavior.luau` is the type's code. It returns ONE table, and the keys below
are the ones the framework reads off it for EVERY type — the surface you get
by declaring them. Anything else on the table is your own: reachable by name
through `require("@builtin::assetTypes.assetType.shared.ref").loadTypeModule("<typename>")` for a
system that knows your type (`computeShader` publishes `dispatchKey` that
way), and never called by the framework.
```luau
local M = {}
M.ref = { ... } -- methods on every AssetRef of this type
M.modules = { ... } -- shared code the instances reach
M.global = {} -- reserved key; ship the empty table
function M.onCreate(name, opts) ... end
return M
```
### The tables
| Key | Shape | What the engine does with it |
|-----|-------|------------------------------|
| `M.ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every `AssetRef` of this type: `ref:name(...)`, with `self` the ref. This is how a type gives its instances an API. Two names in here are contracted — see below. |
| `M.modules` | `{ [name] = require(".sibling") }` | Shared code the type's instances reach through `asset.containing(__FILE__).modules.<name>`, resolved by the instance's pinned `typeRef` guid. See the section above. |
| `M.refShapes` | `{ [method] = "TypeName" }` | Declares the result type of a `M.ref` method so the LSP can check what a call site does with it. See the `M.refShapes` section below. |
| `M.events` | an events schema | The events an ASSET of this type fires, declared the way a component declares its own. Readers subscribe through `ref.events.<name>:connect(...)`; firing authority stays with the type. Keyed by the asset's guid, so every resolver of the same asset shares the signals and a re-resolved ref re-attaches to subscriptions already there. |
| `M.namePattern` | a Lua pattern string | The name shape `asset.create` enforces for instances of this type, replacing the default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `M.global` | `{}` | Reserved. Ship the empty table. |
### The lifecycle hooks
Each is optional; a type that omits one costs nothing. The engine calls them:
| Hook | Signature | When it fires |
|------|-----------|---------------|
| `M.onCreate` | `(name, opts) -> { [filename] = contents }` | On `asset.create("<type>", name, opts)`. Returns the files that scaffold the new instance, as a map of relative path to contents; the framework writes them. The `opts` type annotation is the schema `asset.create` validates the caller's arguments against, so annotate it. |
| `M.onReplace` | `(dest, files) -> { [filename] = contents }` | On an `asset.create` that writes over an asset already at `dest`, after `onCreate`. Receives the files `onCreate` produced and returns the files to write, so a type that re-derives its content (a rig re-imported from its source file) can carry what an author added to the asset it replaces. Optional. |
| `M.onRegister` | `(self)` | Once per instance, the first time it registers: on `engine.onWorldLoaded` for instances already in the world, immediately on a live `asset.create`, and when an instance arrives after that sweep (installed, pulled, or synced from a peer). Guarded by the instance's path, so a double trigger never double-registers. An instance that leaves the runtime releases the guard, so one arriving at the same path again registers. This is what makes "write an asset into the world and it takes effect live" work for content that registers into a runtime registry. The `@builtin` library is excluded from the sweep. |
| `M.onChange` | `(ref, change)` | On every VFS write to a file INSIDE one of this type's instances. `change` is `{ path, asset, type, kind, origin }`: `kind` is `"edited"` or `"seeded"`, `origin` is `"local"` or `"remote"` (an importer runs on the originator only). **Filter on `change.path`**: the hook fires for any file under the folder, so act on the one you care about. It runs as its own task and may wait on what it reads: a `vfs.read` of bytes only the blob store holds (a binary file on the web build) fetches them. The writes to one asset reach the hook in the order they were made, each once the hook before it has finished. A re-entrancy guard suppresses writes back into the same asset routed inline from the hook, and a write the hook makes is routed on a later frame like any other, so the hook must be convergent on its own: diff the meaningful state and short-circuit while your own regeneration is in flight. |
| `M.onDelete` | `(ref)` | When an instance of this type leaves the runtime: it is deleted, or the engine swaps away from the world binding that held it. Its files are gone from `/zero/source` by then. A removal routed while the instance's `onChange` is waiting reaches `onDelete` once that hook, and every write queued behind it, has finished. On a swap the instance still exists in the world it belongs to, and a VFS write the hook makes reaches the world now bound. |
| `M.validate` | `(assetRef) -> { { code, message, severity? } }` | On `asset.validate`, after the structural `type.yaml` check, for the type's own SEMANTIC validation. `severity` defaults to `"error"`; error-severity problems flip `ok` to false, warnings do not. A hook that raises or returns a non-table is itself reported as a `validate.hook_failed` error. `world.push` runs this per user asset, so declaring it enforces your type's rules at publish time with no further wiring. |
### The two contracted `M.ref` names
Most `M.ref` methods are your type's own surface: name them what you like,
return what you like. Two are read by the engine and mean the same thing for
every type, so their shape is fixed:
- **`instantiate(self, target?, opts?) -> (root, idMap)`** — makes an instance
part of the scene. Defining it is the whole opt-in: `ref:canInstantiate()`
is true exactly when it exists. Its **return is a contract** — see the next
section.
- **`inspect(self) -> detail`** — the type-specific half of `asset.inspect`.
See its section below.
### Names a type cannot shadow
Some keys resolve on every `AssetRef` before per-type dispatch, so an `M.ref`
entry of the same name is never reached: `canInstantiate`, `getSource` /
`getBytes` / `getText`, `exists`, `deps`, `meta`, `runtime`, `events`,
`modules`, `typeRef`, and the residency flags `has_backing_asset`,
`has_runtime_changes`, `cpu_resident`, `gpu_resident`. These are the
behaviours every asset must expose identically, which is why they win.
### Reloading
A `behavior.luau` edit ripples to existing refs with no restart: dispatch
reads `mod.ref` fresh each time and `require`'s cache is re-run in place. A
type whose folder appears at runtime is picked up on the next dispatch —
negative results are not cached either.
## The names your type's assets hold (`references:`)
An asset that names another asset by a string depends on it: the named asset
travels with it into a pack or a pull, and a name nothing answers to is an
unresolved dependency `worldValidation` reports and the push gate refuses. The
engine reads `require(...)` and the asset lookups on its own; a name your type's
format or API carries anywhere else is one you declare, in `type.yaml`:
```yaml
references:
# A top-level key of this type's own files that holds a name (or a table of them).
keys:
- { key: "shader", type: "shader" }
# A call's argument, counting from 1, wherever the call is written.
args:
- { call: "g:node", position: 2, type: "procNode" }
# A field of the options table a call takes.
fields:
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in, one of `asset.categories()`. An
argument declared once per category, at the same `call` and `position`, takes
the name from whichever category answers. A key or a field holds one category:
declared again with another `type`, it takes the later one. The block is
declared as the type registers, when the library or the world holding it is
laid into the VFS, so every reference table reads it whatever script has or has
not run. `asset.declareReferenceKey`, `asset.declareReferenceArg` and
`asset.declareReferenceField` declare the same things from a script, for a
surface that is no type's.
## What search does with your type (`indexing:`)
A type declares what search embeds for its instances. **This is not optional
and there is no useful default**: ZeroMind runs your declaration and adds
nothing of its own, so anything you do not point at is absent from the index —
silently, and for every instance of the type forever. Twenty types once shipped
with no `indexing:` block and every instance of them was unfindable.
A type whose instances are never searchable (a run record, a log) says so with
`indexing: none`; every other type declares a recipe.
A type without an `about.yaml` beside its `type.yaml` refuses every push that
carries it, whether or not the push edited the type. Texts in it that are not
written yet follow the rule every `described` file follows: they refuse the
push that edits, stages or commits the type.
Two words carry the whole thing, and they are the same two the search tool
exposes:
- **`identity`** — what an instance IS. For anything you can look at, that is
the picture (`content:` + `modality: image`, matched directly by a text
query). For everything else it is the authored text that says what it is.
- **`capability`** — what it DOES and how it is made. Code, settings, the
model-written summary of them.
A type with no behaviour has no `capability` entry. A type with nothing to look
at has no image. Leaving a slot empty is a statement; filling it with whatever
happens to be lying around is not.
The one you have to decide when authoring a type is: *for an instance of this,
what is the thing a person would recognise it by, and what is the thing it
does?* A texture answers "the image" and "its compression settings". A module
answers "its README" and "its code". Write those two answers into `indexing:`
and the rest follows.
Three specifics worth knowing before you write one:
- **`derive` is instructed by this type's own `README.md`.** A model reads an
instance's source and writes a description; what it embeds is the
description, not the source. It follows your README to know what it is
looking at, so a type whose README says what its instances are gets good
derivations for free. There is no prompt to name.
- **`derive` loses detail.** It keeps the main technique and drops secondary
ones. If the source is code you want searchable by its own vocabulary,
declare the same files a second time as `capability` with
`extractor: verbatim`. Two entries, same role, different failure modes.
- **Never `source: { field: name }`.** A filename is one or two words with no
usable embedding, and a corpus indexed that way answers "language runtime"
with `say_runtime_2.soundClip`.
`facets:` is the second stage: a `file:` embedded whole (`.metadata`, so keys
nobody declared still get indexed) plus computed keys that state a value for
every instance including `false` — the raw file can imply "not rigged" and can
never say it.
The full schema, every extractor and the facet sources are in
[`assetTypes/README.md`](../README.md); the scaffolded block with inline
guidance is in [`template/type.yaml`](template/type.yaml).
## A container whose contents work together (`system: true`)
A type that is a container can say its contents are one working whole by
declaring `system: true` at the top level of its `type.yaml`. `package` declares
it: the components, modules, scenes and tools a package ships are parts of one
system. The declaration is plain data, read from the decoded `type.yaml`
(`require("@builtin::assetTypes.assetType.shared.declaration").of("package").system`),
and a type that leaves it out is an ordinary type.
## What your type looks like (`preview:`)
A type declares how its instances are pictured, and the engine makes the
picture when something needs it: staging an instance whose `preview.png` is
missing or pictures content it no longer holds queues a render, a view that
shows the instance asks for one, and `ref:preview()` renders one on demand. An
edit renders nothing on its own. Each `preview.png` records the content it
pictured, which is how a stale one is told from a current one. The preview studio owns the light, the
backdrop, the framing and the camera, and nothing in the world reaches it, so
an instance pictures the same in every world. Declare one of four recipes:
| `kind` | The picture is | Your type provides |
|---|---|---|
| `instantiate` | the asset stood in the studio through its own `instantiate` | `ref.instantiate` |
| `image` | a file the instance holds, fitted to the frame, nothing rendered | `source.files`, the candidate files in order |
| `surface` | the asset painted on a builtin mesh | `mesh`, and `ref.previewMaterial(self) -> { material }` |
| `custom` | whatever `ref.preview(self, opts)` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
A scene-instantiable type that declares nothing still answers `ref:preview()`
through its `instantiate`, but persists no picture: the declaration is what
makes the engine keep one. List `preview.png` among the type's files so an
instance may hold it.
The picture is findable only when `indexing.content` names it. The two are
separate statements, and neither is derived from the other:
```yaml
indexing:
content:
- role: identity
modality: image
source: { file: "preview.png" }
```
`@builtin::assetTypes.assetType.shared.previewRecipe` reads the declaration;
the scaffolded block with inline guidance is in
[`template/type.yaml`](template/type.yaml).
## Typing a result from the instance (`M.refShapes`)
Every method on `M.ref` is checked against the type its `--!return` names,
and every asset of the type gets the same one. That is right for most
methods and wrong for the ones whose result is shaped by the ASSET: a
method answering one entry per child folder, per row of a config, per
binding an input map declares. The widest true annotation for those is
`{ [string]: Thing }`, and an indexer accepts every key — so a caller's
typo reads as valid and nothing reports.
`M.refShapes` lets the type state the result per instance. Each entry is
`function(self) -> (typeExpression, source?)`: a Luau type expression for
THIS asset, and the module whose type vocabulary the expression uses.
Read the asset; never run it — stating a type must not take effect.
```lua
-- inputMap.assetType/behavior.luau — the shipped example.
-- `activate()` hands back one handle per control the map declares.
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)` resolves and `map.noexisting` is
reported with the map's real controls. Without it, both pass silently.
### What the call site has to say
A per-instance type is matched by the asset's IDENTITY, so it applies only
where the reference the method is called on says WHICH asset. Two spellings
do:
```lua
-- a component field, whose declared default names the asset
public = { map = Field.assetRef("inputMap", "@builtin::inputMaps.default", Sync) }
local controls = public.map:activate() -- typed for THAT map
-- an annotation, naming category and identity
local m: AssetRef<"inputMap", "@builtin::inputMaps.default">
```
`asset.resolve("<identity>", "<category>")` carries the CATEGORY, so the
methods the category defines are checked on the result — but not which
asset it found, so a per-instance result keeps the category's declared
return. A reference that names no asset (`asset.resolve(someVariable)`, a
value passed in as a parameter) carries neither, and calls on it are
unchecked. That is the same rule everywhere: the checker states what the
code states, and a name computed at runtime states nothing.
### The result is a value, not a binding
The type belongs to the expression, so it travels the way any inferred type
travels. Indexing the call's result is checked; stashing it in a module
local and indexing it from another function is not, because the local's
declared type is what carries across — and `any` (or no annotation) carries
nothing:
```lua
-- checked: `d.greting` is reported
function awake()
local d = public.dialogue:lines()
d.greeting:say()
end
-- NOT checked: `lines` is a module local typed `any`
local lines: any = nil
function awake() lines = public.dialogue:lines() end
function start() lines.greting:say() end
```
Bind what you need at the call site and the names stay checked in both
places — the asset-derived type at the boundary, ordinary scoping after it:
```lua
local lineGreeting = nil
function awake()
local d = public.dialogue:lines()
lineGreeting = d.greeting -- `d.greting` is reported here
end
function start() lineGreeting:say() end
```
### When nothing is reported and you expected something
From a call site, a type that is correct and a type that was never published
look the same: no diagnostic either way.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` answers which it
is. It returns two maps — the category surfaces, and the per-asset results
keyed by identity and then by method:
```lua
local shapes = require("@builtin::assetTypes.assetType.shared.refShapes").published()
shapes.categories.dialogue
--> "{ lines: () -> any, lineNames: () -> { string } }"
shapes.returns.Shopkeeper.lines
--> "{ browsing: Line, farewell: Line, greeting: Line, wares: Line }"
```
An identity absent from `returns` was never published for, which is a
different thing from published-and-correct — and the reason to look here
rather than at the call site.
The answers are recomputed when an instance is written, so a control added
to a map reaches the checker with no restart. Only types that declare
`refShapes` are read per instance, and at most 64 assets of one type are —
past that the type keeps its declared return and the engine log names what
was dropped.
## The instantiate hook (`M.ref.instantiate`) — a contracted return
A type opts into becoming part of the scene by defining `instantiate` on its
`ref` table. That is the whole opt-in: `ref:canInstantiate()` is true exactly
when the hook exists, so consumers offer a scene path — an `Asset.source`
field, a viewport drop, a tool argument — by CAPABILITY rather than by a list
of type names.
Unlike `inspect`, this hook's **return is a contract**. A caller writes one
piece of code against every instantiable type, so what comes back cannot vary
by type:
```lua
-- behavior.luau
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
local M = {}
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts) -- IN: the base opts
-- ... compose whatever this type is, under `root`, NOW ...
return Instantiable.result(self, root, idMap) -- OUT: the contract
end,
}
return M
```
**IN.** `target` is an owning entity ref: the instance lands under (or, for a
hierarchy type, onto) that owner. With no target the type spawns a fresh root.
`position`, `rotation`, `scale`, `name` and `temporary` mean the same for every
type — `Instantiable.root` applies them to a root you mint, `Instantiable.place`
to one you adopt, so you never re-read the spec. Honour more opts of your own if
your type needs them, and document them in the hook's `--!arg` docs.
**OUT.** Return `(root, idMap)` through `Instantiable.result`:
- **`root`** — the composed root, as an `EntityRef`. Composition is
**synchronous**: everything your type builds is live when you return, so the
caller can parent to it and read its components in the same statement. Do not
defer the work to a component's `awake` and return an empty shell — a root
that is not live is refused.
- **`idMap`** — the `originalId -> runtimeId` map naming what you spawned, or
nil for a type with no addressable children (`result` normalises it to `{}`).
**A caller never receives nil.** A component that re-composes your asset on
every load keeps this map and passes it back in, which is how a cross-entity
reference into the composition survives a reload.
`AssetRef` runs every `instantiate` through `result` on the way out whether or
not your type called it, so returning something else fails at your own call
rather than handing a caller a nil root. Calling it yourself is still how you
say what you return, and running it twice changes nothing.
`@builtin::assetTypes.assetType.shared.instantiable`'s README is the full reference for both halves.
## The inspect hook (`M.ref.inspect`)
`asset.inspect(ref)` resolves `ref`, builds a common envelope shared by
every asset (`identity`, `name`, `guid`, `source`, `typeName`,
`typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then
calls the resolved type's own inspect hook — `M.ref.inspect(self)` on
`behavior.luau` — for the type-specific `detail`. The hook returns
*only* `detail`; the framework fills in everything else:
```lua
-- behavior.luau
local M = {}
M.ref = {
inspect = function(self)
-- self.path is the asset's own folder. Parse the asset's OWN
-- files — source text, a native payload header, its `.metadata`
-- — never runtime state (a live component instance, a GPU
-- upload, a compiled schema): inspect must work on an asset that
-- hasn't been compiled, uploaded, or registered yet.
return {
-- type-specific fields, whatever this type wants to surface
}
end,
}
return M
```
A type that omits `M.ref.inspect` yields the generic record: the
envelope alone, `detail = nil`. That's a valid, working state — not an
error — but it means agents calling `asset.inspect` /
`tools.use("assets","describe", ...)` on an instance of the type see
only identity and scope, none of what makes an instance of it
meaningful. Declaring the hook is what makes a type's instances
inspectable for what they actually are.
A hook that raises leaves `detail = nil` and sets `record.warning` to
the error text — `asset.inspect` itself never raises for a resolved
ref.
## Discovery
- `asset.list("assetType")` — every registered asset type.
- `asset.inspect("<typename>")` — the type's identity, source path, and
this README, plus its `about.yaml` texts as `detail.about`.
- `asset.resolve("<typename>", "assetType")` — the `<typename>.assetType`
asset itself (used by the validator to find the type's `type.yaml`).
## Related
- `assetTypes/README.md` — the full `type.yaml` schema and validator
rules.
- `@builtin::assetTypes.assetType.shared.instantiable` — the instantiation contract's shared
implementation, both halves.
- Every other `*.assetType/` here — the concrete types built on this
meta-type.
## The Inspector a type ships
Every type names the file its Inspector sections come from with `inspector: { type: "inspector.luau" }` in its type.yaml. `asset.create("assetType", name)` scaffolds the block and an `inspector.luau` whose Contents section lists an asset's files, built from `ctx.parts`. `asset.validate` on a type that names none reports `assetType.inspector_required` (an error for a `@builtin` type the engine's library authors; a warning for a world's own, and for one the library carries by reference, which the world that published it answers for), and one whose file does not load `assetType.inspector_invalid`.
## In the Inspector
Type: what the type.yaml declares (suffix, container, primary files, the settings and inspector blocks), whether the type ships a behavior, how many instances it has, and **Open** for its files. Schema: the settings every instance carries, as read-only typed controls at their defaults (a type whose schema is per instance says where it is declared). Instances: a link to each of the first 20 assets of the type, and how many there are when there are more.
# frame_budget
The share of a frame that cooperative engine work spends before it hands the
frame back.
Some engine work is one long sequence of small units run on a task: a scene
load applies one record after another, and the world-load `onRegister` sweep
fires one instance's hook after another. Run back to back in one frame, a long
sequence holds that frame for its whole length, and nothing else the engine
does (answering a call, drawing, input) happens until it is through. Asking
`due()` before each unit and yielding when it answers true runs the same work
across as many frames as it needs, a slice of each.
```luau
local FrameBudget = require("@builtin::modules.frame_budget")
for _, item in ipairs(items) do
FrameBudget.yield()
process(item)
end
```
- **One slice per frame, shared.** The slice opens at the first call any caller
makes in a frame, and every unit run after it in that frame is charged to it,
whoever runs it. Two long pieces of work running at once share a frame's
slice rather than taking one each.
- **A unit is never split.** The first unit of a frame always runs, so a frame
holds at most the slice plus the one unit that crossed it. A unit that is
itself long stays one piece of work.
- **Code that cannot yield runs in its frame.** `due()` answers false outside a
coroutine that can yield, so a caller called from such code does all its
units in the frame it was called in, as it would without the budget.
A caller that does work of its own around the yield asks `due()` and calls
`wait()`, which yields to the next frame and opens that frame's slice as the
caller resumes; `yield()` is the two together.
Work whose unit is a native call that bounds itself by time is told how long
it may run: `remainingMs()` answers what is left of the current frame's slice,
or nil for code that cannot yield, which then runs the whole of its work in the
frame it was called in. The publish gate's script check runs this way:
```luau
local block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs())
while checking do
FrameBudget.wait()
block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs())
end
```
`FrameBudget.DEFAULT_MS` is the slice a call that names none spends. `spent()`
answers how much of the current frame's slice is gone.
# Shader (asset type)
A shader is a WGSL program that runs on the GPU. Materials reference shaders and
supply property values; renderable entities reference materials, not shaders
directly. This README is the canonical reference for writing **every** kind of
shader — it covers all domains, the surface authoring contract, the material
property schema, the engine library functions you can call, and how a shader
registers and compiles.
> New to how shaders, materials, meshes, and textures relate as assets and live
> GPU resources? Read `core/resource-model` first.
## Folder shape
A `.shader` is a folder asset:
```
<name>.shader/
shader.wgsl # the WGSL body (required)
properties.yaml # the material property schema (optional; surface shaders)
README.md # a one-paragraph description of THIS shader (required)
.metadata # asset metadata
```
Each file carries a committed `.meta` sidecar pinning its stable guid. The
identity is `<name>` (the `.shader` suffix strips). Materials and other assets
reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw
string.
## Domains
The first line of `shader.wgsl` declares the domain:
```wgsl
// @domain: surface
```
| Domain | What it is | You write |
|---|---|---|
| `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. |
| `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `compute` | GPU data processing, no rasterization. | *(legacy)* An `@compute @workgroup_size(...)` entry over storage buffers — you write the `@group/@binding` lines yourself. **The canonical path is now the separate `.computeShader` assetType** (see below); `.shader` + `// @domain: compute` still compiles for back-compat. |
`// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui`
as further spellings of `post-process` and `screen`. A body carrying no
`@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body
declares, a further spelling as the domain it names. Any other name is refused where the shader
registers, with an error naming the spellings that resolve, so a shader reaches
the renderer only under a domain the compiler scaffolds.
Particles are drawn and simulated through these domains like anything else: the
particle package's `particle_sprite` and `particle_mesh` are `surface` shaders,
and its simulation, culling and sorting steps are `.computeShader` assets.
## Texture coordinate space
A shader that samples a texture through a coordinate it builds itself declares
which space that coordinate lives in, on a line beside `@domain:`:
```wgsl
// @domain: surface
// @uv_space: world
```
| Value | The coordinate | A material's `uv_scale` means |
|---|---|---|
| `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. |
| `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. |
Texture residency reads the declaration to work out how finely a frame samples
each texture: a material laying eight copies of its texture across a surface
samples each copy at an eighth of the surface's size, and the mip level that
serves it is three levels coarser than the surface's own footprint implies.
Leaving the line out puts the shader in mesh space, which is what sampling
`input.uv` is. `renderer.textureStreaming().textures` reads back the span each
texture was measured at and the level that span asked for.
**Compute shaders are now their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`. The `.shader` compute domain above remains only for back-compat.
**Surface**, **sky**, **post-process**, and **screen** shaders all get
engine-generated scaffolding — you write only `fragment()` and declare properties in
`properties.yaml`; the engine generates the entry points and the group(1) material
interface. (Each domain's `fragment` takes a domain-specific input instead of
`FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and
"Post-process & screen shaders" below.) Compute shaders get the same treatment via
the separate `.computeShader` assetType (write only `@compute fn main`, declare
bindings in `bindings.yaml`). The legacy `compute` domain here writes its own
entry points directly — see `man compute`.
## Surface shaders
A surface shader writes **only** the parts that are unique to it. The engine owns
all the scaffolding — the vertex stage, every render-mode entry point
(`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights,
shadows, and the material rows), and the material interface generated from
`properties.yaml` (`material` and your texture slots). Adding a render path never
touches your shader.
Inside `fragment()` you have access to exactly four things — nothing is hidden:
1. **`input: FragmentData`** — the interpolated per-fragment surface data the
engine hands you: world position, world normal, uv, view direction, vertex
colour, and more. Every field is in the `FragmentData` table below.
2. **`material.*` and your textures** — the material inputs **you** declare in
`properties.yaml`. The mapping is mechanical: a scalar property named `foo`
becomes `material.foo`; a texture property named `bar` becomes `bar` (the
texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields
your `properties.yaml` declares and no others — to add an input, add a property.
List what a shader exposes with `shaderRef:getProperties()` or
`asset.inspect("<name>")`.
3. **Engine state** — the scene's camera, lights, time, and shadows that the
renderer binds for every surface shader. `uniforms.*` (sun direction/colour,
ambient, `camera_pos`, `time`) and the punctual lights (`zero_point_light(i)`)
are always in scope; the shadow functions come from `#include "@builtin::shaderModules.shadows"`. This is how
you light a surface **without** the prebuilt PBR — see "Engine state" and
"Writing your own shading" below.
4. **Library functions** you `#include` (see "Library includes").
A shader and its property schema go together. The two files below are a complete
surface shader:
`properties.yaml` — declares the material inputs:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: base_color_texture, type: texture, default: white }
```
`shader.wgsl` — those declarations are now `material.base_color`,
`material.roughness`, `material.metallic`, and the `base_color_texture` /
`base_color_texture_sampler` pair:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes"
fn fragment(input: FragmentData) -> vec4<f32> {
var s = zero_pbr_default_surface(input);
s.albedo = material.base_color.rgb
* textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb;
s.perceptual_roughness = material.roughness;
s.metallic = material.metallic;
return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a);
}
```
`fragment()` returns the final colour. The engine forces no lighting model on
you — flat, toon, PS1, dithered, or PBR are all just different `fragment()`
bodies. Calling `zero_pbr_shade` is opt-in.
### The two surface bodies, and what each gives up
A surface shader exposes one of two entry points, and which one decides how
much of the shader the engine can see:
| Body | The engine gets | PBR debug passes read |
|---|---|---|
| `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the `PbrSurface` too when the body hands one to `zero_pbr_shade` | the real channel where a surface was handed over; magenta, the "no data here" marker, where the body shades by its own math |
| `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the real channel |
Both are first-class: `fragment()` is what you want when the shader owns its
own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }`
(and `roughness` / `metallic` / `ao` / `emissive`) answers about your material
for either body wherever the engine has the surface — writing the same
`PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives
one answer per channel. A body that lights itself by its own math draws those
channels magenta. `pbr.shader` exposes `surface()`.
`capture { pass = "normal" }` is a geometry read rather than a material one, so
it answers for every shader: the normal of the surface where one was handed
over, and the interpolated normal of the triangle where none was. It is the same
normal the frame's normal buffer carries, which is what a screen-space pass
reading `@scene.normal` sees.
`shaderRef:shadingModel()` reports which one a shader ended up with —
`"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`.
### Optional vertex hooks
```wgsl
// Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the
// already-skinned, morph-applied local position). Return the modified vertex.
// The `v` parameter is immutable (WGSL function params are), so copy it into a
// `var` first and modify that.
fn vertex(v: VertexData) -> VertexData {
var out = v;
out.position += out.normal * sin(out.time) * 0.1;
return out;
}
// Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two
// things you can do here, separately or together:
// * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering;
// * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its
// world_normal + the light context and the engine forwards the result into the
// interpolated `vertex_color` the fragment reads.
fn vertex_clip(v: ClipVertex) -> ClipVertex {
var out = v;
// Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading).
let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0);
let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l;
out.color = vec4<f32>(v.color.rgb * lit, v.color.a);
out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap
return out;
}
```
#### Declaring how far a hook moves geometry: `vertexBoundsDilation`
Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges:
```yaml
properties:
- { name: sway, type: float, default: 0.5, min: 0, max: 4 }
# 0.4 x sway, at sway's largest value.
- { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 }
```
Each material sets its own value — a material that sways less can set less, one moved farther sets more — and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; its geometry is culled against its undisplaced bounds.
### Structs the engine passes you
`FragmentData` (input to `fragment()`):
| Field | Type | Meaning |
|---|---|---|
| `world_position` | `vec3<f32>` | fragment world-space position |
| `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) |
| `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) |
| `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) |
| `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping |
| `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) |
| `view_position` | `vec3<f32>` | camera world position |
| `view_direction` | `vec3<f32>` | normalized world-space direction to the camera |
| `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down |
| `light_color` | `vec3<f32>` | sun colour |
| `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera |
| `ambient_color` | `vec3<f32>` | ambient colour |
| `ambient_intensity` | `f32` | ambient intensity |
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither |
| `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows |
| `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name |
| `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes |
| `front_facing` | `bool` | true for front faces (double-sided shading) |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
`shader_data` is the per-instance channel, and it is what lets ONE material serve
many entities that differ in a value — a dissolve at its own progress per subject,
a hit flash at its own age, a fill level per instance. The alternative is a
material per entity, which is a separate pipeline binding and a separate row in
the material table for every one of them.
```wgsl
const DISSOLVE_LANE: u32 = 0u;
fn fragment(input: FragmentData) -> vec4<f32> {
let progress = input.shader_data[DISSOLVE_LANE].x;
...
}
```
```lua
-- one material on twenty entities, each at its own progress
renderer.instanceData.set(subject, 0, progress)
renderer.instanceData.clear(subject) -- back to zero lanes
```
The engine attaches no meaning to a lane: a shader and whatever writes it agree
what each one carries. Name the indices in the module that writes them.
`renderer.instanceData.laneCount()` is how many there are. The same lanes reach a
hardware-instanced population through `renderer.mesh.drawInstanced`'s
`instanceDataBuffer`, on slots no entity owns.
`VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph
applied), `normal`, `uv`, `color`, `time`.
`ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context:
`clip_position`, `world_position`, `world_normal`, `uv`, `view_position`,
`view_direction`, `light_direction`, `light_color`, `light_intensity`,
`ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of
the frame being evaluated), and where the vertex stands on its instance:
`local_position` (its position in the mesh, after `vertex()` and before the
instance's world transform), `object_origin` (the world position of the instance's
origin), `object_scale` (the world length of the instance's x, y and z axes) and
`object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) —
what a camera-facing card, a shard grown about its own base, or anything placed
per instance is built from. **Writable:** `clip_position` (snap /
jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the
engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's
own vertex colour passes through).
### Each hook runs twice: this frame and the one before it
A vertex hook decides where the surface IS, so it also decides where the surface
WAS. The engine runs every hook a shader declares a second time, over the same
vertex standing one frame back — the previous-frame position stream, with
`time` = the clock that frame was drawn at and (for `vertex_clip()`)
`view_proj` = the view-projection it was drawn with. The motion vector the
renderer publishes is taken between the two results, so a displacement that
moves with time reports the velocity of the displaced surface, and a
displacement that does not move reports the motion of the transform alone
because the identical offset appears on both evaluations and cancels.
What that asks of a hook:
- **Take the frame from the argument.** `v.time` is the clock of the evaluation
being run; `uniforms.time` is always this frame's. A displacement built on
`uniforms.time` is identical on both evaluations, so its motion vector cancels
to exactly zero. The same holds for `v.view_proj` against
`uniforms.view_proj`: a clip hook that rebuilds its position from world space
through `uniforms.view_proj` reprojects the previous frame with this frame's
camera, and reports no camera motion at all. The wind helpers come in both
shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)`
inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one.
- **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously
— a falling drop that restarts at the top, a looping offset — differences its
jump as velocity on whichever frame it wraps. Compute the wrap COUNT from
`uniforms.time` and the position within the cycle from `v.time`, and both
evaluations share the same cycle, so the surface reports the speed it fell at.
`@builtin::shaders.rain_material` and `snow_material` do exactly that.
The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and
camera-position context are this frame's on both evaluations, so a hook that
displaces along its normal reports the motion of the transform plus this frame's
displacement.
## Engine state — point lights & shadows
The common lighting state — the sun (`input.light_direction` / `light_color` /
`light_intensity`), the ambient (`input.ambient_color` / `ambient_intensity`), the
camera (`input.view_position` / `view_direction`), and `input.time` — is already on
`FragmentData`, so most shaders never touch the raw engine state. The one thing not
on `FragmentData` is the punctual-light array (its length varies), which is always
in scope:
| Expression | Type | Meaning |
|---|---|---|
| `uniforms.point_light_count` | `u32` | number of active point/spot lights |
| `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) |
| `zero_punctual_shadow(i)` | `PunctualShadowEntry` | that light's shadow record (its projected map or cube) |
`PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`,
`cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot).
Shadows come from `#include "@builtin::shaderModules.shadows"`:
- `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed.
- `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each.
- `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch.
- `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing.
## Writing your own shading
The engine forces no lighting model — `zero_pbr_shade` is just one option. You can
light a surface yourself from the state above. Here is a complete custom-lit
(Lambert diffuse) surface with no PBR:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.shadows" // exposes compute_directional_shadow_factor
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = material.base_color.rgb;
// Directional (sun) light: Lambert N·L, attenuated by its shadow.
let sun = normalize(-input.light_direction); // surface -> sun
let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction);
var lit = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow;
// Point + spot lights (the punctual-light array, varying length).
for (var i = 0u; i < uniforms.point_light_count; i = i + 1u) {
let pl = zero_point_light(i);
let to_light = pl.position - input.world_position;
let dist = length(to_light);
let l = to_light / max(dist, 1e-4);
let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0);
lit += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten;
}
// Ambient fill.
lit += input.ambient_color * input.ambient_intensity;
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
- **Unlit:** skip the lights and return your colour directly.
- **Toon / PS1 / custom:** start from the loop above and band, quantize, or warp
it however you like.
- **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes")
instead of writing the BRDF by hand.
## Material properties — `properties.yaml`
A surface shader declares its material properties in a sibling `properties.yaml`.
The engine GENERATES the entire group(1) interface from it — the uniform struct
(`material.<name>`) plus a texture/sampler pair per declared texture. You write
no `@group`/`@binding` lines.
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: emissive, type: color, default: [0, 0, 0, 1] }
- { name: base_color_texture, type: texture, default: white }
- { name: normal_texture, type: texture, default: flat_normal }
```
| `type` | WGSL field type | Notes |
|---|---|---|
| `float` | `f32` | optional `min`/`max` for editor sliders |
| `float2`/`float3`/`float4` | `vec2/3/4<f32>` | |
| `color` | `vec4<f32>` | sRGB colour, default is `[r,g,b,a]` |
| `int` | `i32` | |
| `bool` | `u32` | |
| `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) |
In the shader you read scalars as `material.<name>` and sample textures as
`textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture
samples its default, so a shader can always sample — no presence flag needed.
`vertex()` reads the same material interface, so a height or deformation map
drives displacement from the slot it was bound to. A vertex stage has no implicit
derivatives, so sample it at an explicit mip there:
`textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`.
## Sky shaders
A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only**
`fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each
pixel — and declare tunables in `properties.yaml` exactly like a surface shader
(read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`).
The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface,
and reconstructs the world-space ray; there is no separate sky renderer — a sky
material runs through the same material pipeline, just on a fullscreen triangle.
`SkyInput` (the only argument) carries:
| Field | Type | Meaning |
|---|---|---|
| `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel |
| `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` |
| `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) |
| `camera_pos` | `vec3<f32>` | world-space camera position |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
```wgsl
// @domain: sky
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up);
return vec4<f32>(col * material.exposure, 1.0);
}
```
Day/night comes from `sun_direction.y` (the directional light's elevation), so a
sky shader never needs a time-of-day uniform — orient the light and the sky
follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`,
`equirect_sky`) are all authored this way; author a custom sky material and point
a `Skybox` component at it.
## Post-process & screen shaders
`// @domain: post-process` and `// @domain: screen` shaders are authored exactly
like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>`
(post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables
in `properties.yaml` (read as `material.<name>`, textures via
`textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen
`vs_main`/`fs_main` and the group(1) material interface. **There are no
`uniforms.params[i]` slots** — that convention is retired; every input is a named
property.
A **post-process** shader's `properties.yaml` carries one further, top-level key
beside `properties:` — `space`, either `light` (the default) or `display`:
```yaml
space: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
`light` is the scene's linear radiance — what every surface, the sky and every
`afterLighting` feature write, unbounded above 1.0. `display` is the code values
the `__display__` pass leaves behind after applying exposure and its tone curve
— the 0-1 range a colourist's tool and a dithered or quantized effect expect.
`postprocess.add`'s `opts.space` overrides what the asset declares for one
registration. The chain converts at both ends of an effect that runs on a
segment in the other space, so a light-space vignette still darkens a frame
graded after `__display__`, and a lookup table built from a `.cube` export
always sees the code values it was authored against, wherever the chain
runs it.
`space` also decides which layer a registration that names none lands on: a
`light` shader grades `scene`, the segment holding the scene's own light, and a
`display` shader grades `all`, the picture after `__display__` with the UI on
it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom", "shader"))`
thresholds highlights that still stand above 1.0, and a lookup table registered
the same way reads the code values it was built for. `opts.layer` names one
explicitly — `"all"` is what an effect that must grade the interface says.
A **post-process** shader's `properties.yaml` carries a further, optional
top-level key — `passes:`, the pass list the frame draws through, in order:
```yaml
space: light
passes:
- { name: bright, entry: bright, scale: 0.5, inputs: [scene] }
- { name: down1, entry: downsample, scale: 0.25, inputs: [bright] }
- { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] }
- { name: composite, entry: composite, inputs: [scene, up0] }
```
Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the
one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the
view a pass draws at; the LAST pass takes none, since it draws at the view's
size and writes the chain's output. `inputs` names what a pass reads —
`"scene"`, the chain's input for this effect, or the name of an EARLIER pass —
and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body;
every input, `inputs[0]` included, is also reachable by index through
`zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place
the two reads of `inputs[0]` disagree: in an effect whose declared space
differs from the segment it draws on, `zero_sample_scene` converts a `scene`
input into that space while `zero_pass_input(0, uv)` hands back the segment's
own, unconverted value. A shader declaring no `passes:` is one pass whose
entry is `fragment`, and its generated WGSL is byte-identical to what it is
without the key.
A pass that is not the last writes a scratch target the effect owns — in the
space the shader declared, view-sized times its own `scale` — allocated on the
first draw and replaced whenever the size changes. `engine.params`, below,
carries the drawing pass's own index, its scale, and its first input's texel
size, so one shader body serves every level of a chain built this way.
The worked example is the bloom: `@builtin::shaders.post.bloom` declares
twelve passes — a threshold pass, five downsamples, five tent upsamples and a
composite — out of four entries, since the five downsamples share one and the
five upsamples share another, each level reading the one below it through
`zero_pass_input` and telling itself apart by `engine.params`. Its own README
walks the declaration.
A declaration is refused at compile time — reported through `compileStatus()`,
`postprocess.add`'s second return value, or a live effect's
`status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does
not define; an input naming a later pass, or naming neither `scene` nor an
earlier pass; a `scale` outside `(0, 1]`; a `scale` declared on the last pass;
a `buffer` property (group(2) carries the pass inputs now); or a shader whose
group(0) plus declared texture slots plus widest pass's inputs ask for more
than the 16 FRAGMENT sampled textures one shader stage has.
A **post-process** shader runs as a full-screen pass over the already-rendered
frame. Its `fragment` argument and framework helpers:
`PostInput`:
| Field | Type | Meaning |
|---|---|---|
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) |
| `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right |
Framework helpers (always in scope — no include needed):
| Call | Returns | Meaning |
|---|---|---|
| `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) |
| `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" |
| `zero_linear_depth(d, near, far)` | `f32` | that sample as a distance in metres — the one inversion of the reversed range |
| `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` |
| `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads |
| `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain |
Engine data uniform `engine` (a `PostEngineData`):
| Field | Type | Meaning |
|---|---|---|
| `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height |
| `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index |
| `view_proj` | `mat4x4<f32>` | this frame's view-projection |
| `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) |
| `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) |
| `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. |
The engine fills all of it **per render target**. A registered effect runs over
the live viewport's frame AND over every offscreen one — a `capture` from a
world-space station or orbiting an entity, a capture of a named camera, a
render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj`
and `inv_view_proj` are the camera THAT render was drawn from, while
`resolution` is that target's own pixel size. So a pass reconstructing world
space from `zero_scene_depth(uv)` reconstructs against the station and lens the
capture asked for, and an offscreen frame is a picture of the effect as it
stands at that station. (A render feature's passes reach an offscreen render the
same way, against the same camera — the `renderFeature` assetType README carries
that half, including `@frame.camera`, its own per-target camera input.)
An offscreen render keeps no view history of its own, so `prev_view_proj` there
holds that same matrix rather than the frame before it, and a pass taking camera
motion from the two reads none. On the viewport the pair is a frame apart, so
camera motion is the one reading a capture answers differently from the screen.
`postProcessing = false` on a capture is the one control that takes the chain
off the frame it returns; it names the camera property the ephemeral capture
camera is built with, so it scopes to that one capture. What a capture opts out
of is the registered effects; `__display__` still runs on it, so the exposure
and tone curve that turn the scene's light into a picture are on what a capture
returns.
A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses
`__display__` itself, since a channel like that is a reading of the scene
rather than a graded picture of it. The environment-cube capture bypasses it
too, and for the same reason: a probe face carries radiance into the cube
array, and `__display__` would fit that radiance to a display's code values —
a picture of it rather than the value the PBR indirect term multiplies into
its lighting.
A complete post-process effect — a vignette via `fragment()` + `properties.yaml`:
`properties.yaml`:
```yaml
properties:
- { name: intensity, type: float, default: 0.5, min: 0, max: 1 }
- { name: radius, type: float, default: 0.75, min: 0, max: 1 }
- { name: softness, type: float, default: 0.45, min: 0, max: 1 }
```
`shader.wgsl`:
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let color = zero_sample_scene(in.uv);
let intensity = max(material.intensity, 0.01);
let radius = max(material.radius, 0.01);
let softness = max(material.softness, 0.01);
let center = in.uv - vec2<f32>(0.5);
let dist = length(center);
let vignette = smoothstep(radius, radius - softness, dist);
let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity);
return vec4<f32>(darkened, color.a);
}
```
The asset above **defines** the effect. It enters the frame when something
registers it:
```luau
postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 })
```
The registration names no layer, so the effect grades the layer its `space`
belongs to: this vignette reads light, so it runs on `scene`, over the picture
before the UI reaches it. Registering it is the one step that makes it render,
so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards
recompiles every effect registered from it, in place — the pass keeps its enabled
state, priority, layer, tuned property values and bound textures, and draws the
new pixels on the next frame. `postprocess.remove(name)` takes it back out of the
chain and leaves the asset alone.
Drive the named properties at runtime with `postprocess.setProperty(name, prop,
value)` and bind texture properties with `postprocess.setTexture(name, prop, path)`
(both keyed by the **property name**, never a slot index — see the post-process
section of `man shaders` / the `postprocess.*` API).
Read them back with `postprocess.describe(name)`: it carries the chain state
`postprocess.status()` lists for that effect, the `properties` schema it was
registered with, and the `values` each of those properties currently holds. Before
the effect exists, `shaderRef:getProperties()` on the asset names the same schema,
so what a pass takes is answerable either side of the registration.
A **screen** shader is a standalone full-screen visual (UI background, procedural
pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene
to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a
`ScreenEngineData`:
| Field | Type | Meaning |
|---|---|---|
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `scroll` | `f32` | UI scroll offset |
| `resolution` | `vec2<f32>` | render-target size in pixels |
| `mouse` | `vec2<f32>` | mouse position |
| `velocity` | `f32` | scroll velocity |
```wgsl
// @domain: screen
fn fragment(in: ScreenInput) -> vec4<f32> {
let t = engine.time * 0.5;
let col = vec3<f32>(
sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5,
sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5,
material.brightness
);
return vec4<f32>(col, 1.0);
}
```
## Library includes
A library module is a **`.shaderModule` asset**: it only EXPOSES functions and
structs and does nothing on its own (exactly like a Unity `.cginc`). You must
call what you include. Include one by its identity, the same string you would
hand `asset.resolve`:
| Include | Exposes |
|---|---|
| `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting) |
| `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)` |
| `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access |
| `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions |
| `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) |
| `@builtin::shaderModules.depth` | `zero_linear_depth(depth, near, far)` — the one reading of a stored depth |
| `@builtin::shaderModules.gbuffer_material` (`zero::gbuffer_material`) | `struct ZeroGbufferMaterial { base_color, metallic, perceptual_roughness }`; `zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial`; `zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial`, `zero_gbuffer_base_color`/`zero_gbuffer_metallic`/`zero_gbuffer_roughness(t, coord)` — the one unpacking of `@scene.material`'s `Rgba8Uint` texel into what a surface reflects |
| `zero::scene_depth` | `zero_scene_depth(px: vec2<f32>)`, `zero_scene_depth_uv(uv: vec2<f32>)`, `zero_scene_depth_texel(px: vec2<i32>)`, `zero_scene_depth_size()`, `zero_scene_depth_is_sky(d: f32)`, `zero_scene_world_position(px: vec2<f32>)`, `zero_scene_world_normal(px: vec2<f32>)`, `zero_scene_depth_fade(px: vec2<f32>, world_position: vec3<f32>, fade_distance: f32)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The depth already drawn UNDER a surface fragment, and the world position and geometric normal of the surface standing there. What a decal projector box, a soft particle, a forcefield or water intersection foam shades against. Surface domain; the depth belongs to the view being drawn |
| `zero::scene_color` | `zero_scene_color(px: vec2<f32>)`, `zero_scene_color_uv(uv: vec2<f32>)`, `zero_scene_color_texel(px: vec2<i32>)`, `zero_scene_color_size()`, `zero_scene_color_refract(px: vec2<f32>, offset_px: vec2<f32>)`, `zero_scene_color_refract_uv(px: vec2<f32>, offset_fraction: vec2<f32>)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The scene colour already composed BEHIND a surface fragment, and the displaced read that bends it. What heat haze, a refraction shockwave, a cloaking or shield warp, glass and ice shade with. Surface domain; the colour belongs to the view being drawn, and is the lit opaque scene as it stood immediately before the transparent pass — so a `blend`-queue surface reads this frame's, an opaque one reads the previous frame's, and two overlapping blended surfaces both read the same picture and do not bend each other |
`asset.list("shaderModule")` enumerates the `.shaderModule` assets in this
engine, builtin and world-authored alike, and each one's README says what it
exposes. Those are the `@builtin::shaderModules.*` rows above; a module you
write is included exactly the same way, by its own identity or by the
package-relative `~.name` form.
The `zero::`-named rows come from the renderer itself. Their WGSL is baked into
the engine binary and registered under those names before any asset exists, so
they answer an `#include` in every engine and appear in no asset index. A shader
that includes one records no dependency on it: the engine reading the shader is
the engine that already holds the module.
Two spellings reach the same `.shaderModule`: an earlier name is kept working
through the module's declared alias, so a shader written against `zero::pbr`
still compiles and still pins the asset that name resolves to. Newly written
shaders should use the identity — it says which asset travels with the content.
Whichever punctuation an include is written with — `#include "name"`,
`#include 'name'` or `#include <name>` — names the same module and records the
same dependency.
The engine's own scaffolding — `zero::surface`, `zero::sky`, `zero::post`,
`zero::screen` — is injected by the compiler around the matching domain and is
never written by hand. The surface framework puts `safe_normalize`,
`mat3_from_mat4` and `apply_normal_map(FragmentData, tangent_normal)` in scope
for every surface shader.
## Shader features — compile-time variants
A **property** is runtime uniform data (a colour, a float, a texture): set per
material, read as `material.<name>`, no recompile. A **feature** decides which
code is in the program at all. Use a property when the value changes at runtime,
a feature when it changes what the shader is.
Declare features in `properties.yaml`, alongside the properties:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
features:
- { name: PARALLAX, default: false, description: silhouette parallax march }
- { name: DETAIL, default: true, description: detail-normal overlay }
```
Guard the code each feature owns with `#ifdef`:
```wgsl
fn surface(input: FragmentData) -> PbrSurface {
var s = zero_pbr_default_surface(input);
#ifdef PARALLAX
s.normal = parallax_normal(input); // absent when PARALLAX is off
#else
s.normal = input.world_normal;
#endif
return s;
}
```
`#ifdef` / `#ifndef` / `#else` / `#endif`, one per line, and they nest. The
directives resolve before the WGSL reaches the compiler, so the program holds
exactly the lines its feature set selected and every other line is an empty one,
which keeps a compiler message on the line number the file shows. An unbalanced
block is a compile error naming its line.
A material is what chooses a feature set, so `features:` shapes the shaders a
material draws with — the surface, sky and screen-space domains.
A material names the features it wants in its `mat.yaml`:
```yaml
name: worn_rock
shader: "@builtin::shaders.pbr_layered"
features:
PARALLAX: true # on, over the shader's default
DETAIL: false # off, against the shader's default
```
or through `asset.create`:
```lua
asset.create("material", "worn_rock", {
shader = "@builtin::shaders.pbr_layered",
features = { PARALLAX = true, DETAIL = false },
})
```
The engine compiles one program per feature set its materials ask for, named
`<shader>#<features>`. Materials sharing a set share that program. A feature the
shader does not declare selects nothing, so a stray name cannot make the engine
compile anything, and the compile names both halves of a mismatch: a guard on a
name `features:` does not declare, and a declared name no guard tests.
**Permutations are the cost.** A shader with n features can express 2^n
programs, each its own compile and pipeline. One shader holds at most 32
variants; a material asking for a set past that draws with the shader's default
features and the engine logs which shader ran out. Read what a scene is
spending:
```lua
for _, s in renderer.shaderVariants() do
print(s.shader, #s.variants, "of", s.budget)
print(renderer.variantSource(s.base.program)) -- what it ships as
for _, v in s.variants do
print(v.program, renderer.variantSource(v.program)) -- what one asked for
end
end
```
A shader registers under every key it answers to — its identity, its guid, each
alias — and each key is a row. A variant lands on the row for the key the
material named, which for authored content is the guid, so take a program name
from the report rather than composing one.
## Materials reference shaders
A `.material` applies a shader to entities. Its `mat.yaml` references the shader by
its identity string and supplies property values:
```yaml
name: my_material
shader: "@builtin::shaders.pbr"
render:
blend: alphaBlend
cull: back
depth_write: false
floats:
roughness: 0.5
colors:
base_color: { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
textures:
base_color_texture: { ref: "default:white" }
```
`shader:` is a plain identity string, and each `colors:` entry is an
`{ r, g, b, a }` map — the two forms `mat.yaml` accepts for those keys. A key's
value is the rest of its line, so every value above stands alone on one.
### The render block
Render behaviour that used to be material "flags" — the blend equation, alpha
cutout, which faces are drawn — lives in the `render:` block and drives the
pipeline, not the fragment. These are the keys that reach the pipeline from both
authoring routes, and the values each one takes:
| Key | Values | Sets |
|-----|--------|------|
| `blend` | `opaque` `transparent` `alpha` `alphaBlend` `additive` `add` `cutout` `alphaCutout` `premultiplied` `premultipliedAlpha` `multiply` | the equation the fragment composites with |
| `cull` | `back` `front` `none` `off` `disabled` | which faces the rasterizer keeps |
| `depth_write` | `true` `false` | whether the draw writes depth |
| `depth_compare` | `less` `lessEqual` `lequal` `equal` `greater` `greaterEqual` `gequal` `always` `never` | the test a fragment's depth passes |
| `topology` | `triangleList` `lineList` `lines` `line` | what consecutive vertices assemble into |
`blend` is also spelled `type`, and the two name one key. Its equations, over
the fragment the shader returned (`src`) and the value already in the target
(`dst`): `opaque` is `src`; `transparent`, `alpha` and `alphaBlend` are
`src * src.a + dst * (1 - src.a)`; `additive` and `add` are `src + dst`, the
mode a glow, a light shaft or a spark card is written for; `premultiplied` and
`premultipliedAlpha` are `src + dst * (1 - src.a)`, taking a source that already
carries its own coverage; `multiply` is `src * dst`, which is how a soot, grime
or shadow card darkens what stands behind it. `cutout` and `alphaCutout` keep
the fragment or discard it on its alpha and go on writing depth.
The same block is what `asset.create`'s `render` argument takes, key for key and
value for value, so one material named in Luau and the same material standing on
disk ask for their pipeline with the same words. `depth_write` is the one key
whose value takes the shape of its route: the word `false` on a `mat.yaml` line,
the boolean `false` in the Luau table.
```lua
asset.create("material", "heat_plume", {
shader = "@builtin::shaders.pbr",
render = { blend = "alphaBlend", cull = "none", depth_write = false },
})
```
Where a value outside a key's set is reported is what the two routes differ on.
`asset.create` refuses the call on any of these keys and names the set it
measured the value against. A `mat.yaml` standing on disk registers either way,
each key falling back to a value of its own: `blend` to `opaque`, `cull` to
`back`, `depth_write` to `true`, `depth_compare` to `less` and `topology` to
`triangleList`. The engine log carries the blend fallback, naming the value and
the set it was measured against, so a `mat.yaml` value is worth putting through
`asset.create` once — that is where every key answers with its set.
## Registration & hot reload
A `.shader` is compiled by the asset system, not by the renderer: writing
`shader.wgsl` or `properties.yaml` fires the `.shader` assetType's `onChange`,
which calls `shader.compile` — that reads the body + the property schema, generates
the group(1) interface and (for surface) every render-mode entry point, expands
`#include`s, **validates the result with naga**, and registers it. Validation
happens at this compile step — the whole point of "compile". A shader with invalid
WGSL (an unknown field, a type mismatch, an undefined function) **fails to compile**
with the real reason — readable directly from Luau via
`shaderRef:compileStatus()` (`{ status = "compiled" | "failed" | "pending",
error?, pending? }`), and also in the author log and `asset.inspect`; it is **not**
registered. This fires on create and on every edit, so saving a `.wgsl` recompiles
with no world reload; the change is visible on the next frame. Compilation is
async, so a `compileStatus()` of `"pending"` immediately after a write means check
again next frame.
A surface shader is also checked for the material resolve, the pass that
shades each pixel of the visibility buffer through the shader's own code. That
check reaches its verdict a few frames after the raster compile. Until it
does, `compileStatus()` reads `"pending"` with `pending` saying so, and the
shader already draws. A shader the check refuses reads `"failed"`, and `error`
names the construct the resolve cannot evaluate and where it sits; its pixels
resolve through the error shader until it changes.
The stage the compile checks comes from one of two places: the hook the engine
scaffolds entry points around (`fragment()`, or `surface()` for an engine-lit
surface), or the `vs_main` / `fs_main` pair the body writes itself. The pair is
a pair: a body that writes its own entry points owes both stages. A body
carrying neither route — a hook whose name is a letter off, say, or half a pair
— holds no stage the rasterizer can enter, so the compile **refuses it** and
names both the entry point it looked for and what the body carries, in the same
`compileStatus()` error every other compile failure reads back through.
### Reading a compile error against the text it is about
What the compiler reads is not the file you wrote. The engine generates the
group(1) material interface from `properties.yaml`, wraps the body in its
domain's framework and every entry point that domain needs, expands every
`#include`, and resolves every `#ifdef` — so a 100-line body reaches naga as
tens of thousands of lines. **Every line number in a compile error, and every
`[N]` handle index naga prints where it has no name to print, is a position in
that composed module.** A fault at module scope (`no definition in scope for
identifier: 'zero_scene_depth'`) reads fine without it; a fault inside a
function body does not.
`renderer.compiledSource(name)` returns that composed module, and
`shaderRef:compiledWgsl()` returns it for a ref you already hold. Both answer
for a shader that declares no features, needs no material, entity or draw, and —
the case they exist for — **answer for a shader whose compile failed**, holding
the text the compiler was refused over for as long as `compileStatus()` reports
that failure. `renderer.compiledShaders()` lists every name they answer for.
```lua
local ref = asset.resolve("myShader", "shader")
local status = ref:compileStatus()
if status.status == "failed" then
print(status.error) -- the line, the caret, and the cause
local wgsl = ref:compiledWgsl() -- the text those positions are in
local line = tonumber(string.match(status.error, "wgsl:(%d+):"))
print(string.split(wgsl, "\n")[line])
end
```
The composed text carries every `zero::*` module the shader included, so the
signature a call was rejected against is in the same text as the rejection —
which is the whole of what a "wrong argument type" error needs to be actionable.
A material bound to a broken (or missing) shader renders with the **magenta error
shader** — never invisibly — so a shader problem is impossible to miss on screen as
well as in the log. **Fixing the shader and re-saving recovers it live**, with no
engine restart: the recompile clears the failed-shader state and the object returns
to normal on the next frame.
## Discovery
- `asset.list("shader")` — every registered shader.
- `asset.inspect("<name>")` — domain, status, source, parse errors, this README.
- `shaderRef:compileStatus()` — did it compile? `{ status, error?, pending? }`, no
log needed. `"pending"` with `pending` set means the material resolve check
is still reaching its verdict; a resolve refusal reads as `"failed"`.
- `shaderRef:compiledWgsl()` / `renderer.compiledSource("<name>")` — the WGSL the
compiler received, which is what a compile error's positions index into.
Answers for a failed compile too.
- `renderer.compiledShaders()` — every name that call answers for.
- `shaderRef:getProperties()` — the parsed `properties.yaml` schema.
- `shaderRef:listMaterialsUsing()` — materials bound to this shader.
## Common pitfalls
- **A compile error shows up in one of three ways at the draw.** A shader that
never compiled has no pipeline, so the renderer binds the magenta placeholder.
A shader that compiled once and was then edited into brokenness KEEPS the
pipeline that build produced — the surface goes on drawing the last good
program, pixel for pixel, and looks entirely intact while the source is broken.
A geometry-pass-only shader has no magenta tell either, since it is not on a
forward mesh. `shaderRef:compileStatus()` gives the status + error text (as
does `asset.inspect("<name>")`), and `renderer.drawDiagnostics()` names which
renderables are in which of the three states — a row carries `substituted` for
the placeholder, `stale` for a program that no longer compiles, and the cause
either way.
- **A compile error's line numbers are lines of the composed module, not of your
file.** `renderer.compiledSource("<name>")` / `shaderRef:compiledWgsl()` is
that module; resolve the position against it rather than counting lines in
`shader.wgsl`. The `[N]` a message prints in place of a name is a naga handle
index — it moves with the size of the body and is the same value for two
unrelated faults in one file, so it is neither a line number nor a way to tell
two failures apart.
- **Don't declare group(0) or group(1) in a surface shader.** The engine owns
group(0) and generates group(1) from `properties.yaml`. Re-declaring them is the
fastest way to a layout mismatch.
- **`#include` does nothing by itself** — it only exposes functions; you must call
them.
- **Renaming a property** changes the generated uniform field; materials setting the
old name silently fall back to its default.
- **Compute shaders don't render** — verify output via a buffer readback or a
debug pass. Author them as a `.computeShader` (its own assetType), not a
`.shader` — see `man compute`.
## Related types
- `.material` — the required wrapper that applies a shader to entities.
- `.style` — UI cascade, not GPU shaders.
## In the Inspector
Selecting a shader opens its **Shader** section: its domain and shading model (and, for a post-process shader, the space its `fragment()` reads and returns), whether it compiled (and the compiler's error when it did not), a table of its declared properties (type, default, range), its post-process passes when it has any, the bindings it declares, and openers for its source. The **Materials** section (collapsed at first) has a Find materials action that lists, as links, every material drawing with the shader; it scans every material, so it runs only when asked.
# Component (asset type)
A component is a reusable behavior + data unit attached to an entity.
The component file declares public fields, methods, and lifecycle
callbacks; the engine instantiates one per attachment and drives its
hooks every frame. Components are the primary unit of gameplay code —
movement, AI, animations, UI panels, network sync, and per-entity state
all live here.
## When to use one
- You need per-entity state that survives across frames.
- You need per-entity behavior driven by engine lifecycle hooks
(`start`, `update`, `destroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If you need a global service that outlives any entity, use a `.service`
instead. If you need a stateless pure-function library, use a `.module`.
## Where it lives
- Source: `/zero/source/.../<Name>.component/`
- Identity: `<Name>` (the `.component` suffix strips from the
identity, but the folder retains the suffix on disk).
- Folder shape:
- `init.luau` (or `init.lua`) — declares the component. **Required.**
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
The structural contract is enforced by `asset.validate` against this
type's `type.yaml`.
## How to create one
Always start with the scaffold — it guarantees the folder shape
matches `type.yaml` from the moment it's on disk:
```luau
asset.create("component", "<Name>")
-- Creates: /zero/source/<Name>.component/
-- init.luau (canonical declare + public block + hooks stubbed)
-- README.md (instance README template)
```
After scaffolding, edit `init.luau` to fill in the actual fields and
behaviour. The component registers as soon as the file is written —
hot-reload is automatic; no engine restart required.
## How it operates
1. **Registration.** Writing `init.luau` into a `.component/` folder
indexes the asset, mints a guid (in the `.meta` sidecar), and
surfaces the type to the engine's component registry. Same-frame
visible to `entity.component.add`.
2. **Attachment.** `entity(id).component.add(name, data)` (or the
batch form `tools.use("entityOps", "addComponents", targets,
{ [name] = data })`) attaches an instance.
The `data` table's fields override the component's declared
defaults; omitted fields take the declared default. The `data`
values are copied into `public.*` BEFORE `awake()` runs.
3. **Lifecycle.** The hooks run in this order:
- `awake()` — same frame as attach, immediately after the data
copy. Initialise state, set up native bridges, register with
other systems. Other components on the same entity may not have
awoken yet.
- `start()` — the next frame. Every component on the entity has
completed `awake()` by then, so cross-component setup is safe
here.
- `update(dt)` — same frame as `start()`, then every frame after,
for as long as the gameplay clock is running. `fixedUpdate(dt)`
runs beside it on the fixed timestep; `editorUpdate(dt)` runs
while the clock is held. Which of them ticks is decided by
`engine.mode` AND `engine.paused` together — see **Per-frame
hooks and the two axes** below, and `man modes`.
- `onDestroy()` — when the component is removed via
`component.remove` or when the owning entity is despawned.
Release resources, drop native ECS components.
For the full list (`onEnable`, `onDisable`, `fixedUpdate`,
`editorUpdate`, `onPropertyChanged`, `onAssetReload`,
`onModuleReload`,
`onBeforeSave`, …) and the timing details, **read `man components`
— that is the canonical lifecycle reference. Generic component
patterns (declare blocks, public fields, sync, ECS bindings,
typed methods) all live there.**
4. **Public surface.** Fields declared in `public` are inspectable,
editable in the inspector, and persist with the entity. Methods are
declared on that same table with a colon —
`typed function public:method(args)` — and every one of them takes
the component ref as `self`, so a caller invokes it with a colon
too: `entity(id).component.get(name):method(args)`. That is the one
calling convention a component ref answers to: the reflection
methods `ref:fields()` / `ref:getField(name)` /
`ref:setField(name, value)` take the same spelling. A function the
chunk declares at file scope (`function helper()`) is the
component's own, reachable from its hooks under its bare name;
`public` is what the ref carries.
5. **Settings and the Inspector card.** `type.yaml` names the component's
settings schema as `settings: { schema: { instance: "init.luau",
export: "public" } }`: the `public` table IS the schema, and its values
live on each entity the component is on, so `asset.schema(componentRef)`
answers the Field descriptors and no values file exists. On an entity
the Inspector shows the component as a card whose generic `settings`
section edits those fields as typed controls, each edit checked against
the schema and written to the live component as one undoable operation.
`type.yaml` also names `inspector: { instance: "inspector.luau" }`: a
component that ships an `inspector.luau` beside its `init.luau` shapes
its card — the file returns `{ sections, replace, order }` (see
`assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)`
reading `ctx.component` (the live component) and `ctx.selection.id` (the
entity). `SceneModule.component/inspector.luau` replaces `settings` with
the bound module's declared inputs.
6. **Events.** An `events` block declares typed moments the component
fires from inside — `events = { onHit = Event({ dmg =
Field.number(0, NoSync) }) }`. The owner fires with
`events.onHit:fire({ dmg = 10 })`; outside code subscribes through
the proxy's subscribe-only facade,
`entity(id).component.get(name).events.onHit:connect(fn)`
(`:once` / `:wait` too). Pass `Sync` as the event's second argument
to replicate a fire to other peers. Events let one component react
to another's moments without polling. Full reference: **`man
components`**, Events section.
7. **Hot reload.** Editing `init.luau` reloads the component
definition; live instances are reconciled with the new declaration
in-place, and each crosses one lifecycle boundary: `onDestroy()`
ends the running life, then `awake()` and `start()` construct the
one that replaces it, and `update()` resumes on the next frame.
`public` and `private` values carry across; module-level `local`s
belong to the chunk, so the new life starts with them at their
initial values and its `awake`/`start` are what fill them in.
Whatever the old life handed elsewhere — a subscription, a shared
registration, a spawned entity — is released in `onDestroy`, the
call that pairs with the construction about to run. An edit that
leaves the source byte-identical crosses no boundary at all.
A field carries its value across when something stated it: a key of
the `data` table the instance was attached with (a scene record's
data is that table), or a write made since. Every other field takes
the edited source's declared default, so changing a default reaches
every instance that left the field to it. An instance that states
its own value for a field whose default the edit changed keeps that
value, and the reload logs a `[HotReload]` warning naming the field,
the entity, the value kept and both defaults.
## Discovery
- `asset.list("component")` — every registered component (engine +
world + libraries).
- `asset.inspect("<name>")` — identity, scope, public fields,
lifecycle methods, source path, and this type README. `detail`
carries the component's declared `fields`, `methods`, and `events`,
parsed from its source — `tools.use("assets","describe", "<name>")`
renders it as markdown, so a component's events are visible without
opening its source.
- `ls /zero/source/<Name>.component` lists the files the folder holds.
- `entity(id).component.list()` — components attached to an entity.
## Per-frame hooks and the two axes
`engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay
clock) are independent, and the per-frame hooks read them separately:
- `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is
running** — whichever mode the engine is in.
- `editorUpdate(dt)` ticks while **the clock is held** — because the
mode is `edit`, or because play is paused — and also alongside
`update` whenever edit is running.
Which gives four states, and this table is the contract:
| `engine.mode` | `engine.paused` | hooks that tick |
|---|---|---|
| `edit` | `true` | `editorUpdate` |
| `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` |
| `play` | `false` | `update`, `fixedUpdate` |
| `play` | `true` | `editorUpdate` |
Entering edit sets `paused = true` and entering play sets it back to
`false`, so a session that never writes `engine.paused` only ever sees
rows 1 and 3 — which is where the shorthand "`update` is the play tick,
`editorUpdate` is the edit tick" comes from. It is the two default rows
of a four-row table, not the rule.
**Row 2 is the one that surprises.** With `engine.paused = false` in
edit — set by hand, or by a tool that advances the gameplay clock to
sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate`
both fire, once each, every frame. A component that declares both and
routes them to one body therefore runs that body **twice per frame**:
```luau
local function drive(dt) ... end
function update(dt) drive(dt) end
function editorUpdate(dt) drive(dt) end -- twice per frame in row 2
```
Nothing reports the doubling; it reads as an animation running at twice
its intended speed. To get exactly one tick per frame in every row, ask
which axis you meant and answer it in the body:
```luau
function update(dt) drive(dt) end
function editorUpdate(dt) if engine.paused then drive(dt) end end
```
A scene `entrypoint.luau` declaring the same two hook names is dispatched
by the scene loader, not by this table: there `update` needs play AND
running, `editorUpdate` needs edit, and play-paused ticks neither. Read
`man scenes` before carrying a component's rule to an entrypoint.
## Authoring conventions
- Annotate public fields with `--!desc` so the inspector + LSP show
documentation alongside the field name.
- Declare lifecycle hooks (`start`, `update`, `destroy`) explicitly
rather than relying on engine defaults — readers can see at a glance
what runs when.
- Keep `update(dt)` cheap — it runs every frame per instance. Move
heavy work to `start`, to a service, or behind a job (`man jobs`).
- For multi-entity batching, prefer
`tools.use("entityOps", "addComponents", targets, components)` over
a loop of `entity(id).component.add` — it takes many targets and
many components in one call.
## Common pitfalls
- **Naming.** The component identity is the folder stem with
`.component` stripped (e.g. `<Spinner>.component/` → identity
`Spinner`). Don't repeat the suffix in the identity passed to
`component.add`.
- **`init.lua` vs `init.luau`.** Either is accepted (it's a
`one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both
in one folder is invalid.
- **`update` in edit mode.** It runs whenever the gameplay clock is
running, and entering edit stops that clock — so `update` is idle in
a freshly-entered edit session and ticks again the moment anything
sets `engine.paused = false`. Use `tools.use("wld", "play")` to test
update logic under the mode it ships in; `tools.use("wld", "edit")`
to return. See **Per-frame hooks and the two axes** above.
- **Renaming.** Renaming the folder changes the identity. Update
every `component.add(<oldname>, ...)` call and the scene JSON
entries that reference it.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service` — globally-scoped behavior, no per-entity state.
- `.preset` — a captured component configuration, replayable into
`component.add` without re-typing fields.
- `.bundle` — entity hierarchies that may carry component attachments
as part of the bundle.
## In the Inspector
Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
# dynamicAsset (asset type)
A **prompt-driven, self-regenerating 3D asset**. A `<name>.dynamicAsset/`
folder holds a text `prompt.json`; the asset's model is generated from
that prompt by the `@builtin::services.meshy` text-to-3D service. Editing
the prompt regenerates the model and version-controls the old one — no
explicit call needed.
This type is the **reference example** for the asset-type `onChange`
change-callback (the type-level analogue of a component's
`onAssetReload`). Read its `behavior.luau` to see the pattern end to end.
## Folder shape
```
<name>.dynamicAsset/
├── prompt.json { "prompt": "a mossy stone golem" }
├── .metadata generation status + start date + last prompt
├── model/ (after first generation)
│ ├── model.glb the current generated mesh
│ └── model.json manifest (prompt, date, service handle)
└── versions/ (after the prompt changes at least once)
├── v1/
│ ├── model/model.glb
│ ├── prompt.json the prompt that produced this version
│ └── meta.json
└── v2/ …
```
## Lifecycle
1. **Generate** — `ref:generate("a mossy stone golem")` writes the prompt,
sets `.metadata.generationStatus = "inflight"` + `generationStartedAt`,
and launches Meshy. The GLB is written straight into `model/`.
2. **Status** — `ref:status()` reads the state from `.metadata`:
`status` (`empty`/`inflight`/`succeeded`/`failed`), `stage` (live Meshy
stage), `prompt`, `startedAt`, `finishedAt`, `error`, `handle`. Use it
to find finished / failed / in-flight assets at a glance.
3. **Edit the prompt → regenerate** — writing `prompt.json` (by hand,
`vfs.write`, `ref:setPrompt(...)`, or a pull) fires `onChange`. If the
prompt actually changed, the current `model/` is archived into
`versions/v<N>/` (incrementing) and a fresh generation starts.
## Methods (`AssetRef<dynamicAsset>`)
| Method | What it does |
|--------|--------------|
| `:generate(prompt?)` | Generate/regenerate now (async). Returns the status table. |
| `:status()` | Read generation status from `.metadata`. |
| `:getPrompt()` / `:setPrompt(text)` | Read / set `prompt.json` (set triggers regeneration). |
| `:modelPath()` | VFS path of the current GLB, or nil. |
| `:versions()` | Archived version indices (oldest first). |
| `:restoreVersion(n)` | Make version `n` the current model and prompt again, with no generation and no credits. The model it replaces is kept as the next version. |
| `:spawn(name?, x?, y?, z?)` | Spawn the current model into the scene. |
## Setup
The Meshy service reads its key from the `MESHY_API_KEY` environment
variable (set before launching the engine). Without it, generation fails
with a clear message and `:status().status == "failed"`. Get a key at
https://www.meshy.ai/api.
## Usage
```luau
asset.create("dynamicAsset", "Golem")
local golem = asset.resolve("Golem", "dynamicAsset")
golem:generate("a mossy stone golem, low-poly")
-- … wait …
print(golem:status().status) -- "succeeded"
golem:spawn("golem", 0, 0, 0)
-- Change the prompt → archives v1, regenerates:
golem:setPrompt("a bronze golem, ornate")
print(golem:versions()) -- { 1 }
```
## Notes
- Generation is async and can take minutes. `onChange` returns immediately;
the model appears when `:status().status` flips to `"succeeded"`.
- `onChange` is convergent: it only acts when the prompt differs from the
last generated prompt and queues edits made mid-generation
(`pendingPrompt`), so it never loops on its own writes.
## In the Inspector
Selecting a generated asset opens its **Generation** section: the status of its last generation ("not generated" before the first), and, once a generation has filled them, its stage, prompt, start and finish times and error; how many versions exist; the model in use ("none yet" before one exists); and an opener for `prompt.json`. Generating spends credits, so it stays in Operations, where restoring an earlier version (free) is listed too.
# Input macro (asset type)
An input macro is a recorded or hand-authored sequence of input
simulation events — keystrokes, mouse moves, button clicks, scroll
wheel deltas — timestamped and played back via the `inputSim` toolbox
(`tools.use("inputSim", "macro", <name>)` from Luau). Macros are the
canonical generic surface for "make the engine receive these inputs at
these times": testing, demos, automated repro of input sequences.
The engine deliberately does NOT ship per-feature input recipes
(walk, sprint, drive). Authors record or hand-write the macro they
need; the playback primitive is type-agnostic.
## When to use one
- You want to script an input sequence for testing (e.g. "walk
forward 3 seconds, jump, look around").
- You're capturing a demo / repro of a user interaction sequence.
- You want deterministic input playback across runs.
If you need per-frame programmatic input (more than a fixed sequence
allows), drive the `inputSim` toolbox's `key` / `click` tools directly from
a script. If you need real input handling, that's the `input` API
(`man input`).
## Where it lives
- Source: `/zero/source/.../<name>.inputMacro/`
- Identity: `<name>` (the `.inputMacro` suffix strips).
- Folder shape:
- `events.json` — JSON array of `{ t, op, arg }` event tuples.
**Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
Two paths:
```luau
-- Record a live sequence: recordMacro captures real input for
-- `duration` seconds and returns the recorded events; saveMacro
-- persists them as the asset.
local events = tools.use("inputSim", "recordMacro", { duration = 5 })
tools.use("inputSim", "saveMacro", "<name>", events)
-- Hand-author an empty macro scaffold and fill events in:
asset.create("inputMacro", "<name>")
```
The record path is preferred for sequences any human could perform;
hand-authoring is for synthetic or precisely-timed sequences.
## How it operates
1. **Event format.** `events.json` is a JSON array of triples:
```jsonc
{
"t": 0.5,
"op": "keyDown",
"arg": "KeyW"
}
```
- `t`: seconds since macro start.
- `op`: the name of an `inputSim` verb that drives input — the
keyboard and mouse verbs (`keyDown`, `keyUp`, `key`, `mouseDown`,
`mouseUp`, `mouseMove`, `mouseMoveBy`, `click`, `scroll`,
`lockPointer`), the pad verbs (`pad`, `padOff`, `padDown`,
`padUp`, `padPress`, `padStick`, `padTrigger`) and the touch
verbs (`touch`, `touchDown`, `touchMove`, `touchUp`, `stick`,
`tapButton`, `drag`, `pinch`).
- `arg`: that verb's arguments — the value itself when the verb
takes one (a key code such as `"KeyW"`, a mouse button index
where 0 = LMB, 1 = RMB, 2 = MMB, a canonical pad button name such
as `"south"`), or a table keyed by the verb's parameter names
when it takes several (`{ dx = 200, dy = 0 }` for `mouseMove`,
`{ stick = "left", x = 0, y = -1 }` for `padStick`,
`{ x = 714, y = 984, id = 1 }` for `touchDown`).
2. **Playback.** `tools.use("inputSim", "macro", "<name>")` schedules every
event at its `t` offset relative to playback start; events are
played in order of `t`, and events sharing one `t` play in the
order the list writes them. The same tool takes an inline event list or an
`AssetRef<inputMacro>` instead of a name.
3. **Determinism.** Macros are deterministic relative to engine state
at playback start — same start state + same macro = same end
state.
4. **Recording.** `tools.use("inputSim", "recordMacro", { duration = n })`
polls live input state and returns the recorded events;
`tools.use("inputSim", "saveMacro", "<name>", events)` writes them to
`/zero/source/<name>.inputMacro/events.json` and returns the
macro's `AssetRef`.
## Discovery
- `asset.list("inputMacro")` — every registered macro.
- `asset.inspect("<name>")` — event count, duration, source, this
type README.
- `ls /zero/source/<name>.inputMacro` lists the files the folder holds.
- `tools.use("inputSim", "listMacros")` — every registered `.inputMacro`.
## Authoring conventions
- Start macros from a known state (call `layers.load("base")` before
playback) so determinism holds across runs.
- Keep macros focused on one user-facing action sequence. Longer
macros are harder to compose and debug; chain shorter ones via
`tools.use("inputSim", "macro", "a")` then
`tools.use("inputSim", "macro", "b")`.
- Keep the expected start state and end state in mind when you name a
macro: what scene / mode / focus the playback assumes.
## Common pitfalls
- **Non-deterministic start state.** Playing a macro from a different
starting scene produces different outcomes. Always lead with a
scene load.
- **Frame-rate dependence.** Times are in seconds; the dispatcher
schedules events relative to wall time, not frames. Effects that
depend on per-frame logic may diverge across hardware.
- **`mouseMove` argument.** It carries a `{ dx, dy }` delta, the same
shape the recorder emits. Check the recorded values match.
## Related types
- `.tool` — for agent-callable input wrappers that may invoke
macros as part of larger flows.
- `.scene` — macros pair with scenes for deterministic test setups.
## In the Inspector
Events: how many events the macro records, when the last one fires, and the first 50 events in order (time, op, argument). Replaying it stays in Operations.
·voxeltemplate · born here
❒asset # bookshelf
Voxel template `bookshelf` (demo asset). Live instances spawned via `Voxel.fromTemplate("bookshelf")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # bot_seated
Voxel template `bot_seated` (demo asset). Live instances spawned via `Voxel.fromTemplate("bot_seated")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # bot_standing
Voxel template `bot_standing` (demo asset). Live instances spawned via `Voxel.fromTemplate("bot_standing")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # cabinet
Voxel template `cabinet` (demo asset). Live instances spawned via `Voxel.fromTemplate("cabinet")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # chair
Voxel template `chair` (demo asset). Live instances spawned via `Voxel.fromTemplate("chair")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # clock
Voxel template `clock` (demo asset). Live instances spawned via `Voxel.fromTemplate("clock")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # desk
Voxel template `desk` (demo asset). Live instances spawned via `Voxel.fromTemplate("desk")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # keyboard
Voxel template `keyboard` (demo asset). Live instances spawned via `Voxel.fromTemplate("keyboard")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # lamp
Voxel template `lamp` (demo asset). Live instances spawned via `Voxel.fromTemplate("lamp")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # linked_workstation_baked
Voxel template `linked_workstation_baked` (demo asset). Live instances spawned via `Voxel.fromTemplate("linked_workstation_baked")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # monitor
Voxel template `monitor` (demo asset). Live instances spawned via `Voxel.fromTemplate("monitor")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # mug
Voxel template `mug` (demo asset). Live instances spawned via `Voxel.fromTemplate("mug")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # plant
Voxel template `plant` (demo asset). Live instances spawned via `Voxel.fromTemplate("plant")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # printer
Voxel template `printer` (demo asset). Live instances spawned via `Voxel.fromTemplate("printer")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # trash
Voxel template `trash` (demo asset). Live instances spawned via `Voxel.fromTemplate("trash")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # whiteboard
Voxel template `whiteboard` (demo asset). Live instances spawned via `Voxel.fromTemplate("whiteboard")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # blade
Voxel template `blade` (demo asset). Live instances spawned via `Voxel.fromTemplate("blade")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # house
Voxel template `house` (demo asset). Live instances spawned via `Voxel.fromTemplate("house")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # rock
Voxel template `rock` (demo asset). Live instances spawned via `Voxel.fromTemplate("rock")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # tree
Voxel template `tree` (demo asset). Live instances spawned via `Voxel.fromTemplate("tree")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # windmill_base
Voxel template `windmill_base` (demo asset). Live instances spawned via `Voxel.fromTemplate("windmill_base")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # cabin
Voxel template `cabin` (demo asset). Live instances spawned via `Voxel.fromTemplate("cabin")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # chassis
Voxel template `chassis` (demo asset). Live instances spawned via `Voxel.fromTemplate("chassis")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # door
Voxel template `door` (demo asset). Live instances spawned via `Voxel.fromTemplate("door")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # front_bumper
Voxel template `front_bumper` (demo asset). Live instances spawned via `Voxel.fromTemplate("front_bumper")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # headlight
Voxel template `headlight` (demo asset). Live instances spawned via `Voxel.fromTemplate("headlight")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # hood
Voxel template `hood` (demo asset). Live instances spawned via `Voxel.fromTemplate("hood")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # mirror
Voxel template `mirror` (demo asset). Live instances spawned via `Voxel.fromTemplate("mirror")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # rear_bumper
Voxel template `rear_bumper` (demo asset). Live instances spawned via `Voxel.fromTemplate("rear_bumper")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # rear_window
Voxel template `rear_window` (demo asset). Live instances spawned via `Voxel.fromTemplate("rear_window")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # seat
Voxel template `seat` (demo asset). Live instances spawned via `Voxel.fromTemplate("seat")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # spoiler
Voxel template `spoiler` (demo asset). Live instances spawned via `Voxel.fromTemplate("spoiler")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # steering_wheel
Voxel template `steering_wheel` (demo asset). Live instances spawned via `Voxel.fromTemplate("steering_wheel")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # taillight
Voxel template `taillight` (demo asset). Live instances spawned via `Voxel.fromTemplate("taillight")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # trunk
Voxel template `trunk` (demo asset). Live instances spawned via `Voxel.fromTemplate("trunk")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # wheel
Voxel template `wheel` (demo asset). Live instances spawned via `Voxel.fromTemplate("wheel")` reload automatically when this template's `template.voxbin` payload is rewritten.
·voxeltemplate · born here
❒asset # windshield
Voxel template `windshield` (demo asset). Live instances spawned via `Voxel.fromTemplate("windshield")` reload automatically when this template's `template.voxbin` payload is rewritten.
·computeshader · born here
❒asset # greedy_mesh
Turns a voxel chunk into a mesh, merging coplanar faces of one colour into the
largest rectangle that covers them so a solid wall costs two triangles instead
of two per voxel. One invocation per slice; the vertex and index counts are
claimed atomically, so the pass writes both buffers in a single dispatch.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `params` | `buffer` (read, u32) | chunk size, padding and the origin the mesh is built around |
| `solid_padded` | `buffer` (read, u32) | the chunk's occupancy bitmask, one voxel of padding on every side so a face test at the edge reads a real neighbour |
| `colors` | `buffer` (read, u32) | one packed colour per voxel |
| `vertex_buf` | `buffer` (read_write, u32) | the vertices produced, in the engine's vertex layout |
| `index_buf` | `buffer` (read_write, u32) | the indices produced |
| `counters` | `buffer` (read_write, atomic u32) | how many vertices and indices have been claimed |
## Params
| name | type | what it is |
|------|------|------------|
| `vertStride` | `u32` | one vertex in u32 words, so the writes follow the engine's vertex layout |
# voxelConfig
Read and write the voxel engine's configuration — the path defaults and engine knobs the voxel system runs on (chunk size, default block size, default mesher, CPU fallback, play-mode write permission, and the path defaults).
Get a value by key, get the whole merged config, set a runtime override, or reset one or all overrides. Values resolve in order: a runtime override wins, then the world's voxel settings, then the built-in defaults.
# voxelEngine
Build and edit voxel worlds — spawn worlds and shapes, mutate blocks, query them, transform them, manage palettes, persist them, and kitbash composites.
Spawn worlds, shapes, and templates, clone handles, or scatter and stamp templates across regions, and destroy them. Mutate blocks — set, clear, fill boxes, spheres, cylinders, and lines, mirror, translate, and paste regions. Read the world back — a block, its neighbours, a region, counts by name, raycasts, sphere and line queries, region copies, and bounds. Apply entity-level transforms (position, rotation, scale, parent, snap-to-world) and read them. Manage the palette. Persist to voxbin and templates — save, bake, save and copy templates, and capture an area. Kitbash composite props from existing templates — new, add child, save baked or linked, explode, save as a bundle. And read or override the voxel config. A target — a handle, `"world"`, an entity id, or an entity name — is accepted uniformly across the toolbox.
# voxelEngine
Public API for the voxel system. Single entry point for creating and
editing voxel worlds and shapes. Tools and custom code call into here;
nobody touches the `VoxelWorld` / `VoxelShape` components directly.
Two top-level concepts:
- **World** — singleton entity carrying a chunked `VoxelWorld` grid.
Created lazily on the first `createWorld` call, found by name later
via `world()` / `hasWorld()`, destroyed with `destroyWorld()`.
- **Shapes** — per-entity dense or chunked `VoxelShape` grids. Spawned
freely; each carries its own voxbin path on disk under
`Config.get("paths.shapes")/<entityId>.voxbin`.
Templates are stored under `Config.get("paths.templates")/<name>.voxbin`
and instantiated via `fromTemplate`. Captures (snapshots of a world
region) land at `Config.get("paths.captures")/<name>.voxbin`.
## Exports
Module-level:
- `M.world() -> Handle?` — handle to the singleton VoxelWorld, or nil.
- `M.createWorld(opts: CreateWorldOpts?) -> Handle` — create or reuse the singleton.
- `M.destroyWorld()` — despawn the singleton world if it exists.
- `M.hasWorld() -> boolean` — true when the singleton exists.
- `M.shape(name_or_id) -> Handle?` — handle to an existing shape entity.
- `M.createShape(opts: CreateShapeOpts) -> Handle` — spawn a new shape entity.
- `M.destroyShape(name_or_id)` — despawn the shape entity if it exists.
- `M.fromTemplate(name: string, opts: FromTemplateOpts?) -> Handle` — instantiate from `paths.templates/<name>.voxbin`. Supports live-link, detached, and memory-only modes.
- `M.saveAsTemplate(shape: Handle, name: string, opts: SaveAsTemplateOpts?) -> string` — write a shape's grid as a named template.
- `M.listTemplates() -> { string }` — enumerate template names (no extension).
- `M.deleteTemplate(name: string)` — remove a template file.
- `M.copyTemplate(srcName: string, dstName: string) -> string` — duplicate a template file.
- `M.captureArea(opts: CaptureAreaOpts) -> any` — flatten a region of world + shapes into a dense voxbin record (and optionally save it).
- `M.scatter(templateName: string, opts: ScatterOpts) -> { Handle }` — bulk-spawn instances across a region.
- `M.stamp(templateName: string, opts: StampOpts) -> Handle` — single placement, either as a new entity (`mode = "instance"`, default) or rasterised into the world grid (`mode = "merge"`).
- `M.composite` — re-export of the composite-prop module.
- `M._resolvePivot(value) -> { number, number, number }?` — internal pivot helper, exposed for composite reuse.
Handle methods (returned by `createWorld` / `createShape` / `fromTemplate` / `world` / `shape` / `scatter` / `stamp`):
- `h:setBlock(x, y, z, name)` / `h:getBlock(x, y, z)`
- `h:fillBox(min, max, name)` / `h:fillSphere(center, radius, name)`
- `h:fillCylinder(p1, p2, radius, name)` / `h:fillLine(p1, p2, name)`
- `h:clear()` — clear every cell.
- `h:setPalette(palette)` / `h:addPaletteEntry(name, color)`
- `h:bounds() -> Bounds?` — inclusive bounds of every filled cell.
- `h:flush()` — flush pending dirty-chunk remeshes.
- `h:save()` — write the grid to the component's dataPath.
- `h:dirtyChunks() -> { any }`
- `h:isLive() -> boolean` / `h:templatePath() -> string?`
- `h:bake() -> Handle` — break the live-link, copy into a private dataPath. Shape-only.
- `h:saveAsTemplate(name, opts) -> string`
- `h:exists() -> boolean` / `h:destroy()`
- `h:setPosition(x, y, z) -> Handle` / `h:getPosition() -> Vec3Map?`
- `h:setRotation(r) -> Handle` / `h:getRotation() -> Vec3Map?` (Euler radians, ZYX)
- `h:setParent(parentEntityId) -> Handle`
- `h:copyRegion(min, max) -> any` / `h:pasteRegion(offset, regionData, opts)`
- `h:mirror(axis)` / `h:translate(dx, dy, dz)`
- `h:getNeighbors(x, y, z) -> any`
- `h:queryRegion(min, max, opts) -> { any }` / `h:countByName(min, max) -> { [string]: number }`
- `h:raycast(origin, dir, maxDist) -> any` / `h:sphereQuery(center, radius) -> { any }` / `h:lineQuery(p1, p2) -> { any }`
- `h:clone(opts) -> Handle` — shape-only. Detached duplicate.
- `h:snapToWorld(opts) -> Handle` — quantise transform or shift voxel data to the world grid.
Types:
- `Vec3Map = { x: number?, y: number?, z: number? }`
- `Vec3Array = { number }`
- `Vec3Like = Vec3Map | Vec3Array`
- `ColorMap = { r: number?, g: number?, b: number? }`
- `ColorArray = { number }`
- `ColorLike = ColorMap | ColorArray`
- `PaletteEntry = { name: string, color: ColorLike, material: any?, atlas: any?, faces: any? }`
- `Palette = { PaletteEntry } | { [string]: ColorLike }`
- `Bounds = { min: Vec3Map, max: Vec3Map }`
- `Handle = { entityId: any, componentName: string, [string]: any }`
- `CreateWorldOpts` / `CreateShapeOpts` / `FromTemplateOpts` / `SaveAsTemplateOpts`
- `CaptureAreaOpts` / `CaptureAreaBoxSelector` / `CaptureAreaSphereSelector`
- `CloneOpts` / `SnapToWorldOpts`
- `RegionSpec` / `ScatterOpts` / `StampOpts`
- `QueryRegionOpts` / `PasteRegionOpts`
## Usage
```luau
local Voxel = require("@builtin::systems.voxelEngine")
-- Create the singleton world, write a couple of cells.
local world = Voxel.createWorld({
size = { x = 64, y = 32, z = 64 },
palette = { stone = { r = 0.5, g = 0.5, b = 0.5 } },
})
world:setBlock(0, 0, 0, "stone")
world:fillBox({ 1, 0, 0 }, { 3, 0, 3 }, "stone")
-- Spawn a shape from a template, live-linked to the template file.
local tree = Voxel.fromTemplate("tree", {
position = { x = 10, y = 0, z = 5 },
})
-- Scatter 20 copies inside a region.
local hs = Voxel.scatter("tree", {
region = { box = { min = { 0, 0, 0 }, max = { 50, 0, 50 } } },
count = 20,
snap = true,
})
-- Capture a region of world + shapes into a dense voxbin record.
local rec = Voxel.captureArea({
box = { min = { 0, 0, 0 }, max = { 15, 15, 15 } },
})
```
## Notes
- Handles are thin wrappers over an `entityId` + a component name. Each
method re-resolves the underlying component on every call, so the
handle stays usable across hot-reload cycles.
- All `h:setBlock` / `h:fillBox` / … calls forward to the component via
colon-call (`c:method(...)`) — dot-call would drop `self` and the
strict typed-function checker would read args from the wrong slots.
- `fromTemplate` defaults to `live = true` + `persist = true` —
live-linked instance that auto-bakes private edits to disk. Pass
`live = false` for a detached copy with its own dataPath, or
`persist = false` for a memory-only instance.
- `Voxel.scatter` / `Voxel.stamp` (mode = "merge") obey the play-mode
write gate enforced by `assertModeAllowsWrite`. In play mode, callers
must toggle `Config.set("allowPlayWrites", true)` (or set the
`[voxel].allowPlayWrites` WORLD_SETTINGS override) to unlock voxbin
writes.
- `Voxel.stamp(mode = "merge")` only supports yaw rotations of
0 / 90 / 180 / 270 degrees — voxel grids require axis-aligned stamps.
Non-axis-aligned yaws raise.
- The `composite` sub-module is reachable as `Voxel.composite`. It
builds kitbashed `.voxcomp` props that re-resolve their children at
instantiation time; `fromTemplate` transparently dispatches to it
when the named template resolves to a `.voxcomp` manifest.
# Voxel Template (asset type)
A voxel template is a reusable, named voxel grid that live instances
link to. It is the source of truth for a family of `VoxelShape`
instances spawned via `Voxel.fromTemplate(<name>)` — every live
instance reloads its grid + rebuilds its mesh automatically when the
template's payload is rewritten, and a `Voxel.deleteTemplate(<name>)`
flips every live instance's `staleTemplate` flag.
## When to use one
- You want a reusable voxel prop (`tree`, `rock`, `barrel`) that many
entities share, with edits to the template propagating to every
live instance.
- You want a stable identity (a guid) for a voxel grid so the engine's
asset-reload machinery can drive the live-link instead of a
poll loop.
If you just need a one-off shape on a single entity, use
`Voxel.createShape` — that writes a private `dataPath` voxbin and never
becomes a template.
## Where it lives
- Source: `Config.get("paths.templates")/<Name>.voxelTemplate/`
- Identity: `<Name>` (the `.voxelTemplate` suffix strips).
- Folder shape:
- `template.voxbin` — the binary grid payload (size, blockSize,
palette, flat grid array). Written by `saveAsTemplate` /
`copyTemplate`. **Optional** in the structural spec only so the
freshly-scaffolded (empty) folder validates; every real template
carries it.
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
From a live shape you authored:
```luau
local Voxel = require("@builtin::systems.voxelEngine.voxelEngine")
local shape = Voxel.createShape({ size = { 8, 8, 8 } })
shape:fillBox({0,0,0}, {7,7,7}, "stone")
shape:saveAsTemplate("my_prop")
-- Writes: <paths.templates>/my_prop.voxelTemplate/
-- template.voxbin (the grid payload)
-- .metadata
```
Or scaffold an empty one to fill in later:
```luau
asset.create("voxelTemplate", "MyProp")
-- Creates: /zero/source/MyProp.voxelTemplate/
-- .metadata
```
## How it operates
1. **Live-link.** `Voxel.fromTemplate(<name>)` resolves the template to
an `AssetRef<voxelTemplate>` and stores it in
`VoxelShape.templateRef`. The engine indexes that subscription by
guid, so a write to the template's `template.voxbin` fires
`onAssetReload("templateRef")` on every live instance, which
re-reads the payload and rebuilds the mesh.
2. **Delete.** `Voxel.deleteTemplate(<name>)` removes the folder and
directly flips `staleTemplate = true` on every live instance —
deletes do not emit a content-change event, so the engine notifies
instances synchronously rather than waiting on a reload hook.
3. **Copy-on-write.** Editing a live instance (`setBlock`, `fillBox`,
…) auto-bakes a private `dataPath` copy and clears `templateRef`,
detaching the instance from the template. The original template is
untouched.
## In the Inspector
Selecting a voxel template opens its **Grid** section, decoded from `template.voxbin` once per version of the file: the template's size in voxels, its block size, whether it is chunked (and, when it is, its chunk size and chunk count), how many palette entries it holds, and whether it carries custom data.