# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# proc.types
The procgen type system: core type tags + socket assignability for graph validation.
Part of `@builtin::systems.procgen.proc`.
# proc
Code-authored, graph-backed procedural generation for the Zero engine.
A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by
family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`,
the returned table is the graph's outputs, and `io.output` is how the graph stands in the world.
`builder.module/README.md` holds every rule of that form.
This module owns the whole procedural model: the graph builder + data model,
the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op
implementations. Authored `.procGraph` graphs are persisted via
`procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in
`procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)`
from a script or an agent's `tool_exec` script, or `zero procgen preview` in the
shell. Generated
meshes/materials/textures/bundles are persisted through their own `.assetType`.
An op family can also come from outside this package: a `.procPack` asset
registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones
shipped here (`proc.registerPack(name, ops)` is what it registers through, and
what a test or a tool calls to hold a family for the life of one VM).
`terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/`
and covering a whole landscape; `guides { path =
"systems/terrainSystem/documentation/terrain" }` is its guide.
To find out what the registry holds, use the `procgen` toolbox: `searchNodes`
searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and
`proc.schema(id)` are the same answers in-process, for a graph builder looking
something up while it runs.
# compute_abi Module
The kernel ABI of a `.computeShader`. A `bindings.yaml` that uses the ABI
extensions is lowered to the plain bindings and WGSL the engine compiles; this
module parses, lowers, compiles variants, allocates outputs, packs column tables
and dispatches.
## Purpose
A kernel is one asset that serves many shapes of data. `bindings.yaml` states:
```yaml
bindings:
- { name: cols, kind: columns, access: read }
- { 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, mean, set] }
- { name: BODY, kind: source }
determinism: exact
```
- `columns`: a table of columns in one storage binding (header: the column count, then four words a column: first word, lanes, count, kind). WGSL reads it through `NAME_count(c)`, `NAME_lanes(c)`, `NAME_f32/i32/u32(c, i, lane)`, `NAME_vec2/3/4(c, i)`; `access: read_write` adds `NAME_set_*`. Columns named at specialization are constants `NAME_col_<column>`.
- `count` / `capacity`: the size, in elements, of an output the host allocates. The expression uses `n` (the dispatch size), the shader's params, `len(binding)`, `max`, `min`, `ceil`, `floor` and `+ - * / ( )`.
- `live: true`: on an output of `count: "n"`, the output carries the live count its dispatch ran over (the count the `domain_count` binding was handed), so a reader of it takes the live elements only.
- `append: true`: the output carries a live counter, `NAME_count`, bound right after it. `NAME_store(slot, v)`, `NAME_set_count(n)`, `NAME_count_value()`, `NAME_capacity()` are generated. `NAME_append(v)` (unordered, atomic) is generated for `determinism: float_order` only.
- `specialize`: compile-time parameters. Type options become `alias NAME = type;`, named options become `const NAME: u32` plus `NAME_<option>`, and `kind: source` parameters replace the identifier with text.
- `when` on a binding: a condition over the specialization options, `NAME=option` or `NAME=option|option`. The binding exists in the variants whose option holds and is left out of the others. Terms separated by spaces all hold (`COUNT=device STAGE=table`); alternatives separated by `;` hold when any one does (`COUNT=plain; COUNT=device STAGE=table`). Two bindings may share a name when their conditions never hold together.
- `// @when NAME option option` ... `// @end` in the WGSL: the lines between them stay in the variants where the specialization `NAME` takes one of the options and are blanked in the others (the lines keep their numbers). Blocks may nest. Code that reads a binding a variant leaves out sits in such a block.
- `bits: true` on a binding states that its words are raw bits (an f32 held in a u32 word, an atomic word): a column of another element type bound to a read binding that states it is bound as it is, where an i32, u32 or f32 read binding takes a column of another element type cast by value.
- `determinism`: `exact` or `float_order`. An `exact` shader that calls `NAME_append` is refused.
- `workgroup`: the workgroup size the body declares (default 64).
- `page` / `column`: a kernel binds each arena page once and reaches the runs standing in it by offset. `- { name: PA, kind: page, access: read_write, atomic: false }` is one storage binding of u32 words (`atomic: true`: `atomic<u32>` words); `- { name: pos, kind: column, page: PA, element: vec3<f32>, access: read }` is a run of the page, with no binding of its own. A kernel of thirty columns over three pages has three bindings, whatever the runs' offsets are. A column gets `NAME_len()`, `NAME_get(i)`, `NAME_word(w)` and, unless `access: read`, `NAME_set(i, v)` and `NAME_set_word(w, v)`; an index past `NAME_len()` reaches the last element. On an `atomic: true` page a one-lane column also gets `NAME_atomic_exchange`, `NAME_atomic_min` and `NAME_atomic_max`, the integer ones `NAME_atomic_add`, `_and`, `_or`, `_xor`, and an f32 column `NAME_atomic_add` (compare-and-swap loops where the hardware has no atomic). Each column adds the params `col_base_NAME` (the word its run starts at in the page) and `col_len_NAME` (its elements). `abi.pageBinding(lowered, { [column] = handle | name })` answers the page each page binding takes and those params, from `substrate.placement`, and raises when the columns of one page binding stand in different pages. Runs made inside `proc.substrate.withPageGroup(key, fn)` stand in pages the group owns, in the order they were made, so work that asks for the same shapes in the same order binds the same pages every play. A buffer of its own (not an arena run) is a page of one column. At most eight pages bind in one kernel (the storage-buffer cap).
Every scalar or vector `buffer` binding gets `NAME_get(i)`, `NAME_len()` and, unless `access: read`, `NAME_set(i, v)`. A `vec3` element is stored as a flat scalar array, matching a column of vec3 that is 12 bytes an element. `zero_n()` is the dispatch size.
## Usage
```luau
local abi = require("@builtin::modules.compute_abi")
local schema = abi.parse(bindingsYaml)
local program = abi.program({ key = "my_kernel", schema = schema, wgsl = body })
local variant = program:variant({ specialize = { T = "vec3<f32>" } })
local run = variant:run({ n = 4, inputs = { src = srcBuffer } })
local values = abi.read(run.outputs.dst.buffer)
```
A computeShader asset reference exposes the same through `ref:program()`.
## API
| Function | Does |
|---|---|
| `abi.parse(text)` | `bindings.yaml` to `{ bindings, params, specialize, determinism, workgroup }`; a text parses to one schema, the same table each time it is read |
| `abi.isExtended(schema)` | whether the schema uses an extension |
| `abi.lower(schema, wgsl, spec)` | the lowered source, bindings, params and host slots |
| `abi.compile(key, lowered, label)` | compile a lowered variant once, answering its dispatch key |
| `abi.program(def)` | a program; `program:variant(spec)` lowers and compiles a variant. A program over the schema and source of the one standing under its key is that program, with the variants it has lowered |
| `variant:run(env)` | allocate outputs, bind, dispatch; answers the outputs and live counters. `env.outputs[binding]` is a buffer (or `{ buffer, count?, capacity?, counter? }`) the dispatch writes in place of an allocation; an appended output given one keeps the count its `counter` holds. The first run of a variant waits for its program to be built, so a read of an output asked for after the run sees what the dispatch wrote |
| `abi.table(columns, opts)` | pack columns into one buffer for a `columns` binding |
| `abi.evaluate(text, vars, lengths)` | evaluate a count expression |
| `abi.read(buffer, asU32?)` | read a buffer back, waiting for the frames it takes |
# prefab (nodebox)
Prefabs: the entity records a spawned hierarchy is made of, as record and list values. prefab.empty makes a root, prefab.entity, prefab.parent, prefab.add_component and prefab.link shape the hierarchy (each calls prefab.edit, which holds the record-list edits and the name lookup that prefab.find answers), and prefab.from_geometry, prefab.from_geometries, prefab.from_instances, prefab.from_population and prefab.from_asset make prefabs from what a graph built. The output node shows a prefab and the export node saves it as a bundle.
prefab.record and prefab.find are the parts the others are built from: one entity record, and a lookup of an entity by name.
# field.distance (procNode)
How far each element's position is from a target, as a Float field. It makes the target the wired `b` field or,
when `b` is left unwired, the fixed `point` as a constant field (`value.fallback`, `field.constant`), then
measures with `field.vector_math` in `distance` mode from `a` to that target. The result compiles to the device with
the rest of the field chain.
## Inputs
- `a` (`Field<Vec3> | Vec3`): the positions being measured, one per element.
- `b` (`Field<Vec3> | Vec3`): what each element is measured to, per element, so the target can move with the
element. Wired, it stands in for `point`.
- `point` (`Vec3`, default `{ 0, 0, 0 }`): one fixed position every element is measured to when `b` is unwired. It is
how a radial falloff around a place is built.
## Outputs
- `field`: the distance, a Float field.
# instances (nodebox)
Instances: pack a geometry into a piece (instances.pack), place a piece set on target points (instances.to_points) and take a population or piece set apart (instances.unpack). A piece is one point whose `Mesh` holds a geometry whole, as the node that made it left it: a geometry whose elements are counted on the device (what `geometry.triangulate` makes) keeps its counts there, and draining the piece set (`Geometry.drain`) drains the geometries its records hold with it, so a CPU reader reads each piece's elements; `geometry.merge` with `pack` puts several together into a piece set. The copies `instances.to_points` makes are a population, which the output node draws as instanced draws, one per piece and material, and export saves as a population asset; any other points stand as one entity each.
instances.pack, instances.to_points and instances.unpack are the nodes of that chain, with `points.pose` composing the instance attributes (`P`, `orient`, `scale`, `N`, `v`, `up`, `pscale`, `rot`, `trans`, `pivot`) the copies stand at.
Earlier nodes of the nodebox stand a source on points (instances.on_points), deal one of several sources to each point (instances.pick_random, instances.pick_by_attribute), vary and move the copies (instances.randomize_transform, instances.transform, instances.set_material) and merge them into one geometry (instances.realize). The points they make carry a `Mesh` and stand as entities through the output node.
instances.place, instances.variants, instances.turn and instances.sources are the parts the others are built from: a transform written onto points, a variant index written onto points, the product of two rotations, and the geometries a population stands (the ones given, else the ones its points carry).
# value (nodebox)
Single values in a graph: value.math and value.compare do arithmetic and comparison with the operation picked by a parameter, value.expr follows a Luau expression over the graph's clock, value.get reads one field of a record by a dotted path, and value.switch picks one of two values by a Bool. value.present and value.fallback are how a graph used as a node handles an input its caller may leave unwired: present answers whether anything is wired, fallback takes the wired value or a fallback.
# part (nodebox)
part.merge packs several values into one part, each piece keeping what it is; part.unpack gives one piece back by its name.
# math
One node per operator and per function of Luau's `math` table that is a function of its numbers alone: add, sub, mul, div, mod, pow, neg, abs, min, max, floor, ceil, round, sqrt, sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, exp, log, log10, fmod, ldexp, frexp, modf, noise, map, sign, deg, rad, clamp, lerp, smoothstep, isnan, isinf, isfinite, length, normalize, dot, cross, vec2, vec3, vec4, the comparisons (lt, le, gt, ge, eq, ne, and `compare` over them), `where`, the integer functions (to_int, to_float, bor, bxor, shl, floordiv), and `concat` for text. `math.random` and `math.randomseed` have no node: they draw from state outside the graph, a graph that called one would cook differently each time, and a call of either in a graph is refused, naming `field.rand`, `field.random` and `rand.unit`, which draw from a seed.
Operators and `math.*` over sockets resolve to these nodes, and `vector.create` over sockets resolves to `math.vec2`, `math.vec3` or `math.vec4` by its component count; with plain numbers only, `math.*` and `vector.create` are Luau's own, and `vector.create` holds three components. Each node but `compare` (built from the comparisons) and `concat` (text) calls an operation of `proc.fieldc.operators`: over plain numbers and vectors it answers the plain result, over a Column or a Field it answers a Field (a fieldc template), so a chain of math nodes is one expression that the node consuming it evaluates in a single dispatch (`fieldc.evaluate`).
`math.min` and `math.max` over sockets take any number of operands, folded two at a time; `math.log(x, base)` is the `log` node with its `base`. Operands of different widths widen to the widest: a number applies to every component, and a shorter vector reads 0 for the components it lacks. Division, `floordiv`, `mod` and `fmod` by 0 answer 0, `sqrt`, `log` and `log10` of a value at or below 0 answer 0, `asin` and `acos` of a value past -1 or 1 read the nearest of the two, and `map` over an input range of no width answers its output minimum, so a chain keeps producing numbers. The orderings (`lt`, `le`, `gt`, `ge`) compare first components; `eq` and `ne` compare every component.
# core
The parts the other procgen nodes are built from: connectivity (edges, boundary, adjacency, islands, owner, corners), normals, weld, select, stitch, curve measure and resample, sampling, neighbours, realize, the raster set (`raster.new`, `raster.read`, `raster.stencil`, `raster.sample`, `raster.add_layer`, `raster.remove_layer`, `raster.reduce`, `raster.column`, `raster.resolve`, `raster.blend`, and `raster.cells` under them), `column`, and `entity.read`, which brings scene entities in (assets come in through `io.import`).
Each is a graph of the four ops, the kernels of `kernels/` and other core nodes. `join` holds the module that places the parts of a join, called by `concat` and `realize`.
A graph calls them as `g.core.<name>`, for instance `g.core.edges`. A node with several outputs answers a record: `local faces = g.core.normals.face(...)` then `faces.geometry`, `faces.scaled`. Every node's README states its inputs and outputs.
# Scatter (node)
A scattering node: its `init.luau` holds the graph that does the work, so the declared inputs are this node's inputs
and the declared output is this node's output. The node is its pipeline, in one self-contained asset.
It makes points on the surface (`points.on_surface`, area-weighted), gives every point its own random yaw, lean and
scale (`instances.randomize_transform`), and places the source on those points (`instances.on_points`). The
transform is read from the same point cloud the instances sit on, so each copy takes the pose of its own point.
A node is findable by what it does: the `procgen` toolbox's `ops` with the query `scatter` lists it beside
`points.on_surface` and `instances.on_points`. Editing this node's `init.luau` cooks again every graph that calls it.
## Inputs
- `surface` (Geometry): what the copies land on.
- `source` (Geometry): the shape being copied.
- `count` (Int, default 200): how many.
- `seed` (Int, default 1): changes the arrangement.
- `scaleMin` / `scaleMax` (Float, defaults 0.8 and 1.4): per-copy size range.
- `tilt` (Float, default 0.15): radians of random lean.
## Output
- `instances`: a population, the points each carrying the source as its `Mesh`.
## Authoring a node
A node is a graph returned from a `.procNode`'s `init.luau` (`proc.define`). `asset.create("procNode", name)`
scaffolds that shape, and `procNode.assetType/README.md` describes what a node states and how graphs call it.
# field.ramp (procNode)
A ramp read at every element by a value it carries: a particle's colour, size or opacity following its age. It takes
the value each element reads by (the wired `t`, else the element's own `by` attribute, through `value.fallback` and
`field.attribute`), maps it from `range` onto 0..1 (`field.map_range`, the ends read off `range` by `value.get`), and
reads the ramp there with `ramp.sample`, compiled into the element's dispatch. A value past either end of `range` reads
that end of the ramp.
## Inputs
- `ramp` (`Ramp`): the ramp to read.
- `t` (`Field<Float> | Float`): where along the ramp each element reads. Unwired, it is the element's own `by`
attribute.
- `by` (`String`, default `"life"`): the Float attribute each element reads the ramp by when `t` is unwired. A particle
solver's particles carry `life`, 0 at birth to 1 at death.
- `range` (`Vec2`, default `{ 0, 1 }`): the values of `t` that land at 0 and at 1 on the ramp, so a speed from 0 to 20
or a temperature from 300 to 3000 reads the whole ramp.
## Outputs
- `field`: the ramp's value at each element.
# quickGeometry
Model a scene in Luau with three.js-shaped code. A `build.luau` or a `.sceneModule` builds `Group`s and `Mesh`es from geometry constructors and materials; at the end of the build the tree is stored in the scene as data, drawn by one `Generator`, and nothing runs per frame.
A bare box reads as a placeholder. Every geometry takes **modifiers** that turn it into a modelled shape: round its edges, taper it, bend it, drill it, smooth it, or build it from a profile or cross-sections. A build whose parts are mostly bare boxes and planes logs a warning that names them.
## Using it
The nouns are globals in a scene's `build.luau` and a `.sceneModule`'s entry script: `sceneNouns` and `quickLighting` join both scripts' contexts, so the engine binds their exports when it loads the script, and the language server knows the same names.
```luau
function content()
local paint = MeshStandardMaterial({ color = "#b0332f", metalness = 0.45, roughness = 0.28 })
local steel = MeshStandardMaterial({ color = "#aab2ba", metalness = 1, roughness = 0.25 })
local body = Mesh(BoxGeometry(1, 1, 1):round(0.14), paint, "rounded_box")
body.position:set(0, 0.8, 0)
local block = Mesh(BoxGeometry(1.1, 1.1, 1.1):subtract(CylinderGeometry(0.3, 0.3, 2, 24)), steel, "drilled_block")
block.position:set(1.5, 0.8, 0)
local hull = Mesh(LoftGeometry({
{ shape = EllipseShape(0.45, 0.28), z = -1.2, scale = 0.25 },
{ shape = EllipseShape(0.45, 0.28), z = -0.55, scale = 0.95 },
{ shape = EllipseShape(0.45, 0.28), z = 0.4, scale = 1.0 },
{ shape = EllipseShape(0.45, 0.28), z = 1.2, scale = 0.3, offset = { y = -0.06 } },
}), paint, "hull")
hull.position:set(3.2, 0.8, 0)
end
```
The same code works in a `.sceneModule`'s builder, where `inputs` declare what a placement may set.
A module joins those contexts with `--!context sceneBuild sceneModule` in its leading comment block, the way these two do. A world's own module joins the same way, and its exports become globals in every build script beside the nouns. A name that starts with `_` stays inside its module. A module that exports `_beginRun` and `_finish` has them called around every run of a build. The `script_context` module's README covers contexts in full.
## Parts
- `Group(name)` holds other objects. `Mesh(geometry, material, name)` draws a geometry.
- `object.position`, `object.rotation` (Euler angles in radians, XYZ) and `object.scale` take `.x`, `.y`, `.z` and the vector methods `set`, `setScalar`, `copy`, `add`, `sub`, `multiplyScalar`, `clone` and `toArray`; calls chain.
- `parent:add(a, b, ...)` nests objects under another, and their poses are then in the parent's frame; an object added elsewhere moves. `parent:remove(a, ...)` takes them out, and a removed object is not drawn until it is added again. `object.parent` and `object.children` hold the tree.
- `object.visible = false` leaves the object and everything under it out of the scene. `object.userData` is a table for your own values.
- `object:lookAt(x, y, z)` or `object:lookAt(Vector3)` turns the object so its +Z axis points at a point in its parent's frame; the object's position and the point are numbers.
- `object:clone(recursive)` copies the object, its pose, components and (unless `recursive` is false) what is under it; the copy shares the geometry and material and is placed like a new `Mesh`. `object:traverse(fn)` calls `fn` on the object and everything under it, and `object:getObjectByName(name)` finds one.
- `object:addComponent(type, data)` puts an engine component on the entity a part becomes (`Physics`, a collider, a `Joint`). A part whose pose follows a formula is drawn as an instance and takes none.
- An object that never moves and carries a component becomes an entity named for it, with its parent and local pose; one that never moves and carries none is folded into the object above it. A moving object's leaves are drawn as instances.
## Geometry
| Constructor | Shape |
|-------------|-------|
| `BoxGeometry(width, height, depth)` | box |
| `CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded)` | cylinder; a cone when one radius is 0 |
| `ConeGeometry(radius, height, radialSegments, heightSegments, openEnded)` | cone with its apex up |
| `SphereGeometry(radius, widthSegments, heightSegments)` | UV sphere |
| `TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)` | torus |
| `TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q)` | torus knot |
| `CapsuleGeometry(radius, length, capSegments, radialSegments)` | capsule |
| `PlaneGeometry(width, height, widthSegments, heightSegments)` | flat rectangle |
| `CircleGeometry(radius, segments)` | flat disc |
| `RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength)` | flat annulus |
| `TetrahedronGeometry`, `OctahedronGeometry`, `IcosahedronGeometry`, `DodecahedronGeometry` `(radius, detail)` | regular polyhedra; `detail` above 0 rounds them toward a sphere |
| `LatheGeometry(points, segments)` | a profile of `{ x = radius, y }` points revolved around Y |
| `ExtrudeGeometry(shape, { depth, curveSegments })` | an outline extruded along +Z |
| `ShapeGeometry(shape, curveSegments)` | a flat, filled outline |
| `TubeGeometry(path, tubularSegments, radius, radialSegments, closed)` | a circle swept along a curve |
| `LoftGeometry(sections, { caps })` | a surface through cross-sections along Z |
| `BufferGeometry()` | a mesh from your own arrays |
| `mergeGeometries(list)` | several geometries as one |
Every geometry also takes `translate(x, y, z)`, `rotateX/Y/Z(angle)` and `scale(x, y, z)`, which move it.
### Outlines and curves
`Shape()` records an outline with `moveTo`, `lineTo`, `quadraticCurveTo`, `bezierCurveTo` and `absarc`. `EllipseShape(rx, ry, segments)` and `RoundedRectShape(width, height, radius, segments)` return ready outlines. `CatmullRomCurve3(points, closed)` and `HelixCurve(radius, turns, height)` return curves for `TubeGeometry`.
### Loft
`LoftGeometry` takes sections in order, each `{ shape, z, scale?, offset? }`: an outline, where along Z it stands, a scale (a number or `{ x, y }`) and a move (`{ x, y }`). `caps = false` leaves the ends open. A body, a hull, a fuselage or a bottle is a loft.
### Custom arrays
```luau
local triangle = BufferGeometry()
triangle:setAttribute("position", Float32BufferAttribute({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3))
```
`setAttribute` takes `position`, `normal` and `uv`; `setIndex(list)` gives triangle indices; without normals they are computed and shared across triangles (`computeVertexNormals()`).
## Modifiers
A modifier changes the shape in its own frame, before `translate`/`rotate`/`scale` move it, and modifiers stack in the order called.
| Modifier | Effect |
|----------|--------|
| `:round(radius, segments)` | round every edge with that radius |
| `:bevel(width, segments, angle)` | round only edges sharper than `angle` degrees; `width` is how far it reaches onto each face |
| `:subdivide(levels, mode)` | split every triangle into four, `levels` 1 to 3 times; `"loop"` (default) also smooths, `"linear"` only adds points |
| `:smooth()` | one round of Loop smoothing |
| `:taper(amount, axis)` | scale the cross-section by `1 - amount * d` at distance `d` along `axis` (`"y"` by default) |
| `:twist(angle, axis)` | turn the shape about `axis` by `angle` radians per metre along it |
| `:bend(curvature, axis)` | curve it along `axis`; `curvature` is 1 over the bend's radius in metres |
| `:subtract(other)`, `:union(other)`, `:intersect(other)` | combine with another closed solid, which stands where it was moved to |
`subtract`, `union` and `intersect` take one shape and one shape; merge parts after combining. Both must be closed solids (a box, cylinder, sphere, torus, capsule or polyhedron, or a bevelled or smoothed one).
## Materials
`MeshStandardMaterial({ color, roughness, metalness, emissive, emissiveIntensity, opacity, side })` and `MeshBasicMaterial({ color, opacity, side })`. A colour is a `Color`, a hex string (`"#a3141b"`), a number (`0xa3141b`), a name (`"red"`) or `{ r, g, b }`; hex colours are sRGB. `side = "double"` draws both faces; an `opacity` below 1 blends.
## Math
`Vector3`, `Color` and `MathUtils` come from the same module as the other nouns and are described in the [math](math.module/README.md) module's README: vector methods and operators, colours from hex, names and HSL, and clamp, lerp, smoothstep and a seeded random.
```luau
MathUtils.setSeed(3)
for i = 1, 12 do
local post = Mesh(CylinderGeometry(0.05, 0.05, 1):round(0.01),
MeshStandardMaterial({ color = Color():setHSL(i / 12, 0.5, 0.5) }), "post" .. i)
post.position:set(i * 0.5, 0.5, MathUtils.randFloatSpread(0.2))
end
```
## Motion
Write a pose as a formula of `Time` (seconds) and the `Expr` functions `sin`, `cos`, `sqrt`, `atan2`, `abs`, `min`, `max`, `mod` and `floor`, with `+ - * / ^`:
```luau
local angle = Time * 6.28
piston.position.y = 1.74 * Expr.cos(angle) + Expr.sqrt(32 - 3 * Expr.sin(angle) ^ 2)
crank.rotation.z = -angle
```
The formula is stored with the scene and runs on the device each frame; children follow their parent's motion.
## Lighting
```luau
Lighting({ background = "#0c0f12", environment = 1, sun = { color = "#fff1dc", intensity = 1.6, position = { 18, 30, 22 } } })
PostProcessing({ exposure = 0.9, toneMapping = "aces", bloom = { threshold = 1.05, intensity = 0.55 } })
```
A scene setup places a whole lighting composition as one asset. The V8Dyno scene places `studioLighting`, a studio backdrop, a warm key light and a sky light that lights the model from the backdrop:
```luau
asset.resolve("@builtin::systems.quickGeometry.studioLighting", "sceneSetup"):instantiate(nil, { name = "lighting" })
```
## Where it lives
Each build ends by spawning one entity named `model` with a `Generator` on the `ModelGraph` graph in this package. The tree is the Generator's `objects` and `channels` inputs, stored in `scene.json`; the shapes are made by the nodes of the `shape` nodebox and the modifiers by procgen's `geometry.*` nodes. Names that two parts share get a numeric suffix.
# debug (nodebox)
debug.dump summarizes any graph value into a record; debug.validate checks a Geometry's structure and reports every issue it finds.
# geometry.recalculate_normals (procNode)
Every vertex's normal averaged, by area, over the faces meeting it. The node is `geometry.smooth_normals` with a
crease angle of 180 degrees and area weighting, so no vertex splits: a vertex shared by two faces is smooth across
them, and one already split between two copies stays a hard edge.
## Inputs
- `geometry` (`Geometry`): whose surface the normals are read off. Attributes and material carry to the result.
## Outputs
- `geometry`: the geometry with recomputed per-vertex normals.
# material (nodebox)
Materials as records: material.pbrMat is the standard metallic-roughness material made from its PBR maps (base colour, metallic-roughness, normal, occlusion, emissive) and their factors, and material.shader a material of any surface shader, holding every property and slot to what the shader declares. Each answers one element holding the record of the material kind (`records/material.procRecord`), which geometry.set_material, instances.set_material and the other inputs that take a material put on what draws; the output node shows it and the export node saves it as a `.material`.
# instances.cull (procNode)
Keeps the instances a test says to. An instance survives when the value it is judged by is strictly above
`threshold`; `invert` keeps the rest instead. The value is the `mask` field when it is wired, else the named point
`attribute` (`field.attribute`). `elements.keep` on the points carries every attribute onto the instances that stay, so
a culled set realizes as the whole one would have. With nothing to judge by, every instance stays, and inverted, none
does.
## Inputs
- `instances` (`Points`): the set to thin out, points carrying a Mesh.
- `mask` (`Field`): the value each instance is judged by. Wired, it outranks `attribute`.
- `threshold` (`Float`, default 0.5): an instance survives when its value reads strictly above this. Raising it thins
the set, lowering it fills it back in.
- `attribute` (`String`): a point attribute on the set to judge by, read while `mask` is unwired. A name the points do
not carry is refused.
- `invert` (`Bool`, default false): true keeps the complement, every instance the test dropped.
## Outputs
- `instances`: the surviving instances.
# points.box (procNode)
A 3D lattice of points filling a box centred on the origin. Each count is at least 1, and the extent the lattice spans
is the counts times `spacing` (`value.math`). `grid.box` lays out the cells, x fastest, then y, then z, on the device,
and each cell's centre is one point. `attribute.remove` takes the cell layout off the detail so the lattice reads as
Points, and each point carries its own number as `id`.
## Inputs
- `countX` (`Int`, default 3): how many points along X. The lattice holds countX x countY x countZ points and stays
centred on the origin on every axis. Below 1 reads as 1.
- `countY` (`Int`, default 3): how many points along Y, the layers the lattice is stacked in. 1 collapses it to a single
flat sheet at y = 0. Below 1 reads as 1.
- `countZ` (`Int`, default 3): how many points along Z. Below 1 reads as 1.
- `spacing` (`Float`, default 1.0): distance between neighbouring points, the same on all three axes. The lattice spans
(count - 1) x spacing per axis.
## Outputs
- `points`: the lattice, with `id` numbering each point.
# component (nodebox)
component.set gives every element of a class a component with the fields given.
# texture (nodebox)
Textures: images drawn on the device as Texture values, a width, a height and one colour per texel. texture.noise and texture.gradient draw from a formula, texture.from_shader from an author's compute shader and texture.from_raster from the layers of a raster. A material takes a Texture in a slot, and the output node shows one.
texture.cells is the part the first two are built from: one point per texel carrying its column and row.
# geometry
Nodes that move, join, cut, round, thicken and sample meshes. A graph transforms a geometry (`geometry.transform`, `geometry.set_position`, `geometry.merge`), welds and shades it (`geometry.weld`, `geometry.smooth_normals`), models it (`geometry.extrude`, `geometry.solidify`, `geometry.bevel`, `geometry.subdivide`, `geometry.decimate`), builds surfaces from outlines (`geometry.sweep`, `geometry.revolve`, `geometry.loft`, `geometry.ribbon`) and reads it into volumes (`geometry.voxelize`, `geometry.to_sdf`). Each is built from the core nodes and the kernels of the library.
## Nodes
- `geometry.transform`, `geometry.set_position`, `geometry.set_material`, `geometry.merge`, `geometry.triangulate`, `geometry.measure`: the basic edits and the measurement of a geometry. `geometry.merge` also joins pieces into a piece set for `instances.to_points`; a part that lacks an attribute another part carries takes the value an element without it has: an instance attribute's identity, else zero (its README says exactly how).
- `geometry.weld` (with `match = "position+normal"` it keeps hard edges), `geometry.smooth_normals`: merging points and shading normals.
- `geometry.extrude`, `geometry.solidify`, `geometry.bevel`, `geometry.subdivide`, `geometry.decimate`: modelling.
- `geometry.sweep`, `geometry.revolve`, `geometry.loft`, `geometry.ribbon`: surfaces from outlines and paths.
- `geometry.voxelize`, `geometry.to_sdf`: a mesh as cells and as a distance field.
- `geometry.boolean`: union, subtract or intersect of two closed meshes, over the `intersect` kernels.
- `geometry.delete`, `geometry.separate`: the triangles a mask field or primitive attribute selects, taken away or split into two geometries (`elements.keep` on the primitives); `geometry.recalculate_normals`: `geometry.smooth_normals` at 180 degrees, area-weighted.
- `geometry.selected`, `geometry.flip`, `geometry.profile`, `geometry.tangents`, `geometry.sides`, `geometry.shared`, `geometry.bvh`, `geometry.rings`, `geometry.first`: the parts the nodes above are built from, each usable on its own.
- `geometry.unit`, `geometry.perpendicular`, `geometry.rotate`, `geometry.transport`, `geometry.split`: vector arithmetic over sockets that the nodes which orient points and normals share.
- `geometry.offsets`, `geometry.kept`, `geometry.following`, `geometry.trim`, `geometry.blank`: column arithmetic the nodes above share (a prefix sum of counts, the places a mask keeps, a ring read one place on, the primitives of no area dropped, a one-word column to bind).
## Conventions
- Each node's folder name is its call name inside the box: `geometry.<folder>`.
- Inputs and outputs carry the names of the op each node replaces.
- A node that answers a Data table from numbers read back off the device holds the Luau for it in a `readings.module` inside its own folder.
- A node with one output answers that output's value; a node with several answers a record by output name.
- A fold's index runs from 1: the first pass is 1, so a pass that works on level, chunk or step `n` reads `index - 1` when it counts from 0 (`geometry.bvh`, `geometry.to_sdf`, `geometry.sweep`, `geometry.loft`).
- A field bound to a kernel takes the length of that dispatch, so a node writes a value out as a column (a gather with an explicit `count`) before it binds one whose length differs from the dispatch's.
# sdf (nodebox)
Signed distance field nodes: shapes, smooth combines, round and shell, space warps (transform, twist, bend, taper, elongate, mirror, repeat), displacement, grids and fields in and out, and sdf.mesh, which contours a shape into a closed mesh.
# points.grid (procNode)
A flat lattice of points in the XZ plane, centred on the origin. Each count is at least 1, and the extent the lattice
spans is the counts times `spacing` (`value.math`). `grid.box`, one cell thick at height `y`, lays out the cells, x
fastest, then z, on the device, and each cell's centre is one point. `attribute.remove` takes the cell layout off the
detail so the lattice reads as Points, and each point carries its own number as `id`.
## Inputs
- `countX` (`Int`, default 4): how many points along X. The grid holds countX x countZ points and stays centred on the
origin, so each one added widens it by `spacing`, half of that to either side. Below 1 reads as 1.
- `countZ` (`Int`, default 4): how many points along Z. A count of 1 leaves a single row running along X. Below 1 reads
as 1.
- `spacing` (`Float`, default 1.0): distance between neighbouring points, the same on both axes. The grid spans
(countX - 1) x spacing by (countZ - 1) x spacing.
- `y` (`Float`, default 0.0): the height the whole lattice sits at. Every point takes this as its y.
## Outputs
- `points`: the lattice, with `id` numbering each point.
# points.filter (procNode)
Keeps the points a test says to. The value each point is tested by is the `mask` field when it is wired, else the named
`attribute`'s values (`attribute.labels`). The test is a comparison (`field.compare`): above `threshold`, or, when
`equals` is given, equal to the index that value or label names. `elements.keep` on the points carries every attribute
and the detail onto the points that stay, counted on the device. Given neither a mask nor an attribute, the points come
back as they are.
## Inputs
- `points` (`Geometry`): the cloud to thin. Every point attribute and every detail value is carried onto the survivors,
so a colour or an index still belongs to the point it started on.
- `mask` (`Field`): the per-point value tested; a point stays when it is above `threshold`. Wired, it decides, and
`attribute` is read only when this is empty.
- `threshold` (`Float`, default 0.5): a point stays when its value is strictly above this. Raising it keeps fewer
points.
- `attribute` (`String`): a point attribute to test instead of wiring `mask`. A name the points do not carry is refused,
naming the ones they do.
- `equals` (`String | Float`): keeps the points whose `attribute` equals this instead of testing it against
`threshold`. It is a number, or a label: one of the texts a text attribute holds, or one of the names the points'
detail `labels` gives a numeric one (how one solver's particles are split back by the `stream` their source named).
## Outputs
- `points`: the points that stay.
# geometry.delete (procNode)
Deletes the triangles a test selects. A triangle is selected when its value is strictly above `threshold`. The value
each triangle is tested by is the `mask` field when it is wired, else the named primitive `attribute`
(`field.attribute`), else 0. `invert` deletes the triangles the test did not select. `elements.keep` on the primitives
does the removal: every point stays, and the triangles that remain keep their corners and attributes, counted on the
device.
## Inputs
- `geometry` (`Curves | Surface`): whose triangles are thinned. Point and detail attributes carry over as they are;
primitive and vertex attributes stay with the triangles that survive.
- `mask` (`Field`): read once per triangle for whether it goes. Wired, it is what the selection reads, and `attribute`
is read only when this is empty.
- `threshold` (`Float`, default 0.5): a triangle is selected when its value is strictly above this. Raising it deletes
less.
- `attribute` (`String`): a primitive attribute on the geometry to read the selection from, instead of a wired mask. A
name the triangles do not carry is refused.
- `invert` (`Bool`, default false): true deletes every triangle the test did not select, so a mask naming what to keep
cuts away the rest.
## Outputs
- `geometry`: the geometry with the selected triangles removed.
# shader (nodebox)
An author's own compute shaders as nodes. shader.compute runs a .computeShader over the elements of a geometry through the device.kernel op: each buffer binding is a column of the geometry, each param a knob of the node, and what the shader writes comes out as columns.
# scene (nodebox)
scene.query finds entity ids by name, component and hierarchy, scene.fetch brings entities in as points carrying their pose and components, scene.input is the entity the graph stands on, and scene.water is the water the scene holds.
# geometry.separate (procNode)
Splits a geometry's triangles in two by a test. The value each triangle is tested by is the `mask` field when it is
wired, else the named primitive `attribute` (`field.attribute`), else 0. Two comparisons against `threshold` follow
(`field.compare`): strictly above, and at or below. `elements.keep` on the primitives runs once for each, so `a` holds
the triangles above and `b` the rest. Both keep every point, and between them they hold every triangle once.
## Inputs
- `geometry` (`Curves | Surface`): whose triangles are divided. Point and detail attributes carry to both halves as they
are; primitive and vertex attributes stay with each half's own triangles.
- `mask` (`Field`): read once per triangle for which half it joins. Wired, it is what the split reads, and `attribute`
is read only when this is empty.
- `threshold` (`Float`, default 0.5): a triangle goes to `a` when its value is strictly above this, and to `b`
otherwise.
- `attribute` (`String`): a primitive attribute on the geometry to read the split from, instead of a wired mask. A name
the triangles do not carry is refused.
## Outputs
- `a`: the triangles whose value is strictly above `threshold`.
- `b`: the rest. A call answers both as a record by output name.
# 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.** Each caller is charged the time it runs
between its readings of the slice in a frame (`task.runTime`), whoever runs
it, and the charges of every caller add up to the frame's slice. What the
rest of the frame runs (systems, components, other tasks) is not charged, so
a busy frame still gives the slice to the work. 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
```
## The background lane
Some work is started early so it is ready when asked for, and no picture waits
on it, such as the search text an editor reads ahead of the first
`tools.search`. `background(fn)` runs `fn` on the background lane: every
`yield`, `due` and `wait` its work makes on that coroutine hands the frame back
for as long as a hold on the lane stands, and takes its slice as usual once
none does.
```luau
FrameBudget.background(function()
for _, path in ipairs(paths) do
FrameBudget.yield()
warm(path)
end
end)
```
Work the picture waits on holds the lane while it runs: `holdBackground(key)`
until `releaseBackground(key)`. A world's entry holds it under `"world entry"`
from the moment the world is ready (its `onRegister` sweep) until its
`onWorldLoad` has returned, so the frames of the entry carry the world's load
and the background work runs in the frames before and after it. A hold no one
releases lapses after `BACKGROUND_HOLD_SECONDS` (or the seconds it was taken
for), with a warning naming its key, so work on the lane always runs in the
end. `backgroundHolds()` lists the keys holding the lane now, and
`backgroundWaits()` answers whether the calling code's next unit waits for it
(a walk with a clock of its own asks it between its pieces).
`FrameBudget.DEFAULT_MS` is the slice a call that names none spends. `spent()`
answers how much of the current frame's slice is gone.
A caller with a budget of its own reads `mark()` where its work starts.
`ranMs(mark)` answers how long it has run since, none of the time it spent
suspended; `cpuMs(mark)` answers the CPU time of its work since: those
stretches and the stretches of every coroutine it resumes, and every one they
resume, while it waits on them, which a machine whose cores are taken by other
work does not stretch, so a bound that refuses work for running too long
refuses the same work on a loaded machine as on an idle one, and work handed to
a coroutine as work run in place. A task it starts and waits for runs while it
is suspended, which `cpuMs` does not count.
# sim (nodebox)
Simulation nodes: sim.spawn, sim.force, sim.collider, sim.scene_colliders, sim.particles and sim.shader, built on the runtime's g:state and g:step.
# mesh
The primitive solids and sheets a graph starts from: `mesh.box`, `mesh.sphere`, `mesh.cylinder`, `mesh.cone`, `mesh.capsule`, `mesh.octahedron`, `mesh.torus`, `mesh.rounded_box`, `mesh.plane` and `mesh.grid`. Each is made on the device from lattices and fans of the `make` kernel, with positions, normals and texture coordinates written as formulas over the lattice, and answers triangles centred on the origin that fill the box its parameters name.
## Conventions
- Each node's folder name is its call name inside the box: `mesh.<folder>`.
- Parameters keep the names and defaults of the op each node replaces.
- `mesh.lattice` makes the lattices and fans the presets share, `mesh.spherical` the point of a sphere and `mesh.cube_faces` the faces of a cube; a preset writes its positions, normals and texture coordinates as formulas over the lattice.
# io
The ways in and out of a graph: `import` brings an asset in as the value its type states, `luau` runs a function of a Luau module on the CPU, `output` shows a value in the world and answers a Handle, `export` saves a value as an asset, and `engine` calls the engine bridge that `import`, `export` and the core reading nodes use. `output` holds `show.module` and `engine` holds `engine.module`, the functions they call.
# entity (nodebox)
entity.transform and entity.bounds read one entity's pose and bounds as values, entity.points reads a set of entities as points, and entity.geometry reads the mesh an entity's Model draws as a Geometry.
# proc.substrate
The substrate a graph carries: a geometry, its four domains (point, vertex, primitive, detail) and the named columns over them. A point is a position and an identity; a vertex is one primitive's use of one point; a primitive is a run of vertices (a face, a curve or a volume); detail is the geometry itself, one element. An attribute is a named, typed column over one domain. A numeric column is a `substrate.createBuffer` handle, the engine's one buffer primitive, so the handle a column holds is the one a kernel runs over and a compute shader binds; a column of a type a buffer cannot express (text, a reference, a record) is carried as values and placed on the device interned. `Geometry`, `Column` and `Domain` are the value types; `fromArrays`, `fromPositions`, `fromCurves` and `fromPointCloud` build a geometry. `man proc.substrate` lists every function with its arguments.
Part of `@builtin::systems.procgen.proc`; reached as `proc.substrate`.
# substrate Module
Public Luau surface over the `__substrate` Internal FFI namespace — the
engine's typed data buffer, on the CPU or the GPU.
## Purpose
A substrate buffer is a typed run of values you hold a handle to. The
element type (`f32`, `vec3`, `vec4`, `quat`, `mat4`) sets the stride, so
a buffer knows its own shape and a read comes back in the units it was
written in. `kind` places it: a `"cpu"` buffer is storage the engine holds
outside the Luau heap, a `"gpu"` buffer is storage a compute shader binds.
Everything a buffer does hangs off its handle, so a buffer travels as a
value rather than as a name someone else has to resolve. This is what
animation poses, IK chains, particle pools, and compute-shader storage
are all made of.
This is a distinct primitive from the standard Luau `buffer` library. A
Luau `buffer` is untyped bytes held in the Luau heap, where what it holds
counts in full, so it suits small amounts. A large block of data belongs
in a substrate buffer and passes through Luau a chunk at a time:
`writeBytes` places a packed chunk at a byte offset, and reading the
buffer's bytes back into Luau (`:bytes()`, `:read():resultBytes()`) makes
a copy in the Luau heap. The type here is
`TypedBuffer` for that reason.
## Usage
```luau
-- A CPU buffer: 64 bone poses, 10 floats each
local pose = substrate.createBuffer({ type = "f32", len = 64 * 10 })
pose:write({ 0, 1, 0, 0, 0, 0, 1, 1, 1, 1 }, 0)
local values = pose:read(0, 10):result()
pose:fill() -- every value back to 0
pose:destroy()
-- A GPU buffer a compute shader reads back
local field = substrate.createBuffer({
type = "vec3", len = 4096, kind = "gpu", usage = { "readback" },
})
```
A buffer a compute shader works over comes from the shader, which names
it for the dispatch and allocates it here:
```luau
local sim = asset.resolve("@builtin::mySim.computeShader")
local verts = sim:createBuffer("verts", { type = "vec3", len = 1024 })
sim:dispatch({ x = 16 })
local out = verts:read():result()
```
## Reads
`:read()` answers with a `Readback` for both kinds — a CPU read is one
that is simply already done. Code that reads a buffer therefore never
branches on where the buffer lives:
```luau
local rb = field:read()
if rb:ready() then
local floats = rb:result() -- also :resultU32() / :resultBytes()
end
```
`:state()` reports `"pending"` / `"ready"` / `"unknown"` without draining
and without raising.
## Size
A `"cpu"` buffer holds at most 1 GiB. A `"gpu"` buffer holds at most what the
device creates in one buffer, its `max_buffer_size`, which each GPU, driver and
browser states for itself. A `len` past either bound raises at `createBuffer`,
naming the bytes it needs, the bound, and the most records of that type one
buffer holds; nothing is allocated and no handle exists for it. Data larger
than one buffer is split across several.
## Lifetime
A handle outlives the storage it points at: `destroy` frees the allocation, and
every other holder of that buffer keeps its handle. `:alive()` is what they ask,
and it answers false the moment the storage is gone, through this handle or any
other. When the render device is lost, a `"gpu"` buffer is allocated again on
the device built to replace it, empty, and its handles keep answering; one past
the new device's `max_buffer_size` is gone instead, and its handles answer
false. Binding a dead handle to a compute dispatch is refused at the call that
binds it.
## Exports
- `substrate.createBuffer({ type, len, kind?, usage?, name? })` → `TypedBuffer?`
On the handle: `write` `read` `length` `type` `kind` `alive` `destroy`, the CPU
arithmetic `fill` `add` `scale` `addStrided` `axpby` `lerp`, the indexed
accessors `getVec3` `setVec3` `getQuat` `setQuat`, and `bytes` for
per-element access through the Luau `buffer` library.
For element-wise NumPy-style kernels over these buffers, use the `nx`
module; for slice-and-target position / orientation forms, `mathx`.
# Scatter
Strews copies of one shape over the surface of another, each with its own turn, lean and size.
Both the surface and the thing scattered are inputs, so this covers rocks on a hillside, crates on a deck, bushes
along a bank or rubble across a floor: wire it a different `source` and it is a different field.
It makes points on the surface (`points.on_surface`, area-weighted), gives every point its own random yaw, lean and
scale (`instances.randomize_transform`), and places the source on those points (`instances.on_points`). The transform
is read from the same point cloud the instances sit on, so each copy takes the pose of its own point.
## Inputs
| Input | Type | Default | What it does |
|-------|------|---------|--------------|
| `surface` | Geometry | none | What the copies land on. Points are area-weighted, so a bigger face gets proportionally more. |
| `source` | Geometry | none | The shape being copied. |
| `count` | Int | 200 | How many copies. |
| `seed` | Int | 1 | Changes the arrangement. The same seed always gives the same field. |
| `scaleMin` | Float | 0.8 | Smallest per-copy size multiplier. |
| `scaleMax` | Float | 1.4 | Largest per-copy size multiplier. Equal to `scaleMin` means uniform. |
| `tilt` | Float | 0.15 | Radians of random lean off vertical. `0` stands every copy upright. |
## Output
`instances`: a population, the points each carrying the source as its `Mesh`. A Generator draws it as one
hardware-instanced draw call per source; `instances.realize` merges it into a single Geometry.
## Calling it
Another graph calls a `.procGraph` as it calls a node, by its path or identity, naming the inputs in a table; the
call answers what the graph outputs (`instances`). Its declared inputs are the call's inputs.
# proc.registry
The operation registry: register/lookup/schema/search/help for procedural ops.
Part of `@builtin::systems.procgen.proc`.
# 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.
# proc.hash
Deterministic, portable scoped hashing for the procgen evaluator.
`scoped(seed, graphId, compositePath, nodeId, channel, elementId) -> number`
folds its arguments with 32-bit FNV-1a (via an exact 16-bit-split `mul32`)
and a final avalanche, producing a bit-identical `u32` on native, WASM, and
Android. `unitFloat(...)` maps the same scope to a value in `[0, 1)` for
deterministic random draws.
No `math.random` / `os.time` / float transcendentals — determinism is the
contract. The per-element scope (`elementId`) keeps a given element's draw
stable as unrelated element counts grow.
# entity_resolve
The id behind an entity reference, whatever shape the reference took.
An entity is written down three ways: as an **id string**
(`"ent_5d305b4377f8d505"`), as an **entity proxy** (the table carrying
`.position`, `.component`, `.name`), and — by a person or an agent typing a
call — as the **display name** the entity carries in its Name component.
`entity(ref)` answers for the first two. A call that hands it a name gets nil
back, and code that reads that nil as "the entity is gone" either indexes it or
writes somewhere else entirely. This module is the one place that turns any of
the three into the id every engine call takes.
## Surface
```
local resolve = require("modules.entity_resolve")
resolve.id(ref) -> string? -- the id, or nil when nothing matches
resolve.idOrError(ref, slot) -> string -- the id, or a raise naming the miss
```
`ref` is an id string, a display name, or an entity proxy. `slot` names the
argument the reference arrived in, so the raise reads as the call the caller
wrote rather than as a line number inside the callee.
A proxy or an `{ id = ... }` record answers the id written on it. A string is
the shape the scene has to answer for, since a lookup is the only thing that
can say whether it is a name or an id — and both probes stay silent for one
that matches nothing: a name is tested with `entity.find`, which answers for an
id as well, and then as an id with `entity.exists`, which raises for a string
naming a live entity and is therefore probed under `pcall`. A string matching
nothing reaches the caller as `nil`, with nothing already written to the log on
its behalf.
## Examples
Accept whichever shape the caller wrote, then act on the id:
```lua
local resolve = require("modules.entity_resolve")
local function raise(target, dy)
local id = resolve.idOrError(target, "target")
local e = entity(id)
e.localPosition = { e.localPosition.x, e.localPosition.y + dy, e.localPosition.z }
end
raise("crate_07", 2) -- a display name
raise("ent_5d305b4377f8d505", 2) -- an id
raise(entity.find("crate_07"), 2) -- a proxy
```
Answer for a reference that may match nothing, without raising:
```lua
local id = resolve.id(maybeGone)
if id ~= nil then
entity(id).despawn()
end
```
# clientSettings
The client's settings: the person's own on this device for the account signed
in, the same in every world, on every platform and in a headset. They are a
different thing from a world's own settings: `settings` is the world's
settings file (`/zero/source/.world_settings`), authored with the world.
- **Declared once, by the engine.** A group is one tab of the settings menu:
`clientSettings.registerGroup{ id, title, description, icon, order, visible }`,
where `visible()` says whether the tab shows on this client now. Entries
name their group: `clientSettings.register{ ... }`. A setting carries
- a `field` its every value is held to (`Field.enum`, `Field.range`,
`Field.bool`), whose default is the setting's default; `labels` names an
enum's members, `step` and `format` shape a range;
- a `scope`: `"device"` for what depends on this machine, `"userPlatform"`
for what follows the person on this kind of platform;
- an `effect` of kind `"engine"`: `apply(value)` takes the value into the
engine (on register, on every change and when the account changes), and
`changed(value)` runs only when the person changes or resets it.
An action carries no field and no value: its effect is `run()`, shown as a
`button`. `available()` on either says whether it can be used now and, when
it cannot, why.
Every word a person reads (`title`, `description`, `label`, `button`, an
enum's `labels`) is text or `{ key = "namespace.key", values? }`, the
catalog message said in the player's language each time the menu is drawn.
- **Reading.** `clientSettings.get(key)` is the value the person chose, or the
setting's default. `clientSettings.list()` states every group with each
entry's value, default, `source` (`"player"` once the person chose one,
`"default"` before), scope, choices or range, and availability; the menu
draws exactly that list. A world reads the settings it needs, e.g.
`clientSettings.get("xr.perspective")`.
- **Changing.** `clientSettings.set(key, value)` holds the value to the field,
keeps it and carries out the effect; `clientSettings.reset(key | group)`
returns a setting or a whole group to its defaults; `clientSettings.run(key)`
runs an action. Each is refused with world or agent code on the Luau stack,
naming the setting: the person changes their settings in the menu, and a
world reads them and never changes them.
- **The System tab.** The settings show as the System tab of the app menu
(`appMenu`), the menu the pause action opens: every visible group a
section, with **Reset to defaults** on a section where the person chose
something. `clientSettings.open(group?)` opens the menu on that tab, from
anywhere, a world's own code included; the editor's **Settings…** and the
gear on its dock in a headset do the same. The tab shows while
`clientSettings.reachable()` is true, that is while some group is visible.
- **The groups.** **VR** (`xr_menu`) shows while this client can draw to a
headset; every other group shows in a headset as it does on a desktop.
- **Where values are kept.** As preferences of the signed-in account on this
device (`zero_account_prefs`, under `setting.<key>`), whatever the scope;
with nobody signed in, the signed-out record. Signing in or out switches to
that account's settings and applies them.
`clientSettings.onChanged(fn)` hears each change, and `fn(nil)` when the
account changes. `clientSettings.buildSection(model)` returns the System
tab's widget tree for a state, laid out for a desktop, a phone or a
headset's panel.
# pathTracing
A progressive path-traced view of the scene through the active camera — the
converged image the real-time renderer is trying to approximate, on screen next
to it.
The engine's existing path tracers answer "what light arrives at this surface"
and write the answer into a lightmap or a probe field. This points the same
transport at the camera: every pixel is a path, and what comes back is a
reference image. Held still, it converges over seconds; move the camera and it
starts again.
## Using it
```luau
local referenceView = require("@builtin::systems.pathTracing.referenceView")
referenceView.enable({ samplesPerFrame = 4, bounces = 5 })
-- ... let it converge ...
print(referenceView.settings().samples) -- how far along it is
referenceView.disable()
```
`enable` snapshots the scene's geometry and lights into GPU buffers and starts
tracing. `refresh()` retakes that snapshot after the scene changes; `reset()`
restarts the accumulation without re-snapshotting, for a change the view cannot
see by itself (a light retuned in place). The camera is watched automatically —
any movement restarts it.
`settings()` reports `samples` (how many are in the displayed image),
`converged` (whether it has reached `maxSamples`), and the size of the scene
snapshot in triangles, nodes and lights.
## What it traces
- **Geometry** — every visible mesh-bearing world entity, movable ones
included, as a BVH built by `compute.buildBvh`. Alpha-cutout surfaces are
traced through their coverage masks, so foliage reads as foliage.
- **Materials** — the albedo, emissive, roughness and metallic the raster path
shades with, through a GGX-over-Lambert microfacet BSDF split by metalness.
Both lobes are importance-sampled, and paths terminate by Russian roulette
rather than at a fixed depth.
- **Lights** — every light the bake gathers: directional, point, spot, ambient
and area. Area lights are sampled per path, so their penumbrae emerge from
the accumulation rather than being approximated.
## Shape
| Piece | Role |
|-------|------|
| `referenceView.module` | The public surface. Owns the scene snapshot, the accumulation state, and the camera watch. |
| `pathTrace.renderFeature` | The GPU passes: trace-and-accumulate, resolve, blit. Enqueues nothing while the view is disabled. |
The tracer renders the camera the view was enabled for, from parameters the
module packs, rather than the camera of whichever render target a pass runs in.
One accumulation belongs to one camera, so an offscreen capture drawn in the
same frame shows the same converged image instead of resetting it.
Everything is buffer-bound: no hardware ray tracing, no deferred G-buffer, and
so the same code on either backend and either platform.
# display_writers
The ordered record of what is setting the chain's display transform.
`__display__` carries one curve and one exposure for the whole frame. Several
things write them — every `global` `PostProcess` region with
`setsDisplay = true`, a scene's opening state, an agent's own `setProperty`
call — and this module records the live ones, newest last.
```lua
local DisplayWriters = require("@builtin::modules.display_writers")
DisplayWriters.push("look", { curve = 2, exposure = 1.5 }) -- ACES, +2/3 stop
DisplayWriters.remove("look") -- back to what stood
```
- `read()` — what `__display__` holds now: the value the last write left, or the
default the renderer declares for a property nothing has written.
- `push(key, { curve, exposure })` — show those values and record `key` as the
writer holding them. A key already recorded moves to the newest position.
- `remove(key)` — drop that writer. The display then shows the newest remaining
writer's values, or what stood before the first writer arrived when none
remain.
- `count()` — how many writers are live.
The record is one shared list, so the writers come off in any order: removing
the older of two leaves the newer one's values standing, and removing the newer
leaves the older's.
The exposure package drives `__display__.exposure` alone, from a GPU readback,
every tick it meters, and keeps that outside this list — so a region that
arrives or leaves sets the exposure and the package's next readback sets it
again. The package holds its own record of the exposure that stood before it
started metering and hands that back when it stops.
# vfs Module
Public Luau surface over the `__vfs` Internal FFI namespace — the
engine's virtual filesystem.
## Purpose
Wrap the raw `__vfs.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.vfs` via the prelude. The standard read / write /
move / remove / mkdir / list / exists / readAsync / reload / evict
surface, plus trusted-only `watch` / `unwatch` for the bootstrap VM.
`vfs.read` yields on a byte-cache miss: the module's last step installs
the `vfs_async_read` fallback over the synchronous read, so every VM that
holds this namespace, the trusted VM included, reads a path through the
same two steps and gets the same bytes for it.
## Usage
```luau
-- Read / write
local src = vfs.read("@builtin/components/Camera.luau")
vfs.write("/zero/source/notes.md", body)
-- What a write landed: where the bytes went, and what the static passes
-- read in the Luau among them
local ok, report = vfs.write("/zero/source/game/Vent.component/init.luau", code)
if report.diagnostics then
for _, d in report.diagnostics do
print(d.severity, d.path, d.line, d.message)
end
end
if not report.durable then
log.warn(report.warning)
end
-- Listing
for _, e in ipairs(vfs.list("/zero/source")) do
print(e.isDirectory and "[d] " or " ", e.name)
end
-- Async fetch
local png = task.await(vfs.readAsync("/zero/runtime/screenshots/last.png"))
-- Reclaim RAM after processing a big binary
vfs.evict("/zero/source/textures/imported_huge.png")
-- Reload a module after editing its source on disk
if vfs.reload("@mylib/utils.helpers") then
local m = require("@mylib/utils.helpers") -- sees the new source
end
```
`vfs.reload(identity)` answers whether a module was cached under that name
and has now been dropped. A `false` says the name matched nothing — either a
misspelled identity or a module this VM never required — so the next
`require()` returns whatever it would have returned anyway.
A module that caches state derived from OTHER files keeps serving the old
value when those files are rewritten, since only its own source is watched.
Reload it by identity to make the next `require()` recompute.
## How a write reaches disk
A native engine's `vfs.write` returns once the engine holds the bytes and the
session's journal holds the record of the write, its bytes with it. The record
is in the operating system's hands before the call returns, so an engine
process that ends right after a write, however it ends, leaves the write for
the next session on the same machine to owe and make again. The blob a binary
write stores by content is written and flushed by a worker thread (`vfs-io`) in
the order the writes were made, so a script that writes a thousand files pays
for handing them over and for their journal records, not for the flush of
each. A read of a blob still waiting for its file answers from memory, so a
write reads back the moment it returns. A queue holding more than its byte
budget (256 MiB) makes the next write wait for it and write inline, which
bounds the memory the queue pins. The queue is flushed when the engine exits
normally. `world.syncStatus()` reports nothing owed once the writes have also
reached the world.
## Exports
- `vfs.read(path, opts?) -> string?`
- `vfs.write(path, content, opts?) -> (boolean, WriteReport | string)`
- `vfs.move(src, dst, opts?) -> (boolean, WriteReport | string)`
- `vfs.copy(src, dst) -> (boolean, WriteReport | string)`
- `vfs.remove(path, opts?) -> (boolean, string?)`
- `vfs.mkdir(path, opts?) -> boolean`
- `vfs.list(path?) -> { VfsListEntry }`
- `vfs.exists(path, opts?) -> boolean`
- `vfs.readAsync(path, opts?) -> promiseId`
- `vfs.reload(modulePath?) -> boolean`
- `vfs.evict(path, opts?) -> boolean`
- `vfs.mutationSeq() -> number`
- `vfs.contentClock() -> number`
- Trusted-only: `vfs.watch(path, callback) -> number` /
`vfs.unwatch(watcherId) -> boolean`.
# debugViz_driver
The ambient edit-mode debug-visualization driver. Requiring it registers the
built-in providers (bounds, frustum, bones, colliders, icons, wireframe) with
`@builtin::modules.debugViz`; the editor entrypoint requires it and calls
`tick(dt)` every frame.
```lua
local DebugVizDriver = require("@builtin::modules.debugViz_driver")
-- In the editor entrypoint's per-frame hook:
DebugVizDriver.tick(dt)
```
- `register()` — register the built-in providers. Idempotent: `registerProvider`
replaces by name and a guard makes a re-require a no-op, so a category toggled
off in the panel survives a module reload. Called on require and by `tick`.
- `tick(dt)` — per-frame hook for both modes. Edit mode always rebuilds the
overlay; play mode rebuilds only while a debug session is active
(`debugViz.setPlaySession`) and otherwise clears the batch, so play mode
carries no debug-draw cost by default.
There is no per-entity opt-in — the overlay is editor tooling, driven here for
the whole scene. Toggle categories through the Debug → Visualization panel or the
`debug` toolbox.
# lumen_player
A UI template screen.
# xr_body
The body that follows the person in a headset, in the way of a social VR avatar:
three-point IK from the head and the two hands.
The eyes are the real head, and the body follows it:
- **Lean, look and crouch** move the upper body. The head bone reaches the real
head: the hips drop for a crouch and shift toward a lean, the spine bends the rest
of the way, and the neck and head turn toward the way the head faces (the body's
`IKRig`, `headTarget` and `lookTarget`).
- **The torso turns** toward the way the head faces once the head is past a slack
of 40 degrees, at 160 degrees per second, while the body is not walking.
- **Real steps** in the room carry the body once the head stands 0.3 m from it,
through the character controller's own wall pass, so a wall stops the body. What
the body was carried by is taken out of the eyes' offset (`body.absorbed`), so the
eyes stay where the real head is.
- **The legs step** when the body moves or turns. A foot stays where it was
planted until its home, beside the body, is 0.2 m away; then it steps (0.24 s, 8 cm
high), one foot at a time, and plants. The `IKRig` foot targets carry the feet.
- **Trackers** place the hips and the feet: a device located under the role `waist`
places the hips, and `left_foot` and `right_foot` place the feet in place of the
stepping.
The pure rules are `followStep`, `yawStep`, `stepFeet`, `footHomes`, `headBoneTarget`
and `eyesFromHead`. `new(bodyEntity)` makes a body and `tick(body, frame, rig)` runs
one frame against it; `drop(body, rig)` takes the targets down. The presentation of
`xr_embodiment` runs it.
# logs Module
Public Luau surface over the `__logs` Internal FFI namespace —
read-only, filterable query API over the engine's in-memory log ring.
## Purpose
Wrap the raw `__logs.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.logs` via the prelude. The store is the single
in-engine source of truth for everything the engine has logged
recently — Rust `console_log!`, bridged third-party `log::*` events
(wgpu validation, etc.), and Rust panics. The same store backs the
`/engine/logs` HTTP endpoint and `/zero/runtime/logs/engine`.
## Usage
```luau
-- Did anything break?
for _, e in ipairs(logs.errors(10)) do print(e.timestamp, e.message) end
-- Filtered query
for _, e in ipairs(logs.query({ level = "warn", type = "RENDERER", limit = 50 })) do
print(e.message)
end
-- Case-insensitive grep
local hits = logs.find("MY_MARKER")
-- Aggregate counters (lifetime, survive ring eviction)
local c = logs.count()
print(c.errors, "errors,", c.warnings, "warnings,", c.dropped, "dropped")
```
## Exports
- `logs.query(opts?) -> { LogEntry }`
- `logs.errors(limit?) -> { LogEntry }`
- `logs.warnings(limit?) -> { LogEntry }`
- `logs.find(text, limit?) -> { LogEntry }`
- `logs.tail(limit?) -> { LogEntry }`
- `logs.count(opts?) -> LogCounts`
- `logs.template(message) -> string`
- `logs.clear() -> boolean`
## Origin
A line a script logged carries `script` and `entity` fields, so
`logs.query({ entity = "ent_9f3c" })` asks for one entity's output rather than
guessing at what its messages look like. Engine lines carry neither.
## Context
`logs.query({ level = "error", context = 3 })` also returns the three lines
either side of each match, marked `context = true`. What led up to a failure is
made of lines the filter rejected, so a filtered view cannot otherwise show it.
## The other ways in
The `logs` toolbox reads the same ring through the tool surface — its `search`,
`tail`, `errors`, `summary` and `clear` tools — and adds grouping of repeated
messages. This module is the direct Luau path to that ring.
The ring is also mounted as plain files: `/zero/runtime/logs/engine` for every
level, `/zero/runtime/logs/errors` for the ERROR-and-above subset, and
`/zero/runtime/logs/script` for what scripts logged. Those render the most
recent 500 lines with tool-call records included, where a query here reaches
the whole ring and leaves them out unless asked for.
The ring starts empty at every boot. `/zero/runtime/logs/previous` holds the
previous session of the world the engine booted on: how it ended, then the last
lines it wrote.
# http Module
Public Luau surface over the `__http` Internal FFI namespace — async
HTTP GET / POST returning JSON or raw bytes.
## Purpose
Wrap the raw `__http.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.http` via the prelude. Every method returns a
promise handle: pass it to `task.await(handle)` to block the
coroutine until the request completes.
## Usage
```luau
-- GET JSON
local data = task.await(http.get_json("https://api.example.com/info"))
-- POST JSON
local resp = task.await(http.post_json(
"https://api.example.com/users",
{ Authorization = "Bearer " .. token },
{ name = "Alice", age = 42 }
))
-- Download a binary asset
local bytes = task.await(http.get_bytes("https://example.com/sound.ogg"))
vfs.write("/zero/source/audio/sound.ogg", bytes)
```
## The bound a request carries
Every method takes a deadline after its own arguments: how long the request is
given to be answered, in milliseconds. Left out, the engine's own bound
applies, which is what settles a call against a peer that accepts the
connection and answers nothing. Passed as 0, no bound applies, which a
transfer whose length the caller knows better than the engine does names.
A request given up on resolves like any other failure, with the engine's error
envelope: `{ "__http_error": true, "error": "Network error: no answer within
<n>ms" }`.
```luau
-- Give this call three seconds to be answered
local credential = task.await(http.post_json(tokenUrl, headers, nil, 3000))
-- A download whose length the caller knows better than the engine does
local bytes = task.await(http.get_bytes(assetUrl, nil, 0))
```
## Statuses the caller expects
Every method takes, as its last argument, the HTTP statuses the caller handles
as an answer it expected: the 404 of a read whose subject may not exist yet,
say. A response with one of them settles the future exactly as any other
non-2xx does, with the error envelope, and the engine logs it as information.
Every other failure, a status the caller did not name and a request that
reached no status at all, is logged as an error. So an error line in the log
is always a failure somebody has to look at. Each entry is a whole number
from 100 to 999, and a call naming anything else raises, naming the entry.
```luau
-- A world that has published nothing answers 404: an outcome, not a failure
local answer = task.await(http.get_json(manifestUrl, headers, nil, { 404 }))
```
## Exports
- `http.get_json(url, headers?, timeoutMs?, expectedStatuses?) -> promiseId`
- `http.get_bytes(url, headers?, timeoutMs?, expectedStatuses?) -> promiseId`
- `http.post_json(url, headers?, body?, timeoutMs?, expectedStatuses?) -> promiseId`
- `http.post_bytes(url, headers?, body?, timeoutMs?, expectedStatuses?) -> promiseId`
- `http.request(method, url, headers?, body?, timeoutMs?, expectedStatuses?) -> promiseId`
- `http.request_raw(method, url, headers?, body?, timeoutMs?, expectedStatuses?) -> promiseId`
# recording
Record a video clip (MP4) of the scene as it shows, or of the whole editor
window with its panels: a screen recording for a trailer, a post or a bug report.
Takes are named by the local date and time and filed
under `/zero/source/local/recordings/`, this machine's own content. A take is
written to disk as it records, so it holds no engine memory, survives a
restart and is never synced to a world.
## The loop this is for
```
recording.start -- the scene view; F9 in the editor does the same
… work …
recording.status -- seconds of film and bytes written so far
recording.stop -- ends the take and reports the file
recording.list -- every take, newest first
```
`recording.start window` films the whole editor window instead. The scene view
shows what the viewport shows, so switch the editor's overlays off before a
take that should be clean.
## A master for editing and delivery
`recording.start` takes the options that cut a master: `quality` (1 to 100, 100
is the near-lossless picture), `width` and `height` (a 4K take is 3840 by
2160), `cadence "frame"` with `seconds` for a timeline that
advances a step per rendered frame, `audioTrack` (the VFS path of a pre-mixed
wav, ogg, mp3 or flac the take carries as its sound; it starts at the first
frame and ends where the film does, on either cadence) and `name` (the file
name under the recordings directory). `man recording` and the `recording` guide
(`guides recording`) carry the whole set.
## Getting a take out of the engine
A take is the machine's own content, kept in the engine's blob store under
`/zero/source/local/recordings/`: it has an engine path, and no folder of its
own on the host disk to point at. To hand it to a person:
- in the editor, the Recording panel's **Save to this device** (the browser
downloads it, a native engine opens its save dialog); `Recording.save(path)`
and `userfile.save(path)` do the same from Luau;
- an engine with no window has no one at its screen to save to: serve the take
from a route (`httpServer.route("GET", "/take", function() return { file =
"<engine path>" } end)`) and fetch the address `httpServer.address("/take")`
names.
## The tools
| Tool | What it does |
|---|---|
| `start [scope] [camera] [fps] [audio]` | Start a take. Scope is `viewport` (default) or `window`. |
| `stop` | End the take and wait for the engine to file it. |
| `status` | Whether a take runs, its file, seconds and bytes so far. |
| `list` | The takes on this machine, newest first. |
The same service is `require("modules.api.editor.recording")` in Luau.
# audio Module
Public Luau surface over the `__audio` Internal FFI namespace — the
engine-native CPU audio codec for the canonical ZAUD payload (backed by
`zero_audio::blob`), and the engine's audio observation surface. Auto-injected
as `_G.audio` via the prelude.
## Observing what is audible
`audio.observe()` answers "what is this engine sounding right now, and why is a
source not" in one read. It reports the MIXER's own bookkeeping, which is what
makes it different from reading the `Audio` component's fields back: those carry
what content asked for, and `AudioSource.state` carries the value `:play()` wrote
there. Every voice report carries both — `mixerState` beside `componentState` —
so the two are compared rather than confused.
- `audio.observe() -> AudioObservation` — the whole surface in one call:
`{ available, sampleRate, channels, sampledAtMs, voices, audibleCount,
listener, voiceAccounting, levels, profile }`.
- `audio.voices() -> { AudioVoice }` — every live source with the mixer's
opinion of it: the clip, the channel, whether its bytes are resident, the
mixer's playback state, the position in the clip and the clip's duration, the
gain it reaches the mix at stage by stage, the rate it plays at (`pitch`,
the Doppler ratio `doppler` and their product `rate`), and for a spatial
source its emitter, the listener distance, `maxDistance`, `rolloff` and the
`radialSpeed` it and the listener move apart at.
- `audio.voice(entityId) -> AudioVoice?` — the voice on one entity.
- `audio.whySilent(entityId) -> reason?, detail?` — why a source makes no sound,
from a closed set: `noBackend`, `noDevice`, `notResident`, `neverStarted`,
`refused`, `paused`, `ended`, `gainZero`, `channelSilent`, `masterSilent`,
`outOfRange`. `nil` while it IS sounding; the second return carries the
mixer's own words when it refused the source.
- `audio.device() -> AudioDeviceStatus` — the output device the mix reaches:
`state` (`"open"` / `"silent"`), the device an open stream runs on, the rate
and channel count it runs at, and the counters for what the engine has been
through keeping a stream open — `faults`, `changes`, `reopens`, `failedOpens`,
`glitches` and `lastError`. An output device that goes away leaves the mixer running and
every voice reporting `noDevice` until the engine opens a stream again.
`parked` is true while nothing plays and the output rests (`parks` counts
the times, `resumeLatencyMs` is how long the last resume took to play).
`held` names what the platform holds the output quiet for while the mixer
still has sound (`"background"`, `"focusLost"`); a held output is parked and
every voice waits where it is. `outputLatencyMs` is how long after the mixer
renders a period it is heard, and `performanceMode` the latency mode the
platform runs the stream in where it states one.
- `audio.levels() -> AudioLevels` — the master mix's peak and RMS over the
meter's most recent closed window, with no recording involved. `windows`
counts the windows the mixer has closed since it started, so a silent mix
reads differently from a mixer that is not running.
- `audio.peakSince(window) -> number?` — the loudest peak the master mix
reached across the windows that closed after `audio.levels().windows` stood
at `window`. `levels()` carries the window that closed last, so a reader sees
the windows its own frames land on; this spans all of them, which is what
measuring a sound shorter than the gap between two reads takes. `nil` when
the meter holds no peak for the span — nothing has closed since `window`, or
it reaches further back than the meter's history of recent windows.
- `audio.listener() -> AudioListenerState` — where the scene is heard from, and
how many active listeners exist.
- `audio.voiceAccounting() -> AudioVoiceAccounting` — voice capacity, in use
and free read off the mixer's own tracks, so `free` is what the next play
call is granted or refused against. The mixer keeps two pools and each is
reported apart: `capacity` / `inUse` / `free` are the main track, carrying
the NON-spatial voices, while a spatial voice plays through its own
sub-track and is counted by `spatialCapacity` / `spatialInUse`.
`sourcesHolding` counts both pools from the sources that own them, so it
equals `inUse + spatialInUse` while every voice the mixer carries answers
to a source — and a mixer carrying voices no source reaches is the
difference between those numbers.
- `audio.profile() -> AudioProfile` / `audio.resetProfile()` — what the audio
subsystem costs: the streaming pump, clip decode and encode, voice starts, and
building the observation. Every total is a sum across a window rather than a
per-frame figure: the window runs from the last `resetProfile` — or from
engine start when nothing has reset it — and its length comes back as
`windowMs` and `frames`. Reset, let frames pass, then divide a total by
`frames` for what a frame costs.
The same document is served at `/runtime/active_audio`, with one file per source
under `/runtime/active_audio/voices/<entity>`, as the audio systems published it
after the last frame; `audio.observe()` leaves out the voices of entities a
script has despawned since. It answers in edit mode as well as play mode.
## Setting what the mix is heard at
Every voice names a channel — the `Audio` component's `channel` field, `"sfx"`
unless the source says otherwise — and is heard at its own `volume` scaled by
the level of that channel and by the master level of the mix. Both levels reach
voices that are already playing, so a settings-screen slider is heard as it
moves, and both come back per voice as `gain.channel` and `gain.master`.
- `audio.mixer() -> AudioMixerLevels` — `{ master, muted, channels }`. A
channel absent from `channels` has had no level set and plays at unity, so a
scene that invented its own channel names is heard exactly as authored until
something turns one of them down.
- `audio.setChannelVolume(channel, volume)` — set one channel's level. Scales
every voice on that channel and nothing else.
- `audio.setMasterVolume(volume)` — set the level of the whole mix.
- `audio.setMuted(muted)` — silence the mix whatever the levels read; unmuting
hands them back untouched.
```luau
audio.setChannelVolume("music", 0.3) -- music at 30%, sfx untouched
audio.setMasterVolume(0.8)
audio.setMuted(true) -- every voice reports masterSilent
```
## Playing sound a script synthesizes
`audio.stream(entity, options?) -> AudioStream?, err?` opens a PCM stream and
plays it through the entity's voice: an `ecs.AudioSource` naming the stream in
its `stream` field, so placement, distance attenuation, Doppler, pitch, value
bindings and the mixer's levels apply to it as to any source. `options` shapes
the PCM (`sampleRate` 4000 to 192000 Hz, default the mixer's rate; `channels` 1
or 2; `format` `"f32"` or `"i16"`; `latencyMs`, default 100; `bufferMs`) and the
voice (`volume`, `pitch`, `spatial`, `maxDistance`, `rolloff`, `doppler`,
`channel`, `sourceType`, `pitchValue`, `volumeValue`, `autoplay`).
- `stream:push(pcm, frames?) -> number?, err?` — queue interleaved samples (a
buffer or string in the stream's format, or an array of numbers); returns the
whole frames taken.
- `stream:wanted() -> number` — the frames that bring the queue up to its
target: `latencyMs`, or one and a half times the longest recent gap between
pushes when that is longer.
- `stream:status() -> AudioStreamStatus?` — `queuedFrames`, `queuedMs`,
`capacityFrames`, `targetFrames`, `producerGapMs`, `wantedFrames`, `framesPushed`,
`framesRefused`, `framesPlayed`, `underruns`, `starvedFrames`, `voice`,
`rate`; nil once closed.
- `stream:play()`, `stream:pause()`, `stream:set(settings)`, `stream:flush()`,
`stream:close()`.
The mixer reads the stream at its own rate, whatever the mixer's, and counts
each time it finds the queue empty as an underrun. The stream lives while the
entity's audio source names it: removing the source, despawning the entity,
putting another source in its place or rewriting the source's `stream` field
closes it.
## Codec functions
- `audio.encode(sourceBytes, opts?) -> bytes?, err?` — decode container
audio (ogg / mp3 / wav / flac) and re-encode it into a ZAUD payload.
- `audio.encodePcm(pcm, sampleRate, channels, opts?) -> bytes?, err?` —
encode raw interleaved f32 PCM (a `buffer` or a binary string of
little-endian f32, OR a flat number array) into a ZAUD payload.
- `audio.decode(zaud) -> pcm?, sampleRate?, channels?` — decode a ZAUD
payload to interleaved f32 PCM (`pcm` is a binary little-endian-f32 string).
- `audio.info(zaud) -> table?, err?` — read a ZAUD header:
`{ sampleRate, channels, frames, durationMs, codec, loopStart, loopEnd, packets }`.
- `audio.loopSeam(zaud) -> table?, err?` — measure what a clip's samples do
where a whole-clip loop wraps:
`{ ratio, step, meanStep, maxStep, channel, seamless, threshold, channels }`.
- `audio.peaks(zaud, buckets) -> { number }?, err?` — the loudest sample in
each of `buckets` (an integer from 1 to 4096) equal spans of a clip, across
its channels, held to 1: the shape a waveform is drawn from. A span is
`frames // buckets` frames; the payload is decoded a block at a time, so the
work never holds the clip's whole PCM. A payload that is not a clip, or stops
short, answers `(nil, err)`.
Every sample an encode is handed must be a finite number. A NaN or an infinity
carries no signal, and both codecs turn one into a payload whose header reads as
a healthy clip and whose samples sound as nothing — so `audio.encode` and
`audio.encodePcm` return `(nil, err)` naming how many samples fail and where the
first one sits, and `audio.info` reads a PCM payload's samples the same way and
answers for what the payload carries rather than for what its header claims.
That makes a divergent filter, a `0/0`, or a `math.log(0)` in a bake visible at
the call that would otherwise have written it.
```lua
local zaud, err = audio.encodePcm(samples, 22050, 1, { codec = "pcm" })
if not zaud then
print(err) -- "…: 3 of 176400 samples are not finite, first at index 88214"
end
```
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, and a bed whose head does not
meet its tail ticks for as long as it plays. `audio.loopSeam` is the engine's
reading of that join: the step the wrap makes (`|x[1] - x[frames]|`) against
the step the signal ordinarily makes between neighbouring samples, as
`ratio = step / meanStep`. Reading it as a ratio puts the figure 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 judged the same
way. 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. `seamless` is `ratio <= threshold`, and `threshold` is
the ratio `asset.create("soundClip", ...)` warns past.
```lua
local seam = audio.loopSeam(clipRef:getBytes())
print(seam.ratio, seam.seamless, seam.threshold) -- 41.0 false 8
-- `ratio` is the worst channel's; `channel` names it and `channels` carries
-- each one's own { ratio, step, meanStep, maxStep }.
print(seam.channel, seam.channels[seam.channel].step)
```
The reading is taken on the DECODED samples, 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 and whose source buffer nobody holds. That
costs a decode of the whole payload — `audio.info` reads a header without one.
A clip is counted in frames — `channels` samples that sound together — and a
header's `frames * channels` is the sample count `audio.decode` hands back. So
the buffer `audio.encodePcm` takes is a whole number of frames, and one whose
length leaves a tail over comes back as `(nil, err)` naming the whole frames it
holds and the samples past them.
```lua
local zaud, err = audio.encodePcm(fiveSamples, 22050, 2, { codec = "pcm" })
if not zaud then
print(err) -- "…: 5 samples is not a whole number of 2-channel frames — 2 whole frames and 1 left over"
end
```
A byte payload carries a sample per 4-byte lane, so `audio.encodePcm` takes the
`buffer` `microphone.samples()` hands back and the string `audio.decode` returns
as they are, and recording a capture into a clip is those two calls:
```lua
local status = microphone.status()
local zaud = audio.encodePcm(microphone.samples(), status.sampleRate, 1)
```
A byte length that stops partway through a lane describes a sample the caller
holds only part of, and comes back as `(nil, err)` naming the whole samples it
holds and the bytes past them:
```lua
local zaud, err = audio.encodePcm(twentySevenBytes, 22050, 1, { codec = "pcm" })
if not zaud then
print(err) -- "…: 27 bytes is not a whole number of f32 samples — 6 whole samples and 3 bytes left over"
end
```
`opts` (all optional): `codec` (`"opus"` default / `"pcm"`), `bitrateKbps`
(default 96), `vbr` (default true), `sampleRate` (resample target, default
0 = keep source), `forceMono` (default false), `loopStart` / `loopEnd`
(frame indices, default 0). Pure CPU — runs on native, WASM, and headless.
# entity
The `entity` global: spawning, despawning, finding, and the reference you get
back when you call it.
`entity` is a table you can also call. `entity.spawn(...)` and its siblings act
on the scene; `entity(id)` hands back an **entityRef** — the per-entity surface
carrying `.position`, `.component`, `:despawn()` and the rest.
```luau
local id = entity.spawn("Crate")
local e = entity(id)
e.position = { 0, 1, 0 }
e.component.add("Model", { mesh = "@builtin::meshes.cube" })
```
## What lives here
| File | What it is |
|------|-----------|
| `init.luau` | The `entity` global — typed wrappers over the Internal `__entity` namespace, plus the coercions and `entity.hierarchy`. |
| `members.module/` | The entityRef's member set: every member's kind, type and description, in one table. |
| `ref.module/` | The entityRef metatable — what `entity(id)` returns and how a member access dispatches. |
## Where the entityRef's surface is defined
`members.module` is the single description of it. The runtime's accepted-member
set derives from that table, the LSP's `entityRef` type is generated from it,
and each member's documentation is published from it. Nothing describes the
entityRef anywhere else — a second description could only drift from this one.
To add a member: declare it in `members.module` with its `kind`, `type` and
`doc`, and implement it in `ref.module`. A member missing from the table is
refused by the runtime; a member in the table with no implementation answers
nil.
## Related
- `entity.hierarchy` — swap a blockout entity for a generated asset.
- `ecs.*` — the ECS storage surface. **ECS components are not script
components**; `entity(id).component` is the script-component surface and the
two are separate systems.
# reflections system
Screen-space reflections — a polished floor reflects what stands on it, wet
ground reflects what is above it, and metal picks up its surroundings, all from
geometry the camera can already see.
Environment reflections describe a surface's surroundings in general. They
cannot show the character walking across the floor, because that character is
not in the environment — it arrived this frame. Screen-space reflections read
the frame the engine has just drawn, so anything visible can appear in anything
reflective, with nothing authored per surface.
What that buys and what it costs are the same thing: only what is **on screen**
can be reflected. A reflection of something behind the camera, or off the edge
of the frame, is not there to find. So reflections fade out toward the screen
edge rather than cutting off, and where a ray finds nothing the surface keeps
the shading it already had.
## Using it
Reflections are a render feature. List it on the scene's `RenderFeatures`
entity with the settings it should run under, and it persists with the scene:
```lua
local id = entity.spawn("render features").id
entity(id).component.add("RenderFeatures", {
features = {
{ feature = "@builtin::systems.reflections.ssr", settings = {
intensity = 1.0, -- how much of the reflection reaches the image
maxDistance = 40, -- how far a reflection ray travels, world units
quality = "auto", -- low | medium | high | ultra, or auto (the device's tier)
} },
},
})
```
Every setting is live: edit one in the inspector and the reflections follow.
`renderer.feature.schema("@builtin::systems.reflections.ssr")` lists every knob
with its default.
For code that adjusts reflections at runtime — a quality slider, a cutscene,
weather turning pavement wet — the module is the hand on the same knobs:
```lua
local ssr = require("@builtin::systems.reflections.ssr")
ssr.set({ intensity = 0.6, quality = "medium" }) -- any subset; the rest is kept
ssr.get() -- the settings in force
ssr.active() -- are the passes running
ssr.clear() -- the passes down
```
`set` brings the feature up when none is live, and an `intensity` of 0 takes
it down; the same feature is found rather than stacked when `RenderFeatures`
already runs it.
## What the knobs do
| field | effect |
|---|---|
| `intensity` | How much of the reflection reaches the image, in [0, 1]. 0 turns reflections off and releases the passes. |
| `maxDistance` | How far a reflection ray travels, in world units. |
| `thickness` | How thick a surface is assumed to be, in world units. A ray passing behind one by more than this went past it rather than onto it. |
| `roughnessCutoff` | Perceptual roughness up to which a surface takes the full screen-space reflection. Above it the reflection hands over to the probes and the sky, and is gone 0.1 higher. |
| `quality` | `low` / `medium` / `high` / `ultra` — how many steps the march spends and how many neighbouring rays a pixel gathers — or `auto` (the default), which follows the device's quality tier (`renderer.qualityTier()`): `high` on a desktop, `medium` on a handheld and at the medium tier, `low` at the low tier. `ssr.drawn()` reports the level in force and the sampling it spends. |
| `edgeFade` | How far from the edge of the screen reflections fade out, in UV. |
`roughnessCutoff` is the one to understand first. Every pixel traces one ray
drawn from the lobe its roughness describes, and gathers the rays of its
neighbours that stand on the same surface, so a rough floor shows a bright
sign as the soft, stretched streak its lobe spreads the sign into, and a
mirror shows it sharp. Up to the cutoff a surface takes the full screen-space
reflection. Above it the reflection hands over to the probes and the sky, and
it is gone 0.1 higher, so the hand-over has a soft edge in place of a line. The
default, 0.75, covers wet asphalt and polished stone. A scene that states a
lower cutoff (0.4 was the old default) leaves those surfaces to the probes.
Where the screen holds only part of a surface's lobe (the lobe reaches off the
edge of the frame, or behind the camera) the reflection covers the part it
found and the probe or sky fills the rest.
`maxDistance` and `quality` trade against each other: quality sets the step
count, so a long distance at a low quality samples coarsely and reflections
thin out at range. They thin rather than disappear because the hit refinement
adapts to the step size on its own.
How much of a reflection shows through is the surface's own Fresnel term, taken
from the G-buffer's metallic. Metal takes nearly all of it; a dielectric floor
takes a few percent head-on and much more at a grazing angle — which is why a
wet road reads dry underfoot and mirror-like down the street.
## How it renders
`ssr.renderFeature` runs two compute passes at the `afterDepthPrepass` seam,
before anything shades. `ssr_trace` draws one ray per pixel from the pixel's
GGX lobe (a visible-normal sample; a mirror, below roughness 0.1, keeps its
one reflection ray) and marches it against this frame's depth. The surface's
normal and roughness come from the G-buffer as the previous frame left them,
reprojected through the previous view-projection. The pass writes where each
ray hit and how confident the hit is, or the direction it travelled when it
found nothing. A rough pixel's ray marches fewer steps, because the next pass
blurs what the rays find.
`ssr_resolve` gathers each pixel's lobe over its own ray and the rays of up to
twelve neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`),
weighing every ray against the pixel's own lobe and counting a neighbour only
where it shows the same surface. The light at a hit is read from the colour
the previous frame ended with, where the hit stood then. The resolve
accumulates the result over frames in a history target (one image pair per
view), holds that history to the spread of the rays it gathered, and writes the
scene's reflection channel, `@scene.reflection`: the light of the rays that
found something on screen, and the share of the lobe those rays cover.
A material reads that channel the same frame, at its own pixel, inside its
environment term: it mixes the traced light over the probe and the sky by the
share of the lobe the screen answered, so what the screen did not find comes
from the environment, and the material's Fresnel, roughness and tint weigh the
result into the pixel as they weigh any environment. The reflection stands
where the camera is now; only the light in it is a frame old. The `reflection`
capture pass shows it. Where the trace found nothing the channel holds zero and
the material reflects its environment alone.
A blended material (a `blend` other than `opaque` or `cutout`) reads none of
the channel. It draws over the depth the trace ran against, so the channel at
its pixel holds the reflection traced for the opaque surface behind it. A
blended pane of glass reflects its environment, or the reflection its shader
traces for itself through `@builtin::shaderModules.screenReflection`.
A camera drawing a diagnostic pass holds readings in its colour target rather
than light, so the passes have no light to read from that frame: such a frame
is drawn lit first, unpresented, the passes run for that, and the diagnostic
reads the channel gathered for where the camera stands now. A capture drawn
once, or a camera drawn again from a new station, is drawn lit first for the
same reason, so its first frame holds a reflection (without accumulated
history, so it shows more grain than a continuously drawn view). The march
steps uniformly in screen space and compares in world space; the full account,
including why thickness is tested after refinement rather than during the
march, is in the render feature's own readme.
Each view that draws the feature holds three screen-sized images of its own: the
rays and the history pair, about 50 MB at 1080p for the viewport.
The pass takes its camera from `@frame.camera`, so reflections are correct in
offscreen captures and render-to-texture cameras, not only the live viewport.
## The demo scene
The scene `@builtin::systems.reflections.demo.polished_floor`, loaded with the `scene.load` tool, is a polished
stone floor with three coloured pillars standing on it, under an afternoon
sky, with the feature listed on the scene's `render_features` entity. The
floor reflects the pillars and a player walking across it; delete the entity
and it mirrors the sky alone. `demo/polished_floor.scene/build.luau` is the
whole scene as code, materials included.
## Files
```
reflections.package/
ssr.renderFeature/ -- the trace and resolve passes, and the settings they take
ssr_trace.computeShader/ -- draws and marches one lobe-sampled ray per pixel
ssr_resolve.computeShader/ -- gathers each pixel's lobe, accumulates, writes the reflection channel
ssr.module/ -- ssr.set / .get / .clear / .active, the runtime hand on them
ScreenSpaceReflections.component/ -- the older one-feature component; RenderFeatures is the list
demo/polished_floor.scene/ -- the showcase: a polished floor, three pillars, the feature on one entity
```
# volumetrics
Volumetric (3D-texture) rendering, end to end, in one package. Built
entirely on the engine's generic `compute.*` GPU primitives — no
Rust changes are needed to author new volumetric content.
## Layout
| Asset | Identity | Role |
|---|---|---|
| `Volume.component` | `@builtin::systems.volumetrics.Volume` | Attach a 3D voxel texture to an entity; stands it in the scene through the entity's transform AABB, hidden by what stands in front of it. |
| `VolumetricSky.component` | `@builtin::systems.volumetrics.VolumetricSky` | Clouds in the sky: one per scene, the procedural cloud layer lit by the scene's sun (through the physical atmosphere's air and sky when a `PhysicalAtmosphere` stands in the scene), drawn by `volumetricSky.renderFeature` with no composite authored. |
| `VolumetricLighting.component` | `@builtin::systems.volumetrics.VolumetricLighting` | Light shafts, god rays and glowing air: light scattering between the camera and the scene, drawn by `lightScattering.renderFeature`. |
| `ParticipatingMedium.component` | `@builtin::systems.volumetrics.ParticipatingMedium` | Mark an entity as fog/smoke/dust the camera sees through and that shades the sun on what is under it. |
| `Smoke.component` | `@builtin::systems.volumetrics.Smoke` | Smoke rising from the entity's position: a chimney's column, steam, a smoulder, a black column over a big fire, smoke signals; lit by the scene with a shadow of its own. |
| `Fire.component` | `@builtin::systems.volumetrics.Fire` | Fire with its smoke at the entity's position: a campfire, a torch, a bonfire, a building on fire, an explosion's fireball; flames glow along a blackbody ramp and a flickering point light halfway up them lights the surroundings. |
| `plume.module` | `@builtin::systems.volumetrics.plume` | The smoke and fire plumes `Smoke` and `Fire` hold, from a script: styles, sizes, quality levels; fills a volume each drawn frame and stands it with `Volume:draw`. |
| `mediaTransmittance.module` | `@builtin::systems.volumetrics.mediaTransmittance` | The registry of media and the settings every media pass reads. |
| `mediaShadow.renderFeature` | `@builtin::systems.volumetrics.mediaShadow` | Writes the sun the media take to `@scene.sunOcclusion` and marches each view ray through the media. |
| `volume.module` | `@builtin::systems.volumetrics.volume` | Builders (`noise`/`sphere`/`box`/`wrap`) + the `.zvol` header reader + occupancy + brick paging + the per-entity raymarch dispatch + the draws standing in the scene (`Volume:draw`). |
| `volume.renderFeature` | `@builtin::systems.volumetrics.volume` | Runs every standing draw's march and composite for each view the frame draws, against its camera and depth. |
| `VolumeSequence.component` | `@builtin::systems.volumetrics.VolumeSequence` | Play an open volume sequence through an entity's transform AABB. |
| `volumeSequence.module` | `@builtin::systems.volumetrics.volumeSequence` | A run of `.zvol` frames streamed through a fixed ring of resident volumes. |
| `volumeDemos.module` | `@builtin::systems.volumetrics.volumeDemos` | Shared pipeline for the showcase scenes (fill + emissive raymarch + composite). |
| `volumetricSky.module` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer: tiling noise, weather map, raymarch, TAA and composite orchestration. |
| `volumetricSky.renderFeature` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer's passes for every view the frame draws, brought up by `VolumetricSky`. |
| `volumetricLighting.module` | `@builtin::systems.volumetrics.volumetricLighting` | The light-scattering settings, set from code. |
| `lightScattering.renderFeature` | `@builtin::systems.volumetrics.lightScattering` | The light-scattering passes, brought up by `VolumetricLighting`. |
| `shaders/*` | `@builtin::systems.volumetrics.shaders.*` | Compute shaders `volume_raymarch`, `volume_draw`, `plume_fill`, `volume_pages`, `volume_pack`, `cloud_noise`, `cloud_weather`, `cloud_raymarch`, `cloud_taa`, `cloud_layer_surfaces`; shaders `volume_draw_composite`, `cloud_layer_composite`, `cloud_layer_blit`, `cloud_sky_composite`; shader modules `volume_march`, `cloud_light`, `cloud_surface`, `cloud_shell`. |
| `importers/vdb_to_zvol.importer` | (auto-discovered) | `.vdb` → dense `.zvol` via the `openvdb` WASM plugin (procedural fallback when the plugin isn't loaded). |
| `presets/cumulus_default.preset` | `@builtin::systems.volumetrics.cumulus_default` | Canonical full `VolumetricSky` weather preset. |
| `demo/*.scene` | `@builtin::systems.volumetrics.demo.*` | `sdf_solids`, `smoke_plume`, `nebula`, `godrays`, `zvol_viewer`, `sky`, `showcase`, with their fill shaders. |
The guide `systems/volumetrics/documentation/README` (`guides { path = ... }`)
names the component for each effect, clouds, fog, light shafts, a fog or smoke
volume and the sky, with what each does and costs.
## Path convention — fully-qualified builtin identities
Every intra-package reference uses the asset's fully-qualified builtin
identity, the same convention every other builtin package follows:
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
local V = require("@builtin::systems.volumetrics.volumeDemos")
-- shader identities, e.g. asset.resolve("@builtin::systems.volumetrics.shaders.volume_raymarch")
```
Qualified identities are caller-independent: they resolve identically
from a module, a scene entrypoint, or a component. Caller-relative
(`.sibling`) requires are deliberately avoided here because the
component runtime caller identity is `@builtin::components.<Name>`, so a
`.sibling` require from a component resolves against the wrong root.
(An earlier revision of this package used a `~volumetrics` package-root
alias for relocatability; that alias is not resolvable on current main,
so the package uses qualified identities throughout.)
## Usage
```luau
-- Per-entity volume. The component resolves the name through `Volume.get`,
-- so a volume paged into a brick pool renders from the pool under the same
-- name:
local Volume = require("@builtin::systems.volumetrics.volume")
local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 })
cloud:buildSparse({ brickSize = 8 })
cloud:releaseDense()
entity(id).component.add("Volume", { volumeName = "cloud", density = 6.0 })
-- Procedural sky:
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
-- VDB import: drop a `.vdb` into the VFS; the importer writes a `.zvol`
-- alongside it. Load it with the zvol_viewer demo scene.
-- Animated run: one `.zvol` per frame, played through a bounded ring.
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
Seq.open({ name = "plume", frames = framePaths, resident = 3, fps = 24 })
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
## Plugin dependency
The VDB importer delegates real OpenVDB parsing to the `openvdb` plugin
in the builtin library, `@builtin::plugins.openvdb`. Without the plugin
the importer falls back to a deterministic procedural torus so the
pipeline stays functional.
# scene_starter
The files a new scene is started from, read out of a starter scene folder
(`@builtin::scenes.starter_*`). `scene.create { template = ... }` copies a
starter into a new scene of a world with it, and a new world's startup scene is
copied from a starter the same way.
A copy takes every file of the starter except its `.meta` sidecars, so the new
scene gets an identity of its own where it is written. It takes the baked
`scene.json` with the `.build.state` that records the build script it was baked
from, so the new scene opens as the starter does without running its build.
`README.md` and `entrypoint.luau` carry the new scene's name where the starter
leaves a `[scene_name]` slot, and the copied `scene.json` records the document it
holds as the scene's initial generated baseline (`authoring.initialGenerated`,
as a scene `asset.create` makes carries), so the first authoring save reads the
entities the starter's build placed as that build's own.
```luau
local Starter = require("@builtin::modules.scene_starter")
local source = "/zero/source/libs/@builtin/scenes/starter_clearing.scene"
for _, rel in Starter.paths(source) do
vfs.write("/source/scenes/camp.scene/" .. rel, Starter.bytes(source, rel, "camp"))
end
```
- `paths(sourcePath)`: the files a copy takes, relative to the starter folder,
sorted.
- `bytes(sourcePath, rel, sceneName)`: one file's bytes as the new scene holds
it, or nil when it cannot be read.
- `sceneName(destPath)`: the scene name a `<name>.scene` folder path holds.
# channel Module
Public Luau surface over the `__channel` Internal FFI namespace —
keyframe-channel sampling primitives.
## Purpose
Wrap the raw `__channel.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.channel` via the prelude. Channels are the
keyframe-track substrate: one per animation curve (translation x,
rotation, blend weight, …). Sampling writes the interpolated
value(s) into a buffer at a specified offset — no per-sample
allocation, no per-bone FFI round-trip.
## Usage
```luau
local h = channel.create({
times = { 0.0, 0.5, 1.0 },
values = { 0, 1, 0, 1, 1, 0, 0, 0, 1 },
stride = 3,
interp = "linear",
})
channel.sampleInto(h, 0.25, buf, 0)
channel.sampleManyInto(h, 0.25, buf, { 0, 9, 18 })
local x, y, z = channel.sampleVec3(h, 0.25)
channel.destroy(h)
```
## Exports
- `channel.create(opts) -> number?`
- `channel.destroy(handle) -> boolean`
- `channel.sampleInto(ch, time, buf, offset) -> boolean`
- `channel.sampleManyInto(ch, time, buf, offsets) -> boolean`
- `channel.sampleVec3(ch, time) -> (x, y, z) | nil`
- `channel.sampleQuat(ch, time) -> (x, y, z, w) | nil`
# icons
Phosphor icon constants. The phosphor font is registered as a named
family `phosphor` in the engine, so render icons by setting
`style.fontFamily = "phosphor"` on the label that contains them.
The font is ALSO appended to the proportional family as a fallback, but
the fallback path is unreliable for PUA codepoints in egui 0.34 (see
issue #2191) — always pass `fontFamily = "phosphor"` for icons.
Curated set covering DAW transport, media controls, file management,
desktop shell, editor chrome, and common state indicators. For icons
not listed here, see https://phosphoricons.com — pass the codepoint as
a UTF-8 string literal directly.
## Exports
- `Icon.styled(extra: LabelOpts?) -> LabelOpts` — build a `UI.label` opts table with `style.fontFamily = "phosphor"` applied. Merges with the supplied `extra`.
- `Icon.<Name>: string` — UTF-8 codepoint constants. Categories:
- Transport / media: `Play`, `Pause`, `Stop`, `Record`, `FastForward`, `Rewind`, `SkipForward`, `SkipBack`, `Repeat`, `Shuffle`.
- Audio / DAW: `Microphone`, `Headphones`, `Equalizer`, `Sliders`, `Metronome`, `MusicNote`, `Waveform`, `SpeakerHigh`, `SpeakerLow`, `SpeakerNone`, `SpeakerSimpleHigh`, `SpeakerMuted`.
- File / folder: `Folder`, `FolderOpen`, `File`, `FileText`, `FileAudio`, `FileVideo`, `FileImage`, `FileCode`, `FloppyDisk`, `Trash`, `UploadSimple`, `DownloadSimple`.
- Desktop / shell: `Desktop`, `DesktopTower`, `Monitor`, `Keyboard`, `Mouse`, `House`, `Sidebar`, `Cpu`.
- Editor: `Pencil`, `Plus`, `Minus`, `Check`, `MagnifyingGlass(Plus|Minus)?`, `Gear`, `Power`, `Eye`, `EyeSlash`, `Lock`, `LockOpen`, `Bell`, `Palette`, `Funnel`, `Clipboard`.
- Code / dev: `Code`, `Terminal`, `Bug`, `GitBranch`, `GitCommit`, `GitMerge`, `Database`, `Cloud`.
- Arrows / nav: `ArrowUp/Down/Left/Right`, `ArrowsClockwise`, `ArrowsIn`, `ArrowsOut`, `CaretUp/Down/Left/Right`.
- Layout / list: `List`, `GridFour`, `DotsThree`, `DotsThreeVertical`.
- State / status: `Info`, `Warning`, `WarningCircle`, `CheckCircle`, `XCircle`, `Question`, `Heart`, `Star`, `Tag`, `Hash`, `At`.
- Shapes: `Circle`, `Square`, `Triangle`.
- Productivity / shell apps: `Calculator`, `Notepad`, `NotePencil`, `Note`.
- Games / cards: `GameController`, `Bomb`, `Cards`, `Diamond`, `Spade`, `Club`.
Types:
- `LabelStyle = { fontFamily?: string, fontSize?: number, color?: string, [string]: any }`
- `LabelOpts = { style?: LabelStyle, [string]: any }`
## Usage
```luau
local Icon = require("@builtin::modules.icons")
UI.label(Icon.Play, { style = { fontFamily = "phosphor", fontSize = 24 } })
UI.label(Icon.Folder .. " Documents", {
style = { fontFamily = "phosphor", fontSize = 14 },
})
-- Or use the helper to enforce the phosphor family:
UI.label(Icon.Play, Icon.styled({ style = { fontSize = 24, color = "#fff" } }))
```
## Notes
- The constants are plain string values — each is a single UTF-8 Private
Use Area codepoint. Concatenate freely with surrounding text.
- `Icon.styled` mutates the supplied opts table (`extra.style` is
forced). Pass a fresh table per call site if you need to reuse opts.
- Curated subset only — for icons outside this set, paste the codepoint
from https://phosphoricons.com directly.
# serviceCall
The user-scope entry point for credit-metered service calls. A `.service`
handler calls `Service.invoke(offering, endpoint, opts)` instead of touching
the `service` primitive directly, getting one `(response, err)` contract with
the HTTP status already classified.
```lua
local Service = require("modules.serviceCall")
local resp, err = Service.invoke("origozero/mesh_gen", "create_preview", {
body = { prompt = "a wooden chest" },
})
if not resp then
handle:fail(err) -- "out of credits …", "not signed in …", "unknown service …"
return
end
if resp.status >= 300 then -- upstream relayed a non-2xx (charged 0)
handle:fail("upstream " .. resp.status)
return
end
local task = resp.body -- the upstream payload
```
`Service.invoke` returns the InvokeResponse `{ status, headers, body, charged,
balance }` on a successful round-trip, or `(nil, errMsg)` when the call could
not be charged or forwarded. `Service.balance()` returns the caller's integer
credit balance.
ZeroMind injects the provider secret and meters credits server-side; the
platform JWT and the real upstream URL are never visible to this script.
# numberSequence
Roblox-shaped scalar keyframe-curve value type. A `NumberSequence` is
an immutable curve of up to 64 keypoints, each carrying
`(time, value, envelope)`. The envelope is a per-keypoint random
range half-width applied at `:sample(t)` time; `:evaluate(t)` is
always deterministic.
Exposed as the `NumberSequence` Luau global via `--!global`. Authored
scripts call `NumberSequence.new(...)` directly without a `require`.
The Rust FFI lives at `__sequences.*` (registered by
`crates/zero_scripting/src/ffi/bindings/curves.rs`); this module is
the typed Luau wrapper.
## Exports
- `NumberSequence.new(...) -> NumberSequenceObj` — three signatures:
- `NumberSequence.new(v)` — constant value across `[0, 1]`.
- `NumberSequence.new(v0, v1)` — two-point lerp from `v0` to `v1`.
- `NumberSequence.new({ { time, value, envelope? }, ... })` —
explicit keypoints. `envelope` defaults to `0`. First key must
anchor at `time = 0`, last at `time = 1`. NaN / Inf rejected.
- `NumberSequence.deserialize(payload) -> NumberSequenceObj` —
rebuild from a `{ kind = "NumberSequence", keypoints = {...} }`
payload produced by `:serialize()`.
## Methods (called via `:`)
- `seq:evaluate(t) -> number` — deterministic linear interpolation at
`t`. `t` clamps to `[0, 1]`; NaN coerces to `0`.
- `seq:sample(t) -> number` — `evaluate(t) + (math.random() − 0.5)·2·envelope(t)`.
Per-VM `math.randomseed` controls jitter reproducibility.
- `seq:keypoints() -> { NumberKeypoint }` — array snapshot, sorted
ascending by time.
- `seq:duration() -> number` — always `1.0` for a well-formed
sequence.
- `seq:serialize() -> { kind, keypoints }` — scene-save payload.
- `seq:destroy()` — drop the FFI handle. Luau removed `__gc` on
tables, so eager cleanup is the caller's responsibility for
per-frame-rebuild patterns; otherwise the entry dies with the VM.
## Substrate
Backed by `zero_curves::Channel` (Linear interp). Each sequence
builds the value and envelope channels once at construct time and
reaches into them on every sample — zero per-call allocation, safe
for hot particle loops. Validation errors name the specific rule
(`"first keypoint must anchor at time = 0"`,
`"too many keypoints (max 64)"`, …).
Foundation for VFX property-over-lifetime: declarative particles
(#2572), GPU emitter (#873), beams, trails. Issue: #2673.
# material_remap
Canonical property/texture-role dictionary used when a material **swaps
shaders**. The new shader exposes a different vocabulary than the old one —
one shader's `MAIN_TEX` is another's `albedo` is a third's
`base_color_texture` — so values would be lost on a naive swap. This module
maps any known alias onto a canonical **role** so floats, colors, and texture
links carry across the swap to the best of our ability.
Consumed by `material.assetType`'s `setShader` ref method (and, transitively,
by the `appearance` toolbox's `swapShader`).
## API
```luau
local remap = require("modules.material_remap")
remap.propertyRole("MAIN_COLOR") -- "base_color" (scalar/color side)
remap.textureRole("MAIN_TEX") -- "base_color_texture" (texture side)
-- Remap current property values onto the new shader's accepted names.
local mapped, carried, dropped =
remap.remapProperties(currentProps, shaderRef:getProperties())
-- Canonicalize texture slot names so links bind on the new shader.
local texMapped, texCarried = remap.canonicalizeTextures(currentTextures)
```
## Why two tables
`albedo` as a **color** is the base-color factor; `albedo` as a **texture** is
the base-color map. `mat.yaml` keeps `colors:` / `floats:` separate from
`textures:`, so the caller always knows which side it's remapping. Splitting
`PROPERTY_ROLES` from `TEXTURE_ROLES` removes the ambiguity instead of guessing
from the value shape.
## Property remap vs texture remap
- **Properties** are remapped against the target shader's *real* reflected
field names (`shaderRef:getProperties()`, naga reflection). Direct name match
wins; otherwise role-to-role. Properties the new shader doesn't expose are
dropped.
- **Textures** are canonicalized to the engine's builtin on-disk slot
convention (`base_color_texture`, `normal_texture`, …) because the engine
does not yet surface a target shader's reflected texture-slot list to Luau.
Unknown slots pass through unchanged.
The alias lists are deliberately broad (glTF / Unity / Unreal / Godot /
hand-rolled WGSL conventions). Add new aliases here rather than special-casing
a shader at a call site.
# viewport_select
Turns a viewport pointer gesture into an editor selection change, applying the
standard modifier semantics, and drives the per-frame bridge that reads real
pointer + modifier input. Selection is written into the shared
`modules.api.editor.selection` service's `entity` scope, so the viewport, the
selection outline, and the outliner stay in lockstep.
A left press+release within a few pixels is a click-select; a larger left drag
is a **marquee** (rubber-band) that selects every entity whose screen position
falls inside the band. The band is drawn by `modules.api.editor.marquee_overlay`.
## Exports
- `M.applyClick(Sel, scope, hitId, mods)` — pure decision: `hitId == nil` clears
(unless a modifier is held); ctrl toggles the hit; shift adds it; neither
replaces. Entity ids become `{ kind = "entity", id }` refs.
- `M.applyMarquee(Sel, scope, ids, mods)` — pure decision for a completed
marquee: an empty band with no modifier clears, an empty band with a modifier
leaves the selection unchanged; ctrl toggles each id, shift adds the set,
neither replaces with the set.
- `M.worldToScreen(m, w, h, p)` — project a world point through a 16-float
column-major view-projection matrix and viewport size to viewport pixels
(`sx, sy`), or nil when the point is at/behind the camera. Mirrors the
engine's own `world_to_screen_px`.
- `M.pointInRect(rect, sx, sy)` — inclusive screen-rect hit test.
- `M.nearestIcon(cands, cx, cy, thresholdPx)` — the nearest icon candidate
`{ id, sx, sy }` to the cursor within a pixel threshold, or nil.
- `M.entitiesInRect(rect)` — engine-driven: the selectable entity ids whose
world position projects inside `rect` (viewport-pixel space) this frame.
- `M.iconPick(cx, cy)` — engine-driven: the entity whose meshless icon is
nearest the cursor within `ICON_PICK_PX`, or nil.
- `M.tick(dt?)` — call once per editor frame; prunes dead selection refs, reads
pointer press/drag/release + modifiers, and routes a click or a marquee
through the pure decisions above.
## Notes
- The decision functions are pure so they can be unit-tested against the real
selection service.
- **Icon-pick fallback.** A click that hits no mesh/collider (the engine pointer
pick returns nil) falls back to selecting the nearest meshless-entity icon
(light / camera / audio source / reflection probe) within `ICON_PICK_PX`, so
lights and cameras — invisible to the raycast — are selectable by their
billboard. The engine pointer pick wins whenever it hits.
- **Gizmo precedence.** A marquee only starts on a frame where the pointer has
moved past the click slop AND the transform gizmo is not dragging. `tick` runs
before the gizmo's tick in the editor entrypoint, so by the time a drag passes
the slop the gizmo has already had a frame to claim a grabbed handle.
# highlight
Syntax-highlighting dispatch + per-language modules. Each language
module exports `(text: string) -> { Segment }` where
`Segment = { text, color, monospace?, italic? }`. `Z.codeEditor` calls
into `dispatch` at update time and passes the resulting segments to
TextInput, which builds the egui LayoutJob in pure Luau. Library authors
can ship their own `@author/zui_highlight_<lang>` modules and slot them
into `Z.codeEditor` via the same `language` opt.
## Exports
- `M.dispatch(language: string, text: string) -> { Segment }` — pick a per-language highlighter (with `yml` / `md` aliases) and tokenize; unknown languages fall through to a single plain segment.
- `M.lua: Highlighter` — Lua highlighter.
- `M.json: Highlighter` — JSON highlighter.
- `M.yaml: Highlighter` — YAML highlighter.
- `M.wgsl: Highlighter` — WGSL highlighter.
- `M.markdown: Highlighter` — Markdown highlighter.
Types:
- `Segment = { text: string, color: string, monospace: boolean?, italic: boolean? }`
- `Highlighter = (string) -> { Segment }`
## Usage
```luau
local Highlight = require("@builtin::modules.zui.highlight")
local segs = Highlight.dispatch("lua", source)
-- segs = { { text = "local", color = "#...", monospace = true }, ... }
-- Or call a specific language directly:
local segs2 = Highlight.json(jsonText)
```
## Notes
- Per-language colors come from the active theme's `code.*` tokens
(`ui.getToken("code.keyword")` etc.). Switching themes
(`ui.setTheme("light")`) automatically re-colors on the next call.
- A single-slot LRU cache keyed by `(language, text, theme)` makes
same-text re-emits free (focus-loss redraws, no-op editor pushes).
Cache returns a shared array reference — callers must not mutate it.
- Aliases: `"yml"` → `yaml`, `"md"` → `markdown`. Unknown languages
return a single default-colored monospace segment so user input never
crashes the dispatcher.
## Roles the Lua highlighter reads
`code.keyword`, `code.string`, `code.number`, `code.comment`, `code.bool`
(`true` / `false` / `nil`), `code.attribute` (`--!` directives),
`code.type` (a name after `:`, `->`, `::` or `type`), `code.function` (a name
a call is made through, or one `function` declares), `code.property` (a
member reached by `.` that is not called), `code.builtin` (the standard
library's globals), and `code.default` for the rest.
# material_utils
High-level wrappers around the `__material` FFI global. Convenience
helpers for the common material-authoring operations: create a named
material, apply it to an entity, query / set material properties, and
bind textures.
Exposed as the `Material` Luau global via `--!global` (auto-injected by
the prelude). Material lives ON the Model / SkinnedModel component — there
is no standalone `Material` component, because a material only renders where
there is a mesh. To apply a material, use `Material.apply()` (which errors if
the entity has no model) or set the model's `material` field directly:
`entity(id).component.add("Model", { model = "cube", material = "gold" })`.
PascalCase aliases (`Material.Create`, `Material.Apply`, etc.) are kept
for back-compat with the wider codebase — 88+ call sites across demos,
scenes, components, guides, and the engine test suite use the legacy
names. The lowercase forms are canonical.
## Exports
Canonical (lowercase) surface:
- `Material.create(name: string, opts: MaterialOpts?) -> MaterialRef?` — register a named material; returns the AssetRef envelope.
- `Material.apply(entityId: string, materialRef: MaterialRefOrName) -> boolean` — set the `material` field on the entity's Model / SkinnedModel. Errors if neither is present.
- `Material.exists(name: MaterialRefOrName) -> boolean` — registry predicate.
- `Material.getPropertyNames(name: MaterialRefOrName) -> { string }?` — list property names exposed by a material.
- `Material.getProperty(name: MaterialRefOrName, prop: string) -> any` — read a property value.
- `Material.setProperty(entityId: string, property: string, value: any)` — set a property on the material assigned to an entity's Model / SkinnedModel.
- `Material.setTexture(name: MaterialRefOrName, slot: string, textureRef: string) -> boolean` — bind a texture slot.
PascalCase back-compat aliases:
- `Material.Create(name, opts_or_shader, props?) -> MaterialRef?` — accepts the legacy `(name, shaderString, opts)` 3-arg form OR the canonical `(name, opts)` form.
- `Material.Apply` / `Material.Exists` / `Material.GetPropertyNames` / `Material.GetProperty` / `Material.SetTexture` — direct aliases for the lowercase counterparts.
- `Material.SetProperty(materialName, property, value)` — writes to the REGISTERED material by name (NOT on a component). Different from lowercase `setProperty`.
Types:
- `Color = { number } | { r: number, g: number, b: number, a?: number }`
- `Textures = { [string]: string }`
- `MaterialOpts = { shader?, color?, roughness?, metallic?, emissive?, textures?, [string]: any }`
- `MaterialRef = { __ref?, type?, name?, guid? }`
- `MaterialRefOrName = MaterialRef | string`
## Usage
```luau
local mat = Material.create("gold", {
color = { 1, 0.85, 0.2 },
metallic = 1,
roughness = 0.15,
})
-- entityId must already carry a Model / SkinnedModel (a material only
-- renders on a mesh); apply errors otherwise.
Material.apply(entityId, mat) -- AssetRef envelope
Material.apply(entityId, "gold") -- bare name also works
Material.setProperty(entityId, "roughness", 0.3)
Material.setTexture("gold", "albedo", "@builtin::textures.gold")
```
## Notes
- `Material.apply` accepts either an AssetRef envelope or a bare name —
the model's `material` field auto-wraps strings.
- Material is a field on the Model / SkinnedModel component (declared as
`material`, an `AssetRef<material>`). There is no standalone Material
component — `apply` / `setProperty` route to whichever model is present
and error when neither is.
- `Material.setProperty` writes the property on the material assigned to
the entity's model; `Material.SetProperty` writes on the REGISTERED
material by name. They behave differently — keep them straight.
- All argument validation raises on bad input rather than silently
no-oping, so call sites surface mistakes early.
# colorSequence
Roblox-shaped RGB keyframe-curve value type. A `ColorSequence` is an
immutable curve of up to 64 keypoints, each carrying
`(time, value, envelope)` where `value` is a `{r, g, b}` triple and
`envelope` is a per-channel random range half-width. The per-channel
envelope is a notable improvement over Roblox, where ColorSequence
ships with no envelope at all — a long-standing community wishlist
item.
Exposed as the `ColorSequence` Luau global via `--!global`. Authored
scripts call `ColorSequence.new(...)` directly without a `require`.
The Rust FFI lives at `__sequences.*` (registered by
`crates/zero_scripting/src/ffi/bindings/curves.rs`); this module is
the typed Luau wrapper.
## Exports
- `ColorSequence.new(...) -> ColorSequenceObj`:
- `ColorSequence.new({r, g, b})` — constant color (accepts a
3-array or `{r=, g=, b=}` record).
- `ColorSequence.new(c0, c1)` — two-point lerp from `c0` to `c1`.
- `ColorSequence.new({ keypoint, ... })` — explicit keypoints.
`envelope` may be omitted (= `{0,0,0}`), a single number
(broadcast to all channels), or a 3-array. First key must anchor
at `time = 0`, last at `time = 1`. NaN / Inf rejected.
- `ColorSequence.deserialize(payload) -> ColorSequenceObj` — rebuild
from a `{ kind = "ColorSequence", keypoints = {...} }` payload
produced by `:serialize()`.
### Keypoint shapes
An entry of a keypoint list takes any of three written shapes, and the
shapes mix within one list:
| Written | Read as |
|---|---|
| `{ time = 0.5, value = {1,0,0}, envelope = 0.05 }` | the named record |
| `{ 0.5, {1,0,0}, 0.05 }` | time, then colour, then envelope |
| `{ 1, 0, 0 }` | a bare colour, timed by its place in the list |
A bare colour takes its time from its place: the entries spread evenly
across `[0, 1]`, so `{ {1,0.85,0.35}, {1,0.35,0.05} }` is a ramp from
the first colour at `t = 0` to the second at `t = 1`, and a list of one
colour holds that colour across the whole domain.
## Methods (called via `:`)
- `seq:evaluate(t) -> (r, g, b)` — deterministic linear interpolation
at `t` (multiret). `t` clamps to `[0, 1]`; NaN coerces to `0`.
- `seq:sample(t) -> (r, g, b)` — `evaluate(t)` plus per-channel
`(math.random() − 0.5)·2·envelope(t)` jitter. Per-VM
`math.randomseed` controls jitter reproducibility.
- `seq:keypoints() -> { { time, value = {r,g,b}, envelope = {r,g,b} } }`
— array snapshot, sorted ascending by time.
- `seq:duration() -> number` — always `1.0` for a well-formed
sequence.
- `seq:serialize() -> { kind, keypoints }` — scene-save payload.
- `seq:destroy()` — drop the FFI handle. Luau removed `__gc` on
tables, so eager cleanup is the caller's responsibility for
per-frame-rebuild patterns; otherwise the entry dies with the VM.
## Substrate
Backed by `zero_curves::Channel` (Linear interp). Each sequence
builds the value and envelope channels once at construct time and
reaches into them on every sample — zero per-call allocation, safe
for hot particle loops. Validation errors name the specific rule
(`"first keypoint must anchor at time = 0"`,
`"too many keypoints (max 64)"`, …).
Foundation for VFX property-over-lifetime: declarative particles
(#2572), GPU emitter (#873), beams, trails. Issue: #2673.
# utils
Small stateless helpers used across the builtin module set: parse a
vec3-shaped value into the canonical `{ x, y, z }` map, normalise an
id list from string or table input, and coerce a checkbox-shaped value
into a strict boolean. No engine dependencies, no module state.
## Exports
- `M.parseVec3(value: Vec3Like) -> Vec3Map?` — parse vec3 from array or map form, returns `nil` if unrecognised.
- `M.normalizeIds(value: IdListInput) -> IdList?` — turn a comma/space-separated string or array into `{ string }`.
- `M.parseCheckboxValue(data: CheckboxValue, fallback: boolean) -> boolean` — coerce bool/string/number/nil to a boolean.
Types:
- `Vec3Map = { x: number, y: number, z: number }`
- `Vec3Like = Vec3Map | { number }` — accepted input shape for `parseVec3`.
- `IdList = { string }`
- `IdListInput = string | IdList` — accepted input shape for `normalizeIds`.
- `CheckboxValue = boolean | string | number | nil`
## Usage
```luau
local Utils = require("@builtin::modules.utils")
local v = Utils.parseVec3({ 1, 2, 3 }) -- { x = 1, y = 2, z = 3 }
local ids = Utils.normalizeIds("a, b, c") -- { "a", "b", "c" }
local on = Utils.parseCheckboxValue("true", false) -- true
```
## Notes
- Pure functions — no side effects, no engine calls. Safe to call at
module load time or from any context.
- `parseVec3` always returns the map form (`{ x, y, z }`) regardless of
whether the input was an array or a map. Callers downstream that
expect a particular shape should rely on the map form.
- `normalizeIds` returns the input table unchanged when it is already a
table — it does not validate that each entry is a string.
# 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. An
entry with `caller: trusted` is callable by the engine's trusted side alone:
a world script or a panel calling it is refused, and it asks for no
consent, since no person is its caller.
## 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.
- One call's arguments hold at most 16,384 values together, a table held by
several entries counted at each of them, and 64 MiB of strings and buffers.
A call past that, or one whose arguments hold a table inside itself, is
refused by name before the plugin is reached. Data larger than that goes as
a handle.
- 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 restarts it.** If the component traps, the plugin stops, the log
says so in one line, and a call raises that it stopped and why. The engine
then loads the asset again after a pause of 1 s, then 5 s, then 20 s for
each trap that follows within a minute of a start. A fourth such trap leaves
it stopped, and every call raises why, until it loads again: a new build, or
an edit to `plugin.yaml`. A plugin that runs a minute after a start has its
count cleared.
- **Its listeners hear it stop and start.** `me.on` receives
`"plugin.stopped"` with `{ reason, restarting, restartInSecs? }` when the
plugin traps, and `"plugin.started"` with `{ restarted = true, attempt }`
once it is running again. Work you were waiting on the plugin for (a running
request, a turn) ended with the trap: end it there, with the reason.
- **An engine that stops lets it finish.** When the engine is stopped (its
window closed, or a stop of the engine; in a browser, a stop the page asks
for), each plugin's `shutdown` runs and its files are closed, within 2 s in
all; on the desktop the calls in flight are given the first second of it to
finish. A plugin that trapped is not started again once the engine stops.
- **`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.
# Scene setup (asset type)
A scene setup configures a scene as a whole in one asset: its sun and ambient
light, its fog, its render features and post effects, or any other effect that
applies to a scene. It is an ordered list of **members**, each an asset whose
type implements `applicable`, with the values the setup states for them.
Placed in a scene, it applies every member; selecting the placement shows every
parameter of every member, and an edit made there is that placement's own.
## Where it lives
- Source: `<name>.sceneSetup/`
- Identity: `<name>` (the `.sceneSetup` suffix strips from the identity)
- Folder shape:
- `sceneSetup.yaml`: the definition. **Required.**
- `README.md`: what the setup puts on a scene. **Required.**
- `.metadata`: `description` and `tags`. **Required.**
- `preview.png`: its picture. Optional.
## The definition
```yaml
members:
- id: sun # required, ^[a-z][A-Za-z0-9_]*$, unique
source: "./sun.sceneLight" # any asset that implements applicable
- id: ambient
source: "./fill.sceneLight"
values: { intensity: 0.12 } # values for the member's parameters
- id: fog
source: "<a fog render feature>"
enabled: false # optional, default true
- id: grade
source: "./grade.postEffect"
values: { saturation: 0.82, contrast: 1.12 }
```
A member's `values` are the values this setup states for that member; the
member asset keeps its own, and another holder of it states its own.
A member's `source` is one of:
- an identity: `lighting.harbour_fill`, `@builtin::<library>.<name>`. It
resolves among the assets that can be members, so a name another kind of
asset also answers to reaches the member;
- a path with its type suffix: absolute (`/source/lighting/harbour_fill.sceneLight`),
from the folder holding this setup (`harbour_fill.sceneLight`,
`./harbour_fill.sceneLight`, `../shared/fill.sceneLight`), or from the
world's source folder (`lighting/harbour_fill.sceneLight`). A path starting
`./` or `../` is read from the setup's folder alone.
An identity drops the type suffix, so `harbour_dusk.sky` and
`harbour_dusk.sceneSetup` in one folder share `lighting.harbour_dusk`; a
member naming that identity is skipped as `sceneSetup.member.ambiguous`, which
names both assets, and its path names the one meant. A source that names
nothing is `sceneSetup.member.missing`, and its values and overrides are kept
until it resolves.
A member whose type does not implement `applicable` is refused by name
(`sceneSetup.member.unsupported`). A key the engine does not read is a warning.
## Parameters and paths
A setup's parameters are its members': `<member id>/<name>` (`fog/density`), a
nested member's under its path (`look/reflections/intensity`), and
`<member id>/@enabled` for every member. `@lit` (true by default) says whether
the scene renders lit; off, every surface shows its own colour with no light on
it, for a stylised game or a menu. `asset.schema(setupRef)` lists every path
with the member's own Field descriptor.
A setup that nests another names its parameters through the member id it
gives the nested setup: a setup whose member `base` is another setup has
`base/fog/density` for that setup's `fog/density`, and a placement sets
`base/fog/density`. A path that is no parameter is refused naming the paths
that end in it.
The value a member receives, for each parameter, first present wins: the
placement's override, the outermost setup's `values`, each inner setup's
`values`, the member asset's live value, then its saved value.
## Placing and tuning
```lua
-- A world's setup by its identity (`lighting/harbour_dusk.sceneSetup` is
-- `lighting.harbour_dusk`), or by its absolute path, `/source/lighting/harbour_dusk.sceneSetup`.
local root = asset.resolve("lighting.harbour_dusk", "sceneSetup"):instantiate(nil, { name = "lighting" })
local setup = root.component.get("SceneSetup")
setup:set("fog/density", 0.05) -- this placement's override
setup:set("fog/density", { scale = 3.75 }) -- relative: the setup's density times 3.75
setup:set("fog/heightFalloff", { offset = -0.06 }) -- relative: the setup's value plus -0.06
setup:set("ao/@enabled", true) -- turns a member on for this placement
setup:reset("fog/density") -- back to what the setup says
for path, m in pairs(setup:members()) do print(path, m.state.status) end
```
The placed root holds the `Asset` component (its `source` is the setup) and the
`SceneSetup` component (this placement's `overrides`); the scene stores nothing
of any member. Removing the `Asset` removes the `SceneSetup`, and every member's
application goes with it.
A relative override (`{ scale = n }` or `{ offset = n }`, numeric parameters
only) lands at the value the setup supplies times `scale` or plus `offset`,
checked against the parameter's descriptor, and follows that value: edit the
setup's fog density and every placement scaling it moves with it. It is saved
and synced like any override, and the Inspector shows it as relative.
**Where each value comes from.** `setup:get(path)` and each member's `values`
in `setup:members()` say it: `origin` is `override` (this placement's, with
`relative` and `supplied` for a relative one), `definition` (with `definedBy`,
the setup stating it, and `definedAt`, the path it states it at there, so a
value inherited through a nested setup names that setup), `live` (the member
asset's live value) or `saved`. One line proves what a placement shares:
```lua
for name, v in pairs(setup:members()["fog"].values) do print(name, v.value, v.origin, v.definedBy) end
```
**A light that follows the sky lands at what the sky makes of it.** A sun, a
fill or a rim that follows the sky (`followSky`) states its intensity as its
noon peak: the sky gives it that intensity with the sun 30° up or higher and
dims it toward the horizon, to about a third at 7° and 0 below it. So a dusk
sun stated at 3.2 at 17:51 lands near 0.4. `setup:get(path).landed` (and
`setup:set(path, value)`, which returns the same read) is what it lands at
now, beside `value`, what it states; the card shows `3.2 → lands at 0.4 at
17:51` on the row. The member's `state.notice` in `setup:members()` names a
light the sky dims to under a third of what it states, a distant fill that
lands brighter than the sun it is meant to support, and an ambient term at
half the sun or more. Raise
the stated intensity, move the hour, or, for a fill or a rim, set
`followSkyIntensity` to `false` so it keeps what it states.
**`set` in edit mode is a scene edit.** In edit mode on a world scene, a `set`
is an authored edit of the scene, recorded and saved: it holds over what
`build.luau` states until it is reset or released (`sceneAuthoring`
`releaseAuthored`). A `reset` that leaves the placement with no override
records nothing and releases the edit an earlier `set` recorded. Overrides
stated in `build.luau` are the build's own.
## Auditioning another setup
Two placements, or a placement and an application from code, each apply their
own sun, ambient term and fog; the effect decides which is in force (the
light-tie rule for lights), so an application beside a placed setup reports the
members another application holds as `held`, with `heldBy`, and its
`ApplyState.notice` names each held member, its asset and its holder. To see a
setup in place of the placed one:
- audition it on the placement, a preview for the session:
`setup:audition(asset.resolve("lighting.harbour_night", "sceneSetup"))`
applies it in the placed setup's place and records nothing;
`setup:endAudition()` (or the card's End audition, a flip, a reload) puts
the placement's own setup back. `set` and `reset` are refused while it lasts;
- apply it from code (below): it holds over the placement across flips until
it is dropped;
- read its preview: `preview.png` lights the reference subject
`@builtin::preview.subjects.lookdev` with the setup alone, its exposure fit
so a night setup reads (below);
- point the placement's `Asset` source at it (a scene edit that stays;
`releaseAuthored` returns the placement to `build.luau`'s setup);
- or apply it in a scene with no setup placed, such as a scratch scene.
## Applying it from code
A setup implements `applicable` itself, so it can be applied for an owner
like any member: `setupRef:as("applicable"):apply(owner, values)` starts an
application and `setupRef:as("applicable"):drop(owner)` ends it. Each member is
applied with the owner `"<owner>/<member id>"`.
- **It takes the effects that hold one at a time.** The scene's sun, its
ambient term, its sky and each render feature's settings are held by one
application at a time: of the applications standing, the newest to state
something holds it, so an application made over a placed setup holds them
while it stands, and the placement's members report `held` by it.
- **It stays in force until it is dropped,** across edit/play flips and device
rebuilds.
- **Its drop hands every effect back** to the application before it: the
placement's own, or the scene's own lights.
Which of two suns or two fogs is in force is the effect's own to decide; the
setup decides nothing about its members. An audition (above) is a preview for
the session that a flip ends; an application from code stands until it is dropped.
```lua
local night = asset.resolve("lighting.harbour_night", "sceneSetup")
night:as("applicable"):apply("myGame:time", {}) -- night holds over the placement
-- … flips, rebuilds …
night:as("applicable"):drop("myGame:time") -- the placement's lighting is back
```
## Checking one
`asset.validate(setupRef)` (an engine API function) reads the definition and
every value and returns `{ ok, problems }`: each diagnostic (`sceneSetup.member.missing` and the rest) with its
code, severity, path and message. A problem of severity `error` refuses a push.
## Its picture
A setup's `preview.png` shows its own lighting on a fixed reference subject,
`@builtin::preview.subjects.lookdev` (a grey ground, a white diffuse sphere, a
chrome sphere and a grey card). The preview studio stands the subject and
applies the setup to the world with the owner `preview` for the shot, so its
sun, sky and effects are the ones in force, then drops it, which hands every
effect back to the scene's own holder. A frame that reads darker than mid
grey (a night setup) is shot with its exposure opened up for the picture
alone, by up to eight stops, so the night look reads without the setup
changing. For those frames the world shows the
setup's lighting, so the picture renders only on an explicit request
(`preview.writePreview`, `assets.generatePreviews`, staging) and never from
the preview queue or a live preview; the last picture stands otherwise.
## Make one
```lua
asset.create("sceneSetup", "dusk", { members = {
{ id = "sun", source = "./sun.sceneLight" },
{ id = "ambient", source = "./fill.sceneLight", values = { intensity = 0.1 } },
} })
```
# debris
Timed entity despawn — Roblox `Debris:AddItem(instance, lifetime)`
analog. Wraps the internal `__debris.*` FFI with a typed Luau surface
and installs it as the `debris` global via the prelude.
Collapses the common `task.delay + entity.despawn` pattern into one
centrally-introspectable call. Use for transient entities — bullet
tracers, hit FX, dropped pickups, tween-completion cleanups, ragdoll
cleanup.
## API
| Call | Effect |
|---|---|
| `debris.add(id, lifetime?) -> handle` | Schedule despawn after `lifetime` seconds (default 10). Returns a cancel handle, or 0 if the id can't be resolved. Calling again on the same entity replaces the prior deadline. Negative or zero lifetime despawns immediately. |
| `debris.cancel(handleOrId) -> boolean` | Cancel a pending despawn. Accepts a handle or an entity id / name / proxy. Returns true if a record was removed. |
| `debris.pending(id) -> number?` | Seconds remaining before despawn, or nil if not scheduled. |
| `debris.list() -> { { id, remainingSecs, handle } }` | Snapshot every pending entry as a flat array. Order is not stable. |
| `debris.count() -> number` | Number of currently pending entries. |
| `entity(id):AddDebris(lifetime?)` | Entity-proxy convenience; equivalent to `debris.add(id, lifetime)`. Accepts both colon and dot call styles. |
## Semantics
- **Idempotent**: a second `add(id, lifetime)` replaces the prior
deadline. The latest call's handle is the only handle that
resolves to a live entry.
- **Despawn through any other path drops the pending record**
silently — registered at the `despawn_entity_now` chokepoint so
`entity.despawn`, parent cascade, and `world.load` reset all
clean up automatically. No "despawn(invalid)" errors.
- **Single tick per frame**: `tick(dt)` runs alongside
`task_scheduler::tick` in `world_context::post_update`. No new
Bevy schedule node.
- **Save / load round-trip**: pending entries are snapshotted into
world settings as `debris.pending` at `world.save` and restored at
`world.load`. The saved value is seconds-remaining, so timers
resume from where they paused regardless of wall-clock gap between
save and load.
## Examples
```lua
-- Bullet tracer
local bullet = entity.spawn("Bullet")
debris.add(bullet.id, 2.0)
-- Cancel before deadline
local handle = debris.add(target.id, 5)
debris.cancel(handle)
-- Entity-proxy convenience
entity.spawn("Pickup"):AddDebris(30)
-- Introspection
for _, info in debris.list() do
print(entity(info.id).name, "despawns in", info.remainingSecs)
end
```
See `docs/specs/scripting-api.md` for the canonical reference.
# debug_bounds
The "bounds" provider for `@builtin::modules.debugViz`: appends one amber
wireframe box per scene mesh's world-space AABB into the shared
debug-visualization batch, every edit-mode tick.
```lua
debugViz.registerProvider("bounds", require("@builtin::modules.debug_bounds").tick)
```
`DebugViz.component` registers this provider automatically — attach it to one
entity to draw a box around every mesh in the scene alongside whatever other
providers are registered.
## How it works
`tick(emit)` queries every entity carrying a Mesh (skipping
`debugViz.anchorId()`, the core's own hidden draw-anchor, which itself carries
an invisible Mesh), reads its `bounds()`, and appends a box via `emit.box`.
The core owns the anchor, material, buffers, and render feature that actually
draw the batch — this module only contributes geometry.
## API
- `debug_bounds.tick(emit)` — append one box per scene mesh's current
world-space AABB into the shared batch.
# range_bounds (module)
The `range` field-constraint validator. Registers itself with
`field_constraints.module`'s registry on load so any component field
carrying `constraint = { kind = "range", min = ..., max = ... }` — which
is what `Field.range` emits — is checked against it.
## What it does
Given a field's written value and its constraint:
1. Passes `nil` — a ranged field may be left unset.
2. Rejects a constraint carrying neither bound, since there is no
interval to check against.
3. Rejects a non-number value, naming the interval and the type it got.
4. Rejects a NaN or an infinity, which sits in no interval.
5. Answers whether the value is inside `constraint.min` ..
`constraint.max`, either of which may be absent to leave that side
open.
Every rejection names the interval, so the message tells the caller what
they may write instead of only what they may not.
## What a range is for
A field whose value means something only inside an interval — a
normalized amplitude, a fraction, a probability, a count that starts at
zero — declares that interval once, and every write is held to it. What
the field reads back is then a value the system consuming it can use,
and a number that lands outside is reported where it was written rather
than wherever it is eventually read.
## Where the bounds come from
`Field.range(min, max, default, mode)` validates the interval at
construction: at least one bound is required, both must be numbers when
given, `min` may not sit above `max`, and a non-nil default must be
inside. A field whose interval is wrong is therefore a load-time error
rather than a runtime surprise, and this validator only ever sees a
well-formed interval.
The engine carries `constraint` verbatim and never reads inside it, so
the bounds live entirely in Luau.
## Exports
- `M.check(value, constraint) -> ok, reason?` — the validator function,
also registered under the `range` kind.
# BlankAppLayout
The layout module for the `blank_app` scaffold. It builds a single UI screen
from the engine's raw, CSS-parity widget tree and wires up one interaction: a
`+1` button that increments a counter and re-renders.
This is the file you edit. Replace the `build` tree with your own widgets.
## The contract
A `UiPanel` component points its `source` at this module and calls
`mount(ctx)`, where `ctx = { entity, entityId, data, state? }`. `mount` returns
the handlers the panel drives each frame:
```lua
function M.mount(ctx)
local state = ctx.state or { count = 0 } -- 1. state is the source of truth
local function build() return { --[[ widget tree ]] } end
ui.registerScreen("blank_app", build()) -- 2. register the tree as a screen
return {
state = state,
update = function(dt) end, -- 3. per-frame work (no-op here)
onCallback = function(id, data) -- 4. an interaction lands here
if id == "blank:inc" then
state.count = state.count + 1
ui.updateScreen("blank_app", build()) -- mutate, then re-render
end
end,
destroy = function() ui.unregisterScreen("blank_app") end,
}
end
```
- `state` is returned so the panel hands it back on a live-reload — your count
survives an edit.
- `update(dt)` runs every frame; leave it a no-op when nothing animates.
- `onCallback(id, data)` receives every widget's callback id. Mutate state, then
call `ui.updateScreen(name, build())` to publish the new tree.
- `destroy()` unregisters the screen when the panel goes away.
## The raw widget tree
A node is a table: `{ type = "...", props = {...}, style = {...}, children = {...} }`.
- **Containers** lay out their children: `vertical` (column), `horizontal` (row).
- **Leaves** carry content: `label` (text in `props`), `button` (text + `onClick`
in `props`).
- **`props`** is the widget's data and behaviour — a label's `text`, a button's
`onClick` callback id.
- **`style`** is CSS: `padding`, `gap`, `background`, `color`, `fontSize`,
`fontWeight`, `borderRadius`, `borderWidth`, `borderColor`, `minWidth`,
`minHeight`, `boxShadow`, and the rest of the box model.
The tree is a pure function of `state`: to change what shows, rebuild the tree
and call `ui.updateScreen`. There is no retained widget object to mutate.
## Interactivity
An interactive widget carries a **string callback id** in `props` (this button's
`onClick = "blank:inc"`). When the user clicks, the engine delivers that id to
`onCallback` here. `onClick` works on any widget — a `label`, a `horizontal`
row, an `image` — not just a `button`.
Interaction runs in **play**, not edit: enter play and click the button to see
the count rise.
## Discover the surface
- The `gui` toolbox's **widgetTypes** tool lists every `type`.
- Its **widgetProps** tool lists one type's `props`.
- `@builtin::examples.ui.*` are complete CSS-parity screens (dashboard, sci-fi
HUD, RPG inventory) in this exact model — read one before building.
- The UI and styling guides cover the model and the full style surface.
# ui_observe
What the last UI frame painted, which widget owns a point, and why a widget is
not on screen.
Reached through the `ui` namespace — `ui.observe`, `ui.diagnose`, `ui.hitTest`,
`ui.pointerWidget`, `ui.paintOrder`, `ui.invisibilityReasons` — and served to a
non-Luau reader at `/zero/runtime/ui/<screen>/paint.json`.
## The reading
`ui.observe()` returns one document. Its `widgets` rows cover every widget any
registered screen's tree holds, each carrying:
| field | what it is |
|---|---|
| `parent` | the nearest ancestor in its screen's tree carrying an id |
| `rect` | the box layout gave the widget |
| `clip` | the clip it painted under — every `overflow: hidden`/`clip`/`scroll` box above it, intersected down from the viewport |
| `visible` | the part of `rect` that survived `clip` and the viewport; `w`/`h` are zero when nothing did |
| `viewport` | the region the pass that recorded it paints into: the whole window for a screen on the window, the rect a Scene panel presents the camera's picture in for a screen in that picture |
| `paintIndex` | order within the frame, so two identical rects still separate |
| `painted` | whether the pass that recorded it is the one drawing the viewport |
| `opaqueFill` | whether it filled its whole box at full alpha |
| `hovered` | whether the pointer was over it on the recorded frame |
| `reason` | its verdict, from the closed set below |
| `detail` | a sentence naming what the verdict is about |
| `occludedBy` | the widget covering it, when `reason` is `occluded` |
`generation` advances once per re-rendered frame. Two calls reporting the same
number describe the same frame.
Every rect, the document's own `viewport` (the window) and its `pointer` are in
logical points on the window, the space `ui.getLayoutInfo` and `gui.bounds`
answer in, wherever a widget's screen draws. A screen in the camera's picture
lays out on the camera's canvas (the size `ui.screenSize()` reports); while a
Scene panel presents that picture, its rects are mapped onto the window through
the panel. Times `ui.pixelRatio()` a point is in the window's physical pixels,
where `Zin.test`'s mouse primitives and the `inputSim` toolbox's `click` /
`mouseMove` with target `"ui"` place a pointer.
## The verdicts
`ui.invisibilityReasons()` lists them:
| reason | what the engine found |
|---|---|
| `painted` | it reached the frame |
| `noSuchWidget` | no registered screen's element tree carries the id |
| `hiddenByAuthor` | `props.visible = false` on it or an ancestor kept it out of the render |
| `screenNotShown` | its screen is registered and not shown |
| `neverLaidOut` | its screen is shown and the frame laid out no box |
| `zeroSize` | its own box has no area |
| `offViewport` | its box sits entirely outside the viewport of the pass that drew it (the row's `viewport`) |
| `clippedByAncestor` | an ancestor's clip removed the whole box |
| `occluded` | a later widget covered it with an opaque fill |
| `screenNotOnViewport` | its box is fine and the camera holding the viewport excludes its screen's render layer, so the frame measured it without drawing it |
The resolution reports the nearest cause among them — a widget both clipped
away and covered reports the clip — and `painted` when nothing kept the widget
out.
The camera's render-layer mask decides the screens in the camera's picture.
With no Scene panel presenting the game viewport, the window is that picture
too, and the mask decides every screen on it. While a Scene panel presents the
game viewport, the window around it is the editor's own picture: a screen
placed on the window (`ui.setScreenSpace`, and the default for a screen on
`EditorUI`) paints there whatever the camera's mask holds, and reads `painted`.
A screen placed in the camera's picture reads `screenNotOnViewport` under a
camera that excludes its layer, with or without a Scene panel.
## The pointer
`ui.hitTest(x, y)` names the widget a pointer at that point reaches and the
stack beneath it, topmost first, in logical points on the window. Where
several boxes take the point in, the one that paints last is the one that gets
it, and the containers holding them follow — nearest first, by `parent`.
`ui.pointerWidget()` reports where the pointer sat, whether the UI claimed it,
and which widget the frame reported it over.
# entity_signals
Per-entity destroy signals, surfaced on the entity proxy as
`entity(id).onDestroying` and `entity(id).onDestroyed`, plus the dispatch
the despawn pipeline calls to fire them.
```lua
local boss = entity.find("Boss")
boss.onDestroying:Connect(function()
-- runs BEFORE teardown — final state is still readable
saveBossStats(boss.component.get("Combatant").public)
end)
boss.onDestroyed:Connect(function()
log.info("boss fully cleaned up")
end)
entity.despawn(boss.id) -- onDestroying fires, then teardown, then onDestroyed
```
## Order
`onDestroying` and `onDestroyed` are `Signal`s (see `signal.module`),
created on first access. The despawn pipeline drives the order. For a
cascade rooted at one `entity.despawn(root)` call:
1. `onDestroying` fires across the whole subtree, root first — before any
component teardown, so handlers read final state.
2. components tear down (`onDestroy(self)` per component), leaves first.
3. `onDestroyed` fires per entity as it is removed, leaves first.
`onDestroying` handlers must not yield, and the entity is frozen against
reparenting / re-mutation during the destroying window.
An entity nobody observes costs nothing and fires nothing.
## Entity-keyed tables
A module that keeps per-entity state for something to read every frame (a
registry a render feature walks, a set of marked entities) declares its table
with `entityKeyed`. When an entity is despawned, by `entity.despawn`, a
parent's cascade, a scene rebuild or reload, or a mode flip, its id leaves
every such table, so the reader only ever meets entities in the world and its
cost follows them.
```lua
local EntitySignals = require("@builtin::modules.entity_signals")
local marked = EntitySignals.entityKeyed({})
function M.mark(id: string)
marked[id] = true
end
```
The table is one of the engine's own records: a module-state restore leaves it
as it stands, so an id that left it stays out.
# entity_reflect
High-level entity introspection and manipulation utilities. Wraps the
`__reflect` FFI global with a cleaner API — no per-script component
declaration needed; every method goes through the reflection layer so
it works on any entity that carries the relevant component.
Exposed as the `Entity` global via the `--!global Entity` directive.
## Exports
- `Entity.getField(entityId, component, field) -> any` / `Entity.setField(entityId, component, field, value) -> boolean` — generic reflected read/write.
- `Entity.getPosition(id) -> Vec3?` / `Entity.setPosition(id, pos)` — `Transform.position` shortcuts.
- `Entity.getRotation(id) -> Quat?` — `Transform.rotation` shortcut.
- `Entity.getScale(id) -> Vec3?` / `Entity.setScale(id, scale)` — `Transform.scale` shortcuts.
- `Entity.getName(id) -> string?` — `Name` component read.
- `Entity.isVisible(id) -> boolean` — `Visible` component read; missing component is treated as visible.
- `Entity.getComponents(id) -> { string }?` — list reflected components on this entity.
- `Entity.getSchema(componentName) -> { ComponentFieldSchema }?` — list field names + types for a component type.
- `Entity.snapshot(id) -> any` — full `{ ComponentName = { field = value, ... }, ... }` dump.
- `Entity.patch(id, component, fields) -> boolean` — multi-field update.
- `Entity.distance(idA, idB) -> number?` — straight-line distance between two entities' `Transform.position`.
- `Entity.allTypes() -> { string }` — list every registered reflectable component type.
Types:
- `Vec3 = { x: number, y: number, z: number }`
- `Quat = { x: number, y: number, z: number, w: number }`
- `ComponentFieldSchema = { name: string, type: string }`
## Usage
```luau
-- `Entity` is a global (--!global Entity); no require needed.
local pos = Entity.getPosition("player")
Entity.setPosition("player", { x = 0, y = 1, z = 0 })
local snap = Entity.snapshot("player")
Entity.patch("player", "Transform", {
position = { x = 0, y = 1, z = 0 },
scale = { x = 1, y = 1, z = 1 },
})
```
## Notes
- Every method goes through the `__reflect` FFI — `nil` returns mean the
component or field is missing, not that the entity is gone. Use
`Entity.getComponents(id)` to enumerate what's there.
- `isVisible` treats a missing `Visible` component as visible
(`v == nil` returns `true`).
- `Entity.distance` returns `nil` when either entity lacks a position;
callers should branch on `nil` before using the result.
- The `--!global Entity` directive is what makes `Entity` the global name —
the module's local `E` variable is just an implementation detail.
# field_constraints (module)
Generic field-constraint dispatch. Installs
`_G.__zero_check_field_constraint(value, constraint)`, the Luau half of
the opaque field-constraint primitive: a component field descriptor
may carry a `constraint` value (an arbitrary table with a `kind`
string), and the engine calls this hook whenever a constrained field's
default resolves or a write lands. The engine copies `constraint`
verbatim — it never reads inside it — and treats the hook's first
return as accept/reject, the second as the rejection reason.
## What it does
1. Reads `constraint.kind` and looks up a registered validator for
that kind.
2. Built-in kinds (currently `dataContract`) resolve their validator
module lazily on first use, so component registration never depends
on load order.
3. Calls the validator with `(value, constraint)` and returns its
`(ok, reason?)` result.
The registry is held in the module's durable state (`modules.state`),
so every run of this module, and the engine hook the first run
installed, read and write the one registry.
A malformed constraint (not a table, or missing `kind`) and a missing
validator both reject — the primitive fails closed rather than
silently accepting an unconstrained value.
## Exports
- `M.register(kind, fn)` — register the validator for a constraint
kind. `fn(value, constraint) -> ok, reason?`. A kind belongs to the
chunk its validator is defined in: registering it again from that
chunk (its module running again, on a hot reload or after its require
cache entry was dropped) replaces the validator, and registering it
with a validator defined in another chunk errors, naming both.
- `M.check(value, constraint) -> ok, reason?` — run the check directly
(same function installed as the engine hook).
## Consumers
`Field.dataRef` (`field.module`) emits `constraint = { kind =
"dataContract", contract = ... }`; `data_contract.module` registers
the `dataContract` validator against this registry.
# mathx Module
Public Luau surface over the `__mathx` Internal FFI namespace — batch
math kernels that operate on buffer slices.
## Purpose
Wrap the SIMD-friendly batch ops exposed by Rust (damp, lerp, slerp,
normalize, accumulate, transform) in a typed Luau table that gets
auto-injected as `_G.mathx` via the prelude. Single-value forms are
out of scope — Luau handles those at sub-µs cost and an FFI hop would
dominate.
For element-wise NumPy-style ops on typed buffers, prefer the `nx`
module; `mathx` is the slice-and-target form for specific
position / orientation / quaternion shapes.
## Usage
```luau
-- Critically-damped scalar follow
mathx.dampScalar(buf, 0, 16, 0.0, 0.16, dt)
-- Lerp every vec3 in a slice toward a target
mathx.lerpVec3(positions, 0, n, 0, 1, 0, 0.5)
-- Slerp every quat toward a target rotation
mathx.slerpQuat(rotations, 0, n, 0, 0, 0, 1, 0.25)
-- particle integration: pos += vel * dt
mathx.addScaledVec3(positions, velocities, n, dt)
-- transform vec3 positions by a 4x4 world matrix
mathx.transformVec3(positions, 0, n, worldMatrix)
```
## Exports
- `mathx.dampScalar(buf, off, count, target, smoothTime, dt)`
- `mathx.lerpVec3(buf, off, count, tx, ty, tz, t)`
- `mathx.slerpQuat(buf, off, count, tx, ty, tz, tw, t)`
- `mathx.normalizeQuat(buf, off, count)`
- `mathx.addScaledVec3(dstBuf, srcBuf, count, scale)`
- `mathx.transformVec3(buf, off, count, mat16)`
# slots
The rules of the slot family, shared by the `Slot`, `Assembly` and `Part`
components: which entities are slots and the path each answers to, which part
fills a slot under a configuration, whether a part fits a slot and why not, and
building or removing the part that fills a slot. Content reaches it through the
three components; tools that need the rules without a component require it.
## API
| Call | Returns |
|---|---|
| `Slots.holderOf(entityId)` | The `Assembly` holding the slots at the entity: the nearest one on it or above it, climbing past each one that stands on a part built into a slot. Nil when none does. |
| `Slots.holdsOwnSlots(e)` | Whether an entity carries an `Assembly` that holds its own slots (one on an entity that is no part built into a slot). |
| `Slots.pathOf(slot)` | A `Slot` component's path. |
| `Slots.nameOf(slot)` | A `Slot` component's name. |
| `Slots.discover(rootId)` | Every slot at and under an entity, `Slot` components and `Humanoid` role sockets, each `{ path, name, kind, tags, default, joint, entity, slot?, humanoid?, from }`. A descendant whose own `Assembly` holds its slots is left out, with its subtree. |
| `Slots.partRef(part)` | The AssetRef an AssetRef, identity, guid or path names, or nil and why. |
| `Slots.declaredFits(ref)` | The slot kinds a part fits and where that is declared (`Part`, `.metadata`). |
| `Slots.fits(entry, part)` | `(fits, why, ref)`. |
| `Slots.decide(config, entry)` | The guid filling a slot under a configuration, and its source. |
| `Slots.currentFill(entry)` | The entity filling a slot and its `{ path, part }` record. |
| `Slots.apply(entry, guid)` | Make a slot hold a part, rebuilding it only when it differs. |
```luau
local Slots = require("@builtin::modules.slots")
for _, s in ipairs(Slots.discover(car.id)) do print(s.path, s.kind) end
```
A fill entity carries the `slotFill` attribute: the path of the slot it fills
and the guid of the part.
# Source bindings
Captures editable inputs supplied by builders, remaps their generated output ids to persistent scene ids, and retains exact source revisions for later checked edits.
```lua
local Bindings = require("@builtin::modules.sourceBindings")
local inputs, result = Bindings.capture(function()
Bindings.attach(target) -- target from SourceEditing.bind
return "built"
end)
local registry = Bindings.pack({{owner="build",targets=inputs,placements={captured="persistent"}}})
local available = Bindings.list(registry, "persistent")
local reopened = Bindings.resolve(registry, "build", available[1].id)
```
Inside a scene build, `build.source()` returns the exact `build.luau` snapshot being evaluated, including proposed source during candidate preparation. Use it with `SourceEditing.calls` to locate editable arguments, then call `build.bindSource(target)` after creating the entities named by the target. The scene captures these registrations, maps their outputs to persistent placements, and saves the registry in `authoring/state.json` under `build.bindings`. Source files discovered through bindings join the transaction read set; a changed original input or edit record refuses the build. A tool can reopen that saved registry with `Bindings.resolve` to prepare a checked source replacement.
The registry deduplicates source versions by asset guid and stores their exact-byte SHA-256 revisions. Resolving an input follows its asset identity to its current path and refuses changed bytes. Repeated registrations of one owner/input id combine known outputs only when their source occurrence and scope agree. Every output must occur in the supplied placement map. Scope completeness remains explicit. Nested capture scopes keep their registrations separate and restore the outer scope after an error.
# dotbot
DotBot, the agent in Zero's editor: the component that runs a person's own
Claude or ChatGPT plan (or OrigoZero credits) from inside Zero, and the
DotBot panel in the editor's right dock that talks to it. This world is
where the plugin's published copy lives; the engine's built-in library pins
a version of it.
## What is here
| Part | What it is |
|------|------------|
| `plugin.wasm` | The DotBot component (`wasm32-wasip2`), built in the DotBot repo from `crates/dbot-zero-plugin`. |
| `plugin.yaml` | The plugin's grants: its scope, the hosts it may reach, its private storage. |
| `surface.module` | The plugin's Luau surface, what `require("@builtin::plugins.dotbot")` resolves to. |
| `source.module` | What the panel reads: agents, accounts, conversations, history, turns, agents a turn started. |
| `service.module` | The trusted service between the panel and the component: calls, the event ring, jobs. |
| `panel.editorPanel` | The DotBot panel itself: toolbar, transcript, agents, composer, settings. |
| `view.module` | What the panel says and how it looks (`palette()`), apart from how it is drawn. |
| `transcript.module` | The transcript and the agents section, drawn as virtual rows. |
| `workflows.module` | The Workflows view. |
Each module's own README says what it does in detail.
## Seeing a panel change
The editor draws its DotBot tab from the built-in library, not from this
world, so an edit to the panel here does not show in the real tab. Open the
world's own panel code over a fake plugin with example data instead:
```bash
luau --lang luau 'require("/source/dotbotPanelPreview.module").open()'
```
It opens a **DotBot preview** tab beside the real one. Run it again after
each edit. `dotbotPanelPreview.module/README.md` says what it shows.
## Shipping a change
Work on a branch of this world and open a pull request into `main`. How a
merged change reaches the engine (publishing `plugin.wasm`, and the engine's
pin of this world) is written down in the DotBot repo, in
`docs/zero-plugin.md`.
# xr
The tracked devices of an XR session and the hand controllers: where each part
of the person is, what the controllers' sticks, triggers and buttons read, the
hands and their fingers (held controllers or tracked bare hands), what the hands
point at, vibration, and the comfort settings of the person wearing the headset.
```luau
local right = xr.controller("right_hand")
if right and right.trigger > 0.8 then
xr.pulse("right_hand", 0.6, 0.1)
end
local head = xr.pose("head")
local ray = xr.pointerRay()
if ray then
print(ray.role, ray.origin.x, ray.direction.z)
end
```
## Poses are read by role
A tracked pose is read by the part of the person it follows: `"head"`,
`"left_hand"` and `"right_hand"`. `xr.roles()` lists the roles whose device the
runtime locates now, `xr.tracked(role)` asks about one, and `xr.pose(role, kind?)`
returns the pose in world space, or nil while the device is untracked. For a
hand the pose is where it holds the controller, and `kind` `"aim"` is where the
controller points. A device that follows another part of the body takes a role of
its own and is read the same way.
## Hands
A hand is driven by one source at a time: the controller held in it
(`xr.handSource(hand)` reads `"controller"`), or, while it holds none and the
runtime tracks it, hand tracking (`"hand_tracking"`). Otherwise the source is
`"none"`. A controller always wins over hand tracking.
```luau
local pose = xr.hand("right_hand") -- palm, finger directions, pinch
local joints = xr.joints("right_hand") -- the 26 joints by name
if joints then print(joints.joints.index_tip.position.y) end
print(xr.handTracking().available, xr.handTracking().reason)
```
`xr.joints(hand)` returns the 26 joints in world space: `palm`, `wrist`, then
`thumb_metacarpal`, `thumb_proximal`, `thumb_distal`, `thumb_tip`, and
`<finger>_metacarpal`, `_proximal`, `_intermediate`, `_distal` and `_tip` for
`index`, `middle`, `ring` and `little`. Each joint states its `position`,
`rotation`, `radius` and whether the runtime locates it (`tracked`); a joint's -Z
points along its bone toward the next joint and its +Y out of the back of the hand.
Where the runtime does not locate a hand that holds a controller, the joints are the
model's around the controller's grip, with the fingers curled by the trigger and grip
travel (`modelled` is true).
`xr.hand(hand)` is the same hand reduced to what moves an avatar's hand: the
`palm` (the frame whose -Z points along the fingers and +Y out of the back of
the hand), the `wrist` position and `directions`, 45 numbers giving the unit
direction each finger bone points along in the palm's frame (finger by finger,
thumb first, three bones each). `pinch` is the strength of the pinch of thumb
and index finger, 0 apart to 1 touching, and `pinching` whether it is held: it
begins when the gap between the fingertips' surfaces is 12 mm or less and ends at
30 mm, so it holds through the tremor of the fingers.
A hand tracked without a controller drives the game like a controller does. It
is active, its pinch is its trigger (`xr.controller(hand).trigger` is 1 while the
pinch is held), so a laser press on a panel button, a select in the editor and
the pad's trigger bindings all answer it, and it points the laser along its aim
pose. The aim comes from the runtime where it states one (`XR_EXT_hand_interaction`)
and is derived from the hand's joints otherwise, a ray from an estimated shoulder
through the base of the index finger; `xr.hand(hand).aimSource` says which, and
`xr.handTracking().aim` says which the runtime offers. Where the runtime offers
no hand tracking, `xr.handTracking().reason` says why and the controllers are the
only hands.
Without a body the hands are drawn over each eye as a jointed model (a block for
the palm, one along each bone and one at each joint), so the person always sees
their hands. When a body draws a hand with its own arm (see `xr.perspective`) the
body's hand is that hand.
## A game needs nothing from this module
While a session holds input focus the controllers drive the game's input on
their own:
| Controller | Pad |
|---|---|
| left stick | left stick (`move`) |
| right stick, horizontal | right stick (`look`), as snap or smooth turning |
| right stick, vertical | right stick, which `look` ignores in a headset |
| A / B (right) | south / east (`jump` / `crouch`) |
| X / Y (left) | west / north (`interact`) |
| left menu button | start |
| grips | left and right shoulders |
| triggers | left and right triggers |
| stick clicks | left and right stick clicks (`sprint` on the left) |
Every input map's gamepad bindings answer them unchanged, `Zin.surface`
reports the device class it reported before the session began, and the touch
overlay does not appear. The pad is connected while a controller is held and
disconnected when the session loses input focus.
## Turning
The look action reads the right stick's horizontal axis as discrete steps of
`xr.snapTurnDegrees()` (45 degrees) by default: one flick of the stick is one
step, and the stick has to return to rest before the next flick. Smooth
turning is the opt-in comfort setting `xr.setTurnMode("smooth")`. The game turns
its own camera through the look action and the headset follows the camera's
yaw; the head tracks fully free, and the stick never tilts the view.
A step is 45 degrees at the look sensitivity every shipped camera rig
defaults to (0.005 radians per look unit); a rig authored with another
`sensitivity` turns in proportion.
## Pointing
The engine's pointer hit (`getPointerHitTable()`, the hover and selection a mouse
produces on desktop) is cast along the dominant hand's aim pose while the
session holds input focus. `xr.pointerRay()` returns the same ray. The laser ends where that cast hits; a script that
carries something to a point the cast does not know of calls `xr.setPointerReach(distance)`
each frame, and `xr.setPointerReach(nil)` hands the beam back.
The laser is the game's mouse. While the session holds input focus,
`input.snapshot().mouse_position` is the point the laser rests on (where its cast
hit, else far along the ray) projected into the view the game renders from, in the
game's viewport pixels, every frame and with no press: whatever reacts to the
mouse hovering reacts to the laser resting on it, and mouse-move events follow it.
A ray the game builds from that position (`screenToRay(x, y)` at the mouse,
`physics.raycastFromScreen`) is the laser's own ray, so a hit on a mesh gives the
entity, the point and the UV the laser visibly touches. A laser on a panel, or
pointing out of the game's view, leaves the mouse just outside the viewport
(`mouse_in_viewport` reads false). The press is the controller's trigger, read as
before through the pad.
## Panels
A panel is a surface standing in the world that shows UI and takes the
controller's laser as its pointer. It shows screens of the UI, drawn into a
picture of its own that the engine puts over both eyes after the world has been
tonemapped, so the interface stays sharp and keeps exactly the colours its
author gave it. A panel is flat or bent around the person (`curve` is the
radius in metres of the cylinder), and its pose is measured in the world, in the
room, or in the person's view. With the `"tracking"` anchor a panel stays where
the person put it and follows the rig when the game moves or turns the player.
With the `"view"` anchor the pose is stated in the frame at the head, turned by
the head's yaw and pitch and not its roll (`{ position = {x = 0, y = -0.05, z = -2.4} }`
is 2.4 metres ahead of where the person looks and 5 centimetres below), and the
panel follows the head: it eases towards that place with a time constant of 0.12
seconds, so a small tremor of the head does not shake it, and it stands there at
once when the person recenters, when the session begins and when a script states its
`pose` or `anchor`. The laser points at a view-anchored panel where it is drawn,
and a view-anchored panel held by its handle keeps the place it is put in the view.
```luau
xr.panels.create({
id = "stats",
screens = { "stats_hud" },
width = 1.2, height = 0.7, curve = 1.5,
pose = xr.panels.placement({ distance = 1.2, yaw = 25 }),
anchor = "tracking",
handle = { 0, 0, 0.6, 0.08 },
})
```
A panel's corners are rounded by `cornerRadius`, in metres along the surface
(0.03 unless the panel states another; 0 leaves them square), and the picture,
the frame around it and the laser's hits all stop at that outline.
The world's HUD, the shown screens its game authored (`space = "content"`: every
screen of either the `"window"` or the `"camera"` space that is not the
editor's chrome, so a menu placed on the window shows in both eyes like a
camera-space screen), appears with no script on the curved panel `"hud"`, with the `"view"` anchor,
2.4 metres in front of where the person looks; `xr.panels.autoHud(false)` turns
that off. The game lays its screens out for that panel: while a session shows them
with no window beside it, `ui.screenSize()` is the HUD panel's logical size, 1280
points across, and a screen sized from it fills the panel. The HUD panel passes the laser through wherever its UI has nothing to
act on.
While the laser points at a panel the world receives no pointer: the engine's
pointer hit is empty and the pointing hand's trigger and vertical stick belong to
the panel. The trigger presses what the laser is on, and the stick scrolls it.
A press that began in the world stays the world's when the laser crosses a panel.
`xr.panels.hover()` names the panel under the laser and the `uv` on it, and
`xr.panels.state(id)` reads one panel's hover, grab and drop.
A press on a panel always reaches its UI, the handle included, and a press is a click.
A panel's `handle` is a rectangle of its picture (`{ left, top, right, bottom }`,
0,0 the top left) that moves the panel by a deliberate drag: with the trigger held
(or a hand's pinch), the panel is held once the laser has turned more than 6 degrees
from where the press began, which is more than a controller's trigger pull turns it.
At that moment the UI's press ends outside the panel, so no widget takes it for a
click, and the panel follows the laser at the distance it was held, turns to face the
person, and is pulled and pushed by the stick, until the trigger is released. It stays
where it is put. A press on the handle that is released with the laser turned less
than that clicks the widget under the point where it began, wherever the laser swayed
to, and counts in `xr.panels.state(id).taps`, which is how a small movable panel (a
point) is also a button. `xr.panels.state(id)` reads `grabAngle`, the turn in degrees
that makes a press a grab, and `pressTurn`, how many degrees the laser has turned
since the press held on the panel began (nil while none is held). A press off the
handle follows the laser for the UI however far it turns. A panel created with
`acceptsDrops` is a drop target: `xr.panels.state(id).droppedOn` names it when the grab
ended with the laser on it, and `dropTarget` is true on it, and its frame is drawn
green, while another panel is held over it. A panel that accepts no drops is never
named.
`xr.panels.grab(id, { distance?, offset? })` holds a panel with the pointing hand while
its trigger is held, as if the trigger had been pressed on its handle: a list entry that
was pressed and dragged past the grab angle makes the panel it stands for and grabs it,
and the panel is under the laser from the next frame to the release. The press on the
entry ends there without a click.
A panel created with `resize = { corner?, minWidth?, minHeight?, maxWidth?, maxHeight?, corners? }`
(flat panels, `corners` `"bottom"` or `"all"`) is resized by pulling the trigger on a
corner's zone: the dragged corner follows the laser on the panel's plane, the opposite
corner stays, and the size stops at the limits. The panel keeps its points per metre,
so a larger panel lays out more content rather than larger content.
`xr.panels.state(id)` reads `onCorner`, `resizing` and `resizes`; the engine marks each
resize corner with three dots that light while the laser is on the corner.
A widget with a `dragPayload` on a panel is dragged with the trigger as it is with the
mouse. `xr.panels.drag()` reads the drag in flight (`panel`, `payload`, `label`, `overPanel`
and the pointing `hand`) for as long as the trigger is held, wherever the laser points,
so a script that carries the payload into the world (an asset placed under the laser)
follows `overPanel` and the release, when the reading turns nil.
A `dockArea` drawn on a panel hands a tab dragged out of it and released over
empty space to its owner (`ui.takeDockTearOffs(dockId)`) instead of opening a
window inside itself.
## The view
The camera the game moves relative to is the rig: the game camera's position and
yaw, written as the camera entity's own transform. While a session draws frames
the camera entity that owns the viewport keeps the game's own pose:
`entity(id).position`, `.rotation`, `.eulerAngles`, `.worldMatrix()` and the
local reads are the values the game wrote, so a script that reads the camera's
pose, changes it and writes it back moves the camera exactly as it does on a
desktop. Its facing is the person's: `.transform.forward`, `.right` and `.up` are
the head's directions (`camera.facing(id, axis)` is the same read), and the
`Camera` component's `forward`, `right` and `up` are the same values. A game that
aims, picks up or prompts along its camera's forward acts where the person
looks, with no code for a headset. Everything parented under the camera (a
carried prop, a viewmodel) is drawn and read in the world under the head.
Movement written relative to the camera follows where the person looks;
`xr.pose("head")` is the head's full pose.
The client setting `xr.aim` (`xr.aim()`, `xr.setAim(aim)`) chooses what the
camera faces. `"head"` (the default) is the head's orientation. With
`"controller"` the camera's facing (`transform.forward`, `right` and `up`, and
the `Camera` component's) is the dominant hand's aim direction with the head's
up, so a game that aims, picks up or prompts along its camera's forward acts
where the controller points; the eyes still draw from the head, and the setting
applies on the next frame.
What the game writes stays the base. Its pose, local or world, is the game's own
and the rig is built from it, so a first-person look, a follow camera or a script
turning or moving the camera turns and moves the base, and the head composes on
top of it, with its yaw counted once. The game's view for `worldToScreen`,
`screenToRay` and the laser's mouse is the game camera's lens from the head's
pose, so they agree with what the person sees. When the session stops, the
camera entity is drawn at the game's own pose the same frame.
`getLookHitTable()` casts from the eye point along the camera's facing.
## The body and the perspective
In play mode a headset sits in the local player's body whenever the game has one.
`xr.body()` returns `{ entity, reason }`: the body is the avatar the spawn system
bound to the player (`avatar`), else the entity the game's camera follows
(`cameraFollow`), else the entity the player's character controller moves
(`controller`). A candidate is the body only when the game uses it: the game's
camera follows it, or a character controller the local player drives moves it. An
avatar neither followed nor driven (a game that plays from its own fixed camera) is
not a body, and `xr.perspectiveStatus().why` says so. A game with no such entity (a
strategy camera over many units) has no body and the game's camera is the view. The
search repeats, so a character the game starts following or driving later becomes the
body then.
`xr.perspective()` is `"embodied"` or `"game"`:
- `"embodied"` puts the eyes at the body's eye height straight over its root (never
over an animated bone, so a walk cycle does not bob the view), with the real head
free on top. The yaw is the game camera's, so turning works as it does without a
headset, and the game's camera entity keeps running untouched. The body's head
and what is attached to it draw for every view but the person's own eyes (other
players, the desktop window under `editor` and a capture from another camera
still see it), and its arms follow the hands.
- `"game"` is the view from the game's own camera with the head free.
A world whose camera is a first-person camera is embodied and offers no choice.
Any other world with a body is embodied until the person chooses: a click of the
right thumbstick switches, and so does the **See from** setting in the client
settings (`clientSettings.open("vr")`). The choice is the person's client setting
`xr.perspective`, the same in every world: a world reads it
(`clientSettings.get("xr.perspective")`, `xr.perspective()`) and does not change
it, so `xr.setPerspective` is refused from world code. `xr.perspectiveStatus()` says which
perspective is in force and why, the body found, where the eyes stand, and how much
of the body is hidden from the eyes or reaching for the hands.
The body's head is hidden by drawing the body's skinned meshes a second time for the
eyes alone, with the head bone and everything below it collapsed
(`SkinnedModel.collapsedBones`), while the meshes themselves draw on the layer
`xrSelf`, which the eyes do not draw (`renderer.setLocalLayers`). Parts attached
below the head bone (a hat, hair) and the player's name label draw on `xrSelf` as well. A camera that names the
render layers it draws sees the body only if it names `xrSelf`.
## Reading the controllers
`xr.controller(hand)` returns a controller's inputs as of the frame last drawn:
its sticks, trigger, grip and buttons. Poses come from `xr.pose`; they pass
through the same rig as the eyes, so they move and turn with the game's camera.
## Vibration
`xr.pulse(hand, amplitude, seconds, frequency?)` vibrates a controller. It
returns false and plays nothing while no session holds input focus.
## Taking the headset off
A session stays standing while the headset is off: the person can test in VR,
take the headset off and work at the desktop, and put it on again to be back in
VR, with no step in between. While the runtime does not show the session and
reports that nobody wears the headset, the engine begins no XR frame: a runtime
holds each frame of a session it does not show for its own throttle (SteamVR
holds every frame's end for about 100 ms), so the frame loop pauses and the
engine's own frames run at the desktop's pace. The session keeps listening to
the runtime, and when the headset is worn again the frame loop runs, the
runtime shows the session, and the eyes are drawn again. Leaving VR from the
menu (or `xr.exit()`) still ends the session.
The `xr` observation (`/zero/runtime/observations/xr`) states it:
`reading.userPresent` is what the runtime reports about the person wearing the
headset (`null` for a runtime that reports nothing, whose session never pauses),
and `reading.paused` is true while the frame loop is paused. `xr.focused()` is
false while the headset is off.
## Testing without hands
`input.simulateXrController(hand, control, ...)` and the `inputSim` toolbox's
`xr` tool inject controller state where the runtime's action set enters the
engine, so the pad, the turning, the pointer ray and `xr.controller` follow it
exactly as they follow held controllers. The injected state takes effect while
the session holds input focus. `input.simulateXrHead(...)` and the `xrHead`
tool inject the head pose in the tracking space; the eyes move with it.
`input.simulateXrSession(true)` (or the engine's `--xr-sim` boot flag, which a
headless engine takes too) starts a simulated session: the engine runs its XR
frame loop over a session that needs no headset. It holds input focus from its
first frame, locates a head standing at the tracking space's origin 1.6 m up
and facing -Z (`input.simulateXrHead` moves it) with two eyes 64 mm apart
through symmetric 90 degree frusta, and reports the controllers and hands
`input.simulateXrController` states. The eyes are drawn at 1024 by 1024 pixels
each and shown to no compositor. `xr.focused()`, `xr.pose`, `xr.pointerRay` and
the panels read it as they read a headset. `input.simulateXrSession(false)`
stops it and every read answers as it does with no session. The session starts
and stops on an engine frame, so wait for `xr.focused()` after starting it. It
runs on native engines; a headset's session that already stands is left as it
is.
`input.simulateXrWorn(false)` takes the simulated session's headset off: the
session reports it not worn and stands in the synchronized state, its runtime
holds each begin and end of a frame, and the engine begins none.
`input.simulateXrWorn(true)` puts it on again; the frame loop runs and the
session takes focus once a frame has ended.
# marquee_overlay
A screen-space translucent rectangle with a 1px border, drawn while a viewport
rubber-band (marquee) selection is dragging and hidden otherwise. It owns one
dedicated UI screen tagged `editor`, so it rides the `EditorUI` render layer and
the editor's F1 chrome toggle alongside the rest of the editor overlays.
`viewport_select` drives it.
## Exports
- `M.show(ax, ay, bx, by)` — show the band filling the rectangle spanned by the
two corners, given in UI-logical points (the `ui.screenSize()` space). Corners
may be passed in any order.
- `M.hide()` — hide the band. Safe to call when nothing is shown.
## Notes
- Callers work in viewport pixels; convert to UI-logical points (multiply by
`ui.screenSize().width / viewport.w` and the height ratio) before calling
`show`, since absolute `left`/`top`/`width`/`height` resolve in the logical
space, not render pixels.
- Coordinates are rounded to whole points so a value in the open `(0, 1)` range
is never mistaken for a viewport-axis fraction by the size decoder.
# carried
Content of another world, mounted read-only for this session at
`/zero/runtime/carried/<key>/` without installing it. A closure is named by
the sha-256 of its manifest (`closureSha`); the engine reads the manifest and
every file it names through the device's content cache and lays them out the
way their world places them. Nothing a mount holds is content of the open
world: no asset listing, dependency table, push or `zm status` sees it, and
the open world's code cannot `require` from it.
```luau
local m = carried.mount(closureSha, { key = "ada.avatar" })
local s = carried.wait(m.key) -- yields until ready, refused or none
assert(s.state == "ready", s.detail)
print(vfs.read(s.path .. "/chars/ada.avatar/avatar.json"))
print(carried.resolve(m.key, "chars.ada_albedo")) -- what a reference inside the closure names
carried.release(m.key) -- the last holder takes it down
-- Preview an asset of the open world's working tree through the same route:
local d = carried.wait(carried.mountDraft("/zero/source/props/lamp.model").key)
```
`guides { path: "core/carried" }` covers the status fields, the builtin
versions a closure was built against, and what the open world never sees.
# values Module
Public Luau surface over the `__values` Internal FFI namespace: the named
values an entity holds. Auto-injected as `_G.values` via the prelude; every
entity proxy carries the same calls as `entity(id).values`. The
`topics/values` guide covers the whole system.
A named value is a number, a vector or a boolean an entity carries under a
name. Scripts and engine systems write and read it through one store, with
nothing queued between a write and the next read, so the readers that follow
values (material properties, `Audio` voices, UI props, replication) see a
write on their next read with no script copying it to them.
## Exports
- `values.set(entity, name, value)`: write a value; `nil` removes it. A name
keeps the kind of its first value.
- `values.get(entity, name) -> value?`: read a value.
- `values.declare(entity, name, { type?, default?, replicate? })`: state a
name's kind, the value it starts at and the rate in Hz it replicates at; a
value with no rate stays on this engine.
- `values.remove(entity, name) -> boolean`, `values.clear(entity) -> number`.
- `values.list(entity) -> { [name]: value }`.
- `values.describe(entity) -> { row }`: each value with its type, last writer
(`script`, `engine`, `remote`), revision, replication rate and whether it is
declared.
- `values.entities() -> { id }`: every entity holding a value.
- `values.stats() -> { entities, values, revision, replication }`.
- `values.subscribe(entity, name?, fn) -> connection`: `fn(value, name,
entityId)` once per frame the value changed; `nil` name follows every value
of the entity.
- `values.onAnyChange(fn) -> connection`: every change of every value.
- `values.bind(entity, name, { format?, scale?, offset?, fallback? })`: a UI
prop that follows a value.
## Usage
```luau
local car = entity.find("car")
car.values.declare("throttle", { type = "number", replicate = 10 })
car.values.set("throttle", 0.8)
car.values.set("brake", true)
print(values.get(car, "throttle")) --> 0.8
for _, row in values.describe(car) do print(row.name, row.type, row.value, row.writer) end
```
# mcpLog Module
Public Luau surface over the `__mcpLog` Internal FFI namespace —
read-only ring buffer of MCP tool-call entries.
## Purpose
Wrap the raw `__mcpLog.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.mcpLog` via the prelude. The in-engine "MCP" panel
polls `mcpLog.query()` every frame and renders the returned array of
structured tool-call rows.
## Usage
```luau
-- Pull the most recent 50 calls
for _, entry in ipairs(mcpLog.query(50)) do
print(entry.tool_name, entry.status, entry.duration_ms)
end
-- Full ring (up to 500 entries)
local all = mcpLog.query()
-- Drop everything
mcpLog.clear()
```
## Exports
- `mcpLog.query(limit?) -> { McpLogEntry }` — newest-last array of entries.
- `mcpLog.clear() -> boolean` — drop all entries.
# component_field_route
One rule for which access route serves a component's fields, shared by every
API that names an entity, a component and a field: `Entity.getField`,
`Entity.setField`, `Entity.patch`, `entity.batchWrite` and `entity.batchRead`.
Two routes exist, because two kinds of component do:
- **reflect route** — a component backed by an engine struct (`Transform`,
`MeshInstance`, `Physics`). `__reflect` resolves its fields through the
reflect registry.
- **component route** — a component declared in Luau (`Model`, `Text3D`,
and every other `.component` folder). Its field values
live on the component instance, so the component ref
(`entity(id).component.get(name)`) is what reaches them.
The reflect registry holds engine structs only, so a component declared in Luau
resolves on the second route and nowhere else. Dispatching on which route
serves the name is what lets one call site write `Model.tintBlend` and
`Transform.position` the same way.
## Exports
- `M.isReflected(component: string) -> boolean` — whether the reflect registry holds this component.
- `M.requireComponentType(api: string, component: string)` — raise unless the name is one this engine knows, either as an engine struct or as a declared `.component`.
- `M.componentRef(entityId: string, component: string) -> ComponentRef?` — the component ref serving `component` on that entity, or `nil`.
- `M.declaredFields(ref: ComponentRef) -> { [string]: boolean }` — the public and private field names the ref declares.
- `M.reportMissingField(api, component, field, outcome)` — report a field the component does not declare.
- `M.reportEntityWithoutComponent(api, entityId, component, outcome)` — report one entity that does not carry it.
- `M.reportEntitiesWithoutComponent(api, component, missing, total, outcome)` — report a call's entities that do not carry it, as one line.
- `M.readField(api, entityId, component, field) -> any` — read one field through whichever route serves it.
- `M.writeField(api, entityId, component, field, value) -> boolean` — write one field through whichever route serves it.
## Usage
```luau
local Route = require("@builtin::modules.component_field_route")
Route.writeField("entity.batchWrite", id, "Model", "tintBlend", 0.5)
local blend = Route.readField("entity.getField", id, "Model", "tintBlend")
```
## What a caller is told
| situation | result |
| --- | --- |
| a component name nothing declares | raises, naming the component |
| a component the entity does not have | the neutral value, reported by the route |
| a field the component does not have | the neutral value, reported at error level |
`api` is the surface the caller used; it is named in every diagnostic so the
line points at the call rather than at the machinery underneath.
A report repeats at most once every five seconds per `(api, component, field)`,
the budget the reflect route spends on the same mistake, so a per-frame loop
over a wrong name costs one line rather than one per frame — and a batch names
the entities that do not carry the component once for the call rather than once
each.
# xr_models
The hands and the controllers of a headset as models in the world. A hand is a
rigged hand mesh whose 25 joint bones stand where the runtime puts the hand's
joints, so the fingers bend as the person's do. A controller is the model of the
Quest Touch Plus controller, with its trigger, squeeze, thumbstick and buttons
moving as the person presses them. Both are temporary entities on the layer
`xrEyes`, which only the person's own eyes draw. Their meshes state
`pickable = false`, so the laser, which starts inside the hand or the controller,
and the look ray hit the scene behind them (`getPointerHitTable()`).
```luau
local Models = require("@builtin::modules.api.engine.xr_models")
Models.tick({ mode = engine.mode, bodyHands = { left_hand = false, right_hand = false } })
```
What shows follows the input:
- a hand shows while a controller or hand tracking drives it and the player's body
does not draw it with its own arm. Around a held controller the hand is the
model of a hand holding it;
- a controller shows in edit mode while it is held. It never shows in play mode and
never while its hand is tracked bare.
The models are the WebXR Input Profiles project's `generic-hand` and
`meta-quest-touch-plus` assets, MIT licensed (`models/xr/LICENSE.md` holds the
source and the licence).
`setInput(source)` reads the tracked devices from a table of `handSource(role)`,
`joints(role)`, `controller(role)` and `pose(role)` in place of the XR session, which
is how a test or a desktop engine shows the models. `status()` says which models
stand and whether they are ready; `release()` takes them all down.
# recording
The editor's recording service. The F9 command, the Recording panel, the top
bar's record button and the `recording` toolbox all call it.
A take is an `av.record` take filed under `/zero/source/local/recordings/`:
this machine's own content, streamed to disk as it records, kept across
restarts and outside the world's sync. The service keeps no state; what is
recording, where, and how far along it is reads off `av.status()`, so any
caller reports the same take.
## Exports
- `M.start(opts?) -> (path?, reason?)` — `opts = { scope?, camera?, fps?, audio?, width?, height? }`.
`scope` is `"viewport"` (the scene view as it shows, no panels; the default)
or `"window"` (the whole editor window). Yields: run it where it can.
- `M.stop() -> (Take?, reason?)` — `Take = { path, bytes, seconds }`. Waits for the engine to file the take.
- `M.toggle(opts?) -> boolean` — true when it started a take.
- `M.status() -> Status` — `{ recording, path, seconds, bytes, scope, error }`.
- `M.list() -> { Entry }` — `{ path, bytes, modified? }`, newest first.
- `M.delete(path) -> boolean` — a take by file name or path; the take in flight is refused.
- `M.save(path) -> (boolean, string?)` — `userfile.save` of the take.
- `M.declareCommand()` — declares `recording.toggle` on F9.
## Usage
```luau
local Recording = require("modules.api.editor.recording")
task.spawn(function()
local path = Recording.start({ scope = "window" })
task.wait(5)
local take = Recording.stop()
print(take and take.path, take and take.bytes)
end)
```
# lightCookies
Projects an authored image through a spot light's cone — a gobo, window blinds,
a headlight cutoff, a projector pattern.
## How it divides up
The renderer already projects a texture through a spot's frustum. At each shaded
point it reads `zero_feature_texture(uv, cookieLayer)`, with `uv` from that
point's position in the light's own clip space, and multiplies the cone by what
it finds. `SpotLight.cookieLayer = -1` means no cookie.
What the renderer does not decide is what goes in the layer. That is this
package: resample an authored image into one full layer of the shared
feature-texture array, and point a spot at that layer.
## Using it
```luau
local lightCookies = require("@builtin::systems/lightCookies.package/lightCookies")
-- Size the array once for every layer the scene will use.
lightCookies.configure({ resolution = 256, layers = 4 })
lightCookies.project(lampId, "/textures/cookies/window_blinds.png", { layer = 0 })
```
Or attach a `LightCookie` component next to the `SpotLight` and author
`texture` / `layer` / `gain` / `tint` on it.
`lightCookies.clear(lampId)` stops the projection; the layer keeps its contents.
## When a fill lands
`fill` and `project` queue the fill and return its layer at once. The module's
own loop writes it over the frames that follow: the rasterize is issued on the
next frame and the copy into the layer on the frame after, and the fill is
written once `renderer.featureTexture.state().fills` reports the copy landed in
its layer, one fill at a time in the order they were asked for. The loop belongs to the module, so a fill
lands even when the code that asked for it (a one-shot script, a task scope, a
component that is destroyed) has ended.
`lightCookies.status(layer)` reports where the last fill of a layer stands:
```luau
local s = lightCookies.status(0)
-- s.state: "queued" | "rasterizing" | "copying" | "written" | "refused"
-- s.reason: why a refused fill was refused, in the engine's words
-- s.filled: whether renderer.featureTexture.state().filled lists the layer
```
`status` reads a fill `"written"` from the first reading of the array that
reports its copy landed, so `s.state` and `s.filled` agree whichever of the
module's loop and the reader runs first in a frame.
A fill names a layer below the count `configure` sized the array to; one past
it is refused at the call, which returns nil and the reason. A fill that cannot
land once it is on its way (the GPU refuses its rasterize because its image was
given back first, a later `configure` left the array without its layer, or its
copy never reached the array) reads `"refused"` with the reason, and is also
logged as a warning.
A `LightCookie` component whose fill is refused at the call, such as one
authored before the scene's `configure` has sized the array, asks again each
time `configure` sizes it. `lightCookies.observe().configurations` counts
those calls for code of its own that does the same.
`lightCookies.observe()` reports how many fills are waiting, the one in
progress, and the loop's own counters.
## An empty layer puts the light out
The cone is multiplied by what it reads from its layer, so a spot pointed at a
layer nothing has filled renders black rather than plain. `project` fills before
it points the light, which is the order that keeps the cone lit; if you set
`SpotLight.cookieLayer` by hand, fill that layer first.
## The array is shared, and sizing it is explicit
The feature-texture array is one resource that every feature using
`zero_feature_texture` draws layers from, and it has no allocator: sizing it
zeroes every layer, including layers another feature owns. So this package never
sizes it as a side effect of setting a cookie, and `layer` is authored rather
than assigned. `lightCookies.configure` is the one call that resizes, made once
by whoever knows what else in the scene wants layers.
A scene that also bakes global illumination shares this array with the lightmap
atlas. Size it for both, and give cookies layers above the ones the bake fills.
## A cookie fills a whole layer
The cone's lookup runs over the layer's entire `uv` range, so an image is
resampled to the layer's extent rather than placed in a corner of it. One layer
carries one cookie.
## Alpha
The source's alpha is how much of the pattern applies. At alpha 0 the cone
passes through unmodulated, so a fully transparent image is a no-op rather than
a black cone.
# editorRegistry
The single registry every editor surface is built from — builtin tabs and world panels alike. The engine's own tools register through the same public API a world uses. Two surfaces consume the registry: the dock service (`system_tools.module`) renders whatever panels are registered, sorted by `order`, and the top bar (`EditorTopBar.component`) builds its menu bar from the registered menus and each panel's `menu`/`order`. Both subscribe to `onChanged` so add/remove is live.
Registrations run through two paths, both ending in `addPanel`: builtin tabs register from `modules.api.editor.system_tools.panels` (the require IS the registration), and world panels register via an `editorPanel` asset whose `onRegister(self)` hook calls `addPanel`. State lives in a fixed `_G` slot so it survives hot-reload and edit↔play mode flips. A duplicate id replaces the prior registration, which is how a world overrides a builtin tab and how hot-reload re-registers cleanly.
## Panels and menus
- `M.addPanel(spec) -> boolean` — add (or replace) a dock panel. `spec`: `id` (required, unique), `build` (required, `(state) -> widget`), `label?`, `menu?` (default `"window"`), `order?`, `refresh?`, `onCallback?`, `onMount?`, `tick?`, `float?`.
- `M.removePanel(id) -> boolean` — remove a registered panel by id.
- `M.addMenuItem(spec) -> boolean` — add (or replace) a clickable action item that runs `onClick`, with no associated panel. `spec`: `id` (required), `onClick` (required), `label?`, `menu?`, `order?`.
- `M.removeMenuItem(id) -> boolean` — remove a registered action item.
- `M.addMenu(spec) -> boolean` — add (or replace) a top-level menu in the bar. `spec`: `id` (required), `label?`, `order?`.
- `M.removeMenu(id) -> boolean` — remove a top-level menu and cascade-drop every item/panel that targeted it.
## Introspection and subscription
- `M.list() -> { panels, items, menus }` — snapshot copies of current registrations for introspection.
- `M.onChanged(fn) -> handle` — subscribe to any add/remove mutation; `fn` runs with no args.
- `M.offChanged(handle) -> boolean` — unsubscribe.
## Host accessors (dock service + top bar)
- `M.setDock(controller?)` — publish (or clear with `nil`) the live `DockController`.
- `M.dock() -> DockController?` — the live dock controller, or `nil` when no dock is mounted.
- `M.panelsSorted() -> {spec}` — live dock panels sorted by `(order, id)`, including `build`.
- `M.menuModel() -> {menu}` — the full top-bar menu model: every menu in bar order, each carrying its entries (`{kind="panel", id, label}` or `{kind="action", id, label}`) in `order`.
The `DockController` type is `{ open, close, toggle, isOpen }` plus optional `getLayout` / `restoreLayout` for layout persistence.
## Usage
```luau
local editor = require("@builtin::modules.api.editor.registry")
editor.addMenu({ id = "mygame", label = "My Game", order = 70 })
editor.addPanel({
id = "my_tools", label = "My Tools", menu = "scene", order = 50,
build = function(state) return Z.lbl("hello") end,
})
editor.addMenuItem({ id = "act", menu = "scene", label = "Go",
onClick = function() end })
```
# 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 } }`.
A preview pictures its whole subject, however many entities it composes. While
the subject settles, its bounds are measured each frame by walking it in Luau
for up to `opts.entityBudget` entities (default 2000); a subject composing more
is measured by the capture framing alone, which reads each root's hierarchy
bounds from the engine.
## Example
local result = asset.resolve("gold", "material"):preview({ size = { width = 512, height = 512 } })
-- result.imageBase64 holds the rendered PNG (base64)
# scifi_hud
A UI template screen.
# future
A future is a promise held as a value: store it in a table, return it from a
function, hand it to another task, and await it whenever the value is needed.
Every promise-returning call (`http.get_json`, `delay`,
`asset.load`, ...) already hands back one, a `PromiseHandle`; this module makes
new ones, runs work as one, chains them, waits for several at once, bounds one
in time and cancels them.
```lua
local future = require("@builtin::modules.future")
task.spawn(function()
-- Start both loads; they run at the same time.
local pending: { Future<any> } = {}
table.insert(pending, http.get_json("https://example.com/a.json"))
table.insert(pending, http.get_json("https://example.com/b.json"))
-- Collect them. Each await returns once its load has settled.
local results = {}
for i, f in pending do
results[i] = f:await()
end
end)
```
## Members of a future
| Member | What it answers |
|---|---|
| `f:await()` | Yields until the future settles and returns its value; a future that has already settled returns at once, with no yield. A rejection raises its error at this line. The same call as `await(f)` and `task.await(f)`. |
| `f:state()` | `"pending"`, `"resolved"`, `"rejected"` or `"cancelled"`, read without taking the value. |
| `f:rejection()` | Why the future was rejected: `{ message, origin?, stack? }`, the reason as text, the `chunk:line` the rejection came from and, when Luau rejected it, the stack there. `nil` while it is pending or once it resolved. |
| `f:source()` | The `chunk:line` whose call created the promise, for finding what a hung await is waiting on. |
| `f.handle` | The promise's id string. `tostring(f)` reads the same. |
| `f:andThen(onResolve, onReject?)` | A future of what the handler returns; a future it returns is awaited and its value delivered. Without `onReject` a rejection passes through. A handler that raises rejects it. |
| `f:catch(onReject)` | A future of `f`'s value, or of what `onReject` returns given the error. |
| `f:finally(fn)` | A future settled the way `f` was, once `fn()` has run, whichever way `f` settled, cancelled included. |
| `f:tap(fn)` | A future of `f`'s value, once `fn(value)` has seen it. |
| `f:timeout(seconds, reason?)` | A future of `f`'s value that rejects with `reason` (a message naming the time by default) when `seconds` of real time pass first; `f` is then let go of. |
| `f:cancel()` | Ends a pending `f` as cancelled: `true`, or `false` and the reason. |
The chaining methods come with the module, which every world script VM loads,
so a future an engine call hands back chains with no require. A handler runs in
a task (it may wait) inside a `scopes.run`: the chained future settles once
everything the handler started is over.
Every task that awaits a future receives its value: the ones waiting when it
settles and any that await it later, for as long as the future is held.
## Module functions
| Call | Result |
|---|---|
| `future.wrap(promise)` | The future naming a promise, from its future or its id string. An id naming no promise the engine keeps raises. |
| `future.new(onCancel?)` | A pending future plus `resolve(value)` and `reject(error)`, which settle it once. `error` is any value but nil. `onCancel()` runs when the future is cancelled. |
| `future.resolved(value)` | A future already resolved with `value`. |
| `future.rejected(err)` | A future already rejected with `err`. |
| `future.after(seconds)` | A future resolving with `true` after `seconds` of real time (the promise `delay(seconds)` hands back). |
| `future.spawn(fn, ...)` | Runs `fn(...)` as a task; the future resolves with what it returns (awaiting a future it returns) and rejects with what it raises. |
| `future.all(futures)` | Every value, in the order given. The first rejection rejects it, the first cancel cancels it, and the rest are let go of. `{}` for none. |
| `future.allSettled(futures)` | `{ status, value?, error? }` for each, in order, once all have settled. Never rejects. |
| `future.race(futures)` | Settles the way the first to settle did; the rest are let go of. |
| `future.any(futures)` | The first value resolved; the rest are let go of. When none resolves it rejects with `{ message, errors }`. |
| `future.retry(fn, attempts, delaySeconds?)` | Calls `fn()` until it succeeds, at most `attempts` times, with `delaySeconds` of real time between. |
| `future.fromEvent(event, predicate?)` | The first value of the next fire of `event` (a Signal, a component event, anything offering `:Connect(fn)` / `:connect(fn)`) that `predicate` accepts. Disconnects once settled or cancelled, and is cancelled when what started it ends. |
```lua
local future = require("@builtin::modules.future")
task.spawn(function()
-- Both loads at once; the first failure fails the lot.
local maps = future.all({ http.get_json(urlA), http.get_json(urlB) }):await()
-- Whichever search answers first; the other is cancelled.
local nearest = future.race({ future.spawn(searchNear), future.spawn(searchFar) }):await()
-- No level within five seconds rejects, and the load is cancelled.
local ok, err = pcall(function()
return future.spawn(loadLevel, "forest"):timeout(5):await()
end)
end)
```
## Cancellation
`f:cancel()` ends a pending future as cancelled. Awaiting it raises the error
`task.isCancellation(err)` recognises, and `f:state()` reads `"cancelled"`. A
cancellation is never written to the error log.
- **The work stops.** The task running a `future.spawn` or a handler is
cancelled, and so is everything it started; each unwinds, so the `pcall` or
cleanup around its wait runs.
- **Downstream.** A future chained from a cancelled one (`andThen`, `catch`,
`tap`, `timeout`, `all`, `race`, ...) is cancelled too, without calling its
handler; `finally` runs its function first.
- **Upstream.** A future counts the chains and combinators waiting on it. One
whose last such consumer is cancelled, or settled without it (a `race`
another input won, a `timeout` that ran out, an `all` another input
rejected), is cancelled. A direct `await` is not a consumer.
- **What started it.** The task running a handler belongs to what the calling
code belongs to: a component instance, a scene load, a task scope. When that
ends, the future is cancelled.
A future an engine call handed back (`http.get_json`, `delay`) runs to its end
whatever waits on it; its `cancel()` answers false and the reason.
## Rejections
A rejection is kept apart from any value, so a future resolved with a table of
any shape delivers that table. Awaiting a rejected future raises its error: a
string at the await's line, any other value (an error table `reject` was
given) as itself. Catch it with `pcall`, and read where it came from on the
future:
```lua
local f, _, reject = future.new()
task.delay(1, function()
reject({ code = 404, message = "no such level" })
end)
local ok, err = pcall(f.await, f)
if not ok then
print(err.code) -- 404: the error value reject was given
local why = f:rejection()
print(why.origin) -- the line that called reject
end
```
A rejection nothing sees (no await receives it and nothing reads
`rejection()`) is written to the error log once the future is gone, so a
future you hold and await later reports nothing on its own. A chain or
combinator sees every rejection its inputs hold when it settles, so the second
rejection of an `all`, or a `race` input already rejected when another won,
writes nothing.
## Identity
A VM holds one future object per promise. Every call that hands a promise to
the VM while its future is alive, `future.wrap` included, hands back that same
object: `future.wrap(f) == f`, `rawequal(future.wrap(f.handle), f)`, and a
future is one table key.
## Types
`Future<T>` is a future whose await delivers a `T`; `PromiseHandle` is a
future whose value has no stated type. They name the same value, so either
is accepted where the other is declared, and `f:await()` on a `Future<T>`
checks as a `T`. `f:andThen(fn)` checks as a `Future` of what `fn` returns (a
`Future<V>` it returns reads as `V`), `f:catch(fn)` as the value or what `fn`
returns, `finally`, `tap` and `timeout` as `f`'s own type, and
`future.all({ Future<T> })` as a `Future<{ T }>`.
# tween
Tween / easing library — smooth property interpolation with chaining,
timelines, and 30+ easing curves. This file is the public surface; the
implementation lives in three submodules: `core.module/` (lifecycle and
interpolation), `easing.module/` (easing curves and name lookup), and
`timeline.module/` (keyframe sequencer).
**Important**: callers MUST call `tween.update(dt)` every frame from a
component's `update` function. Without this, tweens will not advance.
## Exports
Property animation:
- `tween.to(entityId, property, target, durationOrOpts, easing?) -> Tween` — animate an entity property to a target value.
- `tween.fromTo(fromVal, toVal, durationOrOpts, easing?) -> Tween` — animate raw values via `onUpdate`.
- `tween.create(opts: TweenOpts) -> Tween` — create without auto-starting (for use in chains / timelines).
- `tween.update(dt: number)` — advance all active tweens; call every frame.
Global controls:
- `tween.setGlobalSpeed(speed: number)` / `tween.getGlobalSpeed() -> number`.
- `tween.cancelAll()`, `tween.cancelEntity(entityId)`.
- `tween.pauseAll()`, `tween.resumeAll()`.
- `tween.getActiveCount() -> number`.
Timelines and easing:
- `tween.timeline() -> Timeline` — keyframe-based orchestration.
- `tween.easing` — the easing namespace (re-export of the easing module).
- `tween.easings() -> { string }` — list of available easing names.
Types:
- `TweenOpts = { entityId?, property?, from?, to?, duration?, delay?, easing?, loops?, yoyo?, onStart?, onUpdate?, onComplete?, onCancel?, onLoop? }`
## Usage
```luau
local tween = require("@builtin::modules.tween")
-- Drive the tween system every frame from a component update:
function update(dt)
tween.update(dt)
end
-- Property tween on an entity:
tween.to("box", "position", { x = 0, y = 5, z = 0 }, {
duration = 1.0,
easing = "easeOutBounce",
onComplete = function() print("done") end,
})
-- Raw value tween via callback:
tween.fromTo(0, 1, 0.4, "easeInOutQuad"):andThen(
tween.create({ from = 1, to = 0, duration = 0.4, easing = "easeOutCubic" })
)
-- Timeline sequencer:
local tl = tween.timeline()
tl:add(0.0, tween.create({ entityId = e, property = "position", to = pos, duration = 1 }))
tl:add(0.5, tween.create({ entityId = e, property = "tint", to = color, duration = 0.3 }))
tl:play()
function update(dt)
tween.update(dt)
tl:update(dt)
end
```
## Notes
- Properties supported by `tween.to`: `"position"`, `"rotation"`,
`"scale"`, `"tint"`. See `core.module/init.luau` `ENTITY_PROPS` for
the full accessor map.
- Duration argument is permissive — pass a number (seconds) or a full
`TweenOpts` table with `duration`, `easing`, `delay`, `loops`,
`yoyo`, and the callback hooks.
- Tween / Timeline objects are returned as the underlying class
instances from the core / timeline submodules; the public `M.timeline()`
surface exposes them as plain `TimelineObj` and `TweenObj` opaque
handles to keep `--!global` registration unencumbered.
- The submodules are also independently `require`-able for callers
that need direct access to easing curves or timeline internals.
# frameStream Module
Public Luau surface over the `__framestream` Internal FFI namespace — an
image the GPU drew carried out to another program, frame after frame.
## Purpose
Wrap the raw `__framestream.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.frameStream` via the prelude. A session binds
one texture to one stream: make a render target the size you want to
emit, point a Camera at it, open a stream to whoever is consuming the
pixels, and attach the two. From then on the engine reads that texture
back every time the session is due a frame, packs the pixels, and writes
each frame to the stream. The image sits in GPU memory, where nothing
outside the renderer can reach it; the session is what puts it on the
wire.
The readback runs through a ring of staging buffers allocated once and
reused for the life of the session, so the frame the GPU is finishing is
read back while the next one renders and nothing waits on the render
thread. The write refuses rather than waits, so a consumer reading
slower than the engine renders falls behind by frames — visible on
`status().droppedBackpressure` — instead of holding the renderer back.
## Usage
```luau
-- A 128x32 render target, and a Camera that draws into it.
local rt = renderer.texture.create({ width = 128, height = 32 })
entity.spawn({
name = "panelCam",
position = { 0, 0, 6 },
components = {
Camera = { textureHandle = rt.guid, postProcessing = false },
},
})
-- Somewhere to send the pixels.
local out = task.await(stream.open("tcp://127.0.0.1:9000"))
-- Carry the camera's frames out at 30 fps.
local session = frameStream.attach(rt.guid, out, { fps = 30 })
-- Later.
local s = frameStream.status(session)
print(s.frames, s.dropped, s.achievedFps)
frameStream.detach(session)
stream.close(out)
```
## What reaches the stream
One frame's pixels, then the next frame's, with nothing between them. A
frame is `width * height * bytesPerPixel` bytes, rows top-first, and is
written in a single call — so a consumer that has counted its bytes
reads a whole frame or none of it, never half of one.
`format` picks the layout: `"rgb24"` (3 bytes per pixel, the default) or
`"rgba8"` (4) — a call naming any other format raises, naming both.
`flipY = true` writes the last texture row first, for a consumer whose
display is scanned bottom-up.
A consumer at the far end of a byte stream that can drop out and be
reopened usually wants more than the pixels — a magic to resynchronise
on, a length, a sequence number. That belongs to the consumer's own
protocol, so it is written by whoever speaks it rather than baked in
here.
## Framing the bytes yourself
To put a header of your own ahead of each frame, run the frames through
a `loopback` stream and write them on from there. The session fills the
loopback with whole frames; you drain one, prepend whatever your
consumer expects, and write the result to the real stream:
```luau
local FRAME = 128 * 32 * 3
local pixels = task.await(stream.open("loopback://panel", {
inboundCapacity = FRAME * 4,
outboundCapacity = FRAME * 4,
}))
local out = task.await(stream.open("tcp://127.0.0.1:9000"))
local session = frameStream.attach(rt.guid, pixels, { fps = 30 })
local counter = 0
task.spawn(function()
while true do
local frame = stream.read(pixels, FRAME)
if #frame == FRAME then
stream.write(out, myHeader(counter) .. frame)
counter += 1
end
task.wait()
end
end)
```
That costs one in-memory copy per frame and keeps the protocol in
content, where it can change without an engine build. Attaching straight
to the destination stream skips the copy, and is the path to take when
the consumer wants the pixels bare.
## Rate
`fps` caps how often a frame is taken and is independent of the rate the
engine renders at: a session at `fps = 30` in an engine running at 144
takes every fifth frame or so, and one at `fps = 30` in an engine
running at 20 takes every frame it can. `status().achievedFps` is what
it reached — compare it against `requestedFps` to tell a display that is
running slow from one that is running as asked.
## Reading the status
`frameStream.status()` separates the three ways a frame fails to arrive,
because they call for different fixes:
- **`droppedBackpressure`** — the consumer is reading slower than the
session is producing. Either the consumer is too slow, or the stream's
`outboundCapacity` is too small to absorb its jitter.
- **`stalledReadbacks`** — the frame came due while every staging buffer
still held a copy on its way from the GPU. The session is asking for
frames faster than the GPU is handing them back.
- **`lastOutcome == "tooLarge"`** — a frame is bigger than the stream's
whole outbound capacity, so every frame of that size will be refused
too. Open the stream with an `outboundCapacity` that holds one.
## Which frame a stream holds
A frame is copied when it comes due and reaches the stream once its copy
has come back from the GPU, so how many frames a stream holds at a given
moment depends on how fast those copies come back. Two sessions on one
texture can therefore hold different numbers of frames when they are
read, the newest frame of one showing a later image than the newest of
the other. `status().lastCopyFrame` names the engine frame, in
`time.frameCount()` numbering, that the copy of the newest accepted frame
was taken on. Every copy one engine frame takes of a texture holds the
same image, so read it in the same step as draining the stream, and two
sessions whose readings agree hold the same image as their last frame.
Two different readings can still name one image: an engine frame on
which nothing drew into the texture copies the image it already held.
## Platforms
Frame egress runs on native and wasm alike: the readback is submitted
and polled without blocking on either, and the packing is plain byte
work. What differs between them is which transports a stream
can be opened over — `stream.transports()` is the probe for that, and
`tcp` names its wasm absence there.
## Exports
- `frameStream.attach(texture, stream, opts?) -> string?, string?` — session handle, or nil + reason.
- `frameStream.detach(handle) -> boolean`
- `frameStream.status(handle) -> FrameStreamStatus?` — `nil` when handle names no live session.
- `frameStream.list() -> { string }`
# modules.api.engine.dirty_hot_reload
Picks up dirty-overlay changes from disk while a scene is loaded in
edit mode, applies them to the live entities, and keeps the in-memory
representation in lockstep with `scene_dirty/` files. Pairs with
`scene_saver` (writes deltas) + `scene_loader` (composes canonical +
overlay at load time).
## Parents
A record's `parent` names the entity it stands under: the entity whose id is
that text, else the entity whose display name is exactly that text. A `*` or
`?` in it is a character of the name, never a pattern.
A record whose parent no entity provides waits. An entity that does not stand
yet is not built, one that already stands keeps its state, the layer logs the
record once, and `debugState(guid).waiting` maps its id to the parent it
names. While a record waits, the scene saver leaves it as it stands rather
than writing a standing entity's older state over it, until an author edits
that entity, which the saver then records as it stands. When a record builds
an entity, the records waiting on that entity's id or display name are built
under it, so a child record that arrives before its parent's record lands
where a load of both places it. Each waiting record is built as its overlay
file states it at that moment, so a record rewritten while it waited,
including by this session's own saver, builds from its current bytes. A load
gives the same account of a record whose parent stays missing: the loader
abandons it with `parentMissing`.
# video Module
Public Luau surface over the `__video` Internal FFI namespace — video
playback via render-target-backed players.
## Purpose
Wrap the raw `__video.*` FFI namespace (backed by `zero_video`) in a
typed Luau table that gets auto-injected as `_G.video` via the
prelude. Players are backed by standard render targets — the handle
returned by `video.create` is an `"rt:video_N"` string usable anywhere
a render target works (materials, UI, post-process inputs).
## Usage
```luau
-- Stream a video onto a material
local rt = video.create("http://example.com/clip.mp4", {
loop = true, autoplay = true, rate = 1.0,
})
material.setTexture(myMat, "baseColor", rt)
-- Transport
video.pause(rt); video.seek(rt, 30.5); video.play(rt)
-- Inspect
local info = video.getInfo(rt)
print(info.width, info.height, info.currentTime, "/", info.duration)
-- Ask whether this host decodes the stream before waiting on a frame.
-- `codecSupported` is nil until the answer arrives, false where the host has
-- no decoder for `info.codec`, and then `info.state` is `"unsupported"`.
if info.codecSupported == false then
print(info.error)
end
-- The decoder the stream plays through: "mediacodec" (the device's own) on
-- Android, "webcodecs" in a browser, "mediafoundation" on Windows and
-- "openh264" on Linux and macOS.
print(info.decoder)
-- Frames handed to the texture against frames the playback clock reached,
-- and how many samples decoded on the frame thread (a native stream decodes
-- on a thread of its own; a browser stream in the browser's decoder).
print(info.framesPresented, "/", info.framesExpected, info.frameThreadDecodes)
video.destroy(rt)
```
## Exports
- `video.create(url, options?) -> rtHandle`
- `video.play(handle)` / `video.pause(handle)` / `video.stop(handle)`
- `video.seek(handle, time)`
- `video.setRate(handle, rate)` / `video.setLoop(handle, loop)`
- `video.getInfo(handle) -> VideoInfo?`
- `video.destroy(handle)`
# yaml.module
YAML decode + encode for authored engine content. Pure Luau, no engine
dependencies — a general parsing library, not data-system plumbing.
```luau
local Yaml = require("@builtin::modules.yaml")
local doc = Yaml.decode(vfs.read(path))
vfs.write(path, Yaml.encode(doc))
```
## Supported subset
- Block mappings (`key: value`) and block sequences (`- item`), nested
to any depth.
- Compact sequence-of-mapping entries (`- path: x` / ` kind: y`).
- Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line.
- Plain scalars with type inference: `~` / `null` → nil, `true` /
`false` → boolean, numeric literals → number, everything else →
string.
- Single- and double-quoted strings (`''` escapes a literal quote
inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a
double-quoted one). A quote opens a quoted scalar where a scalar
begins — after `key:`, after a `- ` entry marker, or inside a flow
collection — so a plain scalar carries an apostrophe as data
(`note: the world's rules`). Quoted keys are read in flow mappings.
- `#` comments — honored outside quotes, so a `#` inside a quoted
string is kept as data.
- Literal (`|`) and folded (`>`) block scalars, with a chomping
indicator (`-` strips the final newline, `+` keeps every trailing
blank line, none keeps one newline) and an indentation indicator
(`1`-`9`: the content's indent past the parent's), in either order
(`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text:
quotes (balanced or not), `#`, `key: value` and `---` inside it are
data.
- An optional leading `---` document marker.
## Loud-error contract
Constructs outside the subset above raise instead of misparsing:
anchors/aliases (`&`, `*`), tags (`!`), directives (`%`),
multi-document streams (a second `---`), a block-scalar header
it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and
block-scalar bodies). Every error carries the offending line number
(`yaml: line N: ...`), so a bad config points straight at the line to
fix.
Tab indentation is rejected everywhere — including block-scalar body
lines whose leading whitespace contains a tab. A tab after the first
non-space character of a line is content and passes through.
## API
- `Yaml.decode(text: string): any` — decode a YAML document into a
Luau value (table, scalar, or nil for an empty document). Raises on
malformed input or an unsupported construct.
- `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as
`decode` does, and report whether the text carries a comment by the
decoder's own rule: a `#` at a line's start or after whitespace, outside
a quoted scalar and outside a block scalar. Re-encoding the value drops
such comments, so an editor that writes a document back reads this first.
- `Yaml.encode(value: table): string` — encode a Luau table as YAML
(block style, two-space indent, alphabetically sorted keys). Raises
on values YAML can't represent (functions, userdata, non-string
mapping keys).
A top-level empty table encodes to an empty document, which decodes
back to `nil` (the YAML empty-document ambiguity).
# debug_frustum
The "frustum" provider for `@builtin::modules.debugViz`: appends one cyan
wireframe frustum per scene Camera into the shared debug-visualization batch,
every edit-mode tick.
```lua
debugViz.registerProvider("frustum", require("@builtin::modules.debug_frustum").tick)
```
`DebugViz.component` registers this provider automatically — attach it to one
entity to draw every enabled camera's view frustum alongside whatever other
providers are registered.
## How it works
`tick(emit)` queries every entity carrying a Camera and, for each enabled one,
builds its 8 near/far corners in the camera's local space:
- half-height at a given distance is `tan(fov / 2) * distance`; half-width is
`half-height * aspect`.
- the camera looks down its local **-Z** axis
(`entity(id).transform.forward` is documented as "local -Z axis in world
space"), so the near/far planes sit at local `z = -near` / `z = -far`.
- each corner is `position + forward * dist + right * (±halfWidth) + up *
(±halfHeight)`, using the entity's world position and world-space
forward/right/up axes — no separate quaternion math needed.
`Camera` has no `aspect` field, so the aspect ratio is read live from
`getViewportSize()` (the window's real aspect, matching what the viewport
camera sees), falling back to a 16:9 default if the viewport size isn't
readable. The 12 edges (4 near, 4 far, 4 connecting) are appended via
`emit.line`.
## API
- `debug_frustum.tick(emit)` — append one wireframe frustum per enabled scene
camera into the shared batch.
# restirLighting
Direct light from many small sources at a cost that does not grow with how many
there are.
A shading pass that loops every light pays for every light at every pixel, which
is why the number of lights has to be capped. Resampled importance sampling
breaks that link: each pixel draws a few candidates, keeps ONE of them with a
probability proportional to what it would contribute, and carries a weight that
makes the survivor stand for the whole set. What it keeps is then reused — by its
neighbours this frame, and by itself on the next one — so the set a pixel
effectively samples keeps growing while the number of candidates it draws stays
where you put it.
A cave of glowing crystals, a street of practicals, a control room of indicator
lamps: hundreds of sources, and each pixel looks at about a dozen.
## Using it
Put an `EmissiveSource` on the geometry that glows:
```lua
local id = entity.spawn("crystal", { position = { 2, 1, 0 } }).id
entity(id).component.add("EmissiveSource", {
color = { 0.3, 0.8, 1.0 },
intensity = 8.0,
radius = 6.0,
size = 0.4,
})
```
Or register sources from a script, which is how a generated scene does it:
```lua
local restir = require("@builtin::systems.restirLighting.restirLighting")
for i = 1, 400 do
restir.set(`lamp{i}`, {
position = { math.random() * 60 - 30, 1.5, math.random() * 60 - 30 },
color = { math.random(), math.random(), math.random() },
intensity = 4.0,
radius = 5.0,
})
end
```
The pass starts with the first source and stops with the last. Settings are on
`restir.configure`, or on a `ResampledLighting` component for a scene to author:
```lua
restir.configure({ candidates = 16, spatialSamples = 6 })
```
## What a pixel pays
`candidates + spatialSamples + 1` evaluations, reported by
`restir.perPixelCost()`. None of those terms is the source count.
The estimate is formed on a grid of one cell per 2x2 pixels (`resolution =
"full"` gives every pixel its own cell), across four passes:
| Pass | Runs over | Does |
|---|---|---|
| `restir_sample` | grid cells | draws `candidates` sources at random, resamples to one, merges the cell's own history |
| `restir_spatial` | grid cells | borrows from `spatialSamples` neighbours, each evaluated against this cell's surface |
| `restir_resolve` | pixels | shades the chosen source with the pixel's own normal, roughness and albedo |
| `restir_denoise` | pixels | averages that light over the cells around the pixel and composites it |
Which source to look at is a low-frequency decision a cell of pixels can share.
What the surface does with it is not, and is computed per pixel.
One source per cell is correct on average and different from its neighbour,
which is the grain a single sample carries. `restir_denoise` averages across the
cells around a pixel, weighing each by how nearly its surface is this one, so the
estimate keeps its value and loses its variance.
`mode = "reference"` replaces the reservoir lookup with a loop over every
registered source at every pixel. That is the picture the resampled mode is
estimating and the cost it is measured against — the same shading, the same
filter and the same composite, so the two are comparable directly.
## Temporal reuse
A cell keeps its reservoir across frames and merges it with the fresh
candidates, so a good find keeps paying after the frame that made it. The stored
world position is what says the cell is still looking at the same surface; a
camera move or an occluder passing in front fails that test and the history is
dropped rather than smeared.
`historyCap` bounds how many candidates the history is allowed to stand for.
Without it a converged cell would outvote every new candidate forever and a
lighting change would never work its way out. At the default of 20 a change is
absorbed over roughly twenty frames.
Removing a source, or turning its `intensity` down to 0, releases it; the pass
stops with the last one.
## Where it sits
Sources registered here are additional to the lights the engine holds rows for.
The passes run in `afterLighting` at orders 80-84 and add to the scene as it was
drawn, reading position, normal, albedo and metallic-roughness back out of the
G-buffer.
A source lights every surface within `radius` that faces it, along the straight
line between them.
## One frame, several targets
A render feature's `render` runs once a frame, and the passes it enqueues run
once per render target — the window, an offscreen capture, a camera rendering to
a texture. Each pass therefore reads the frame size out of the textures it is
handed and works out its own cell grid, so every target resamples at its own
resolution. A reservoir carries the grid width it was written under, which is
what stops one target's history being read as another's.
The reservoir buffers are sized to the widest grid any target has asked for. A
target wider than they have yet been sized for reports the grid it needed, and
the frame after that covers it.
## Reading what it did
`restir.stats()` returns the counters the passes keep on the GPU for the most
recent frame a read-back has landed for, carrying that frame's number so a
repeated read is distinguishable from a fresh one. `meanWeight` is counted in
sixteenths with each cell capped at 16 so the total fits a 32-bit counter;
`peakWeight` alongside it is exact to a thousandth, and is where an estimator
that has come loose shows first.
# MaterialAuthor
Stand up new materials and textures fast — the go-to surface for making materials at design time, each in one call instead of a hand-rolled asset-create-and-wire dance.
Every tool writes a source material asset and hands back a live `AssetRef<material>` you can apply straight to a Model. Wrap a texture (a proxy, a `.texture` asset, or an image path) into a new material with its PBR slot inferred from the texture name; make a flat-colour material from an RGB(A) value; clone an existing material under a new name with property or texture overrides; or scan a folder of textures — loose images and `.texture` assets — inferring each one's slot from its name and composing them into a single material. It pairs with the SVG → texture importer: drop a `.svg`, get a `.texture`, wrap it.
**This is authoring, not runtime.** Every tool creates source assets, which is a design-time action — never call it from gameplay code (components, controllers, per-frame updates, spawn logic). At runtime you consume an already-authored material by name or ref through the lower-level `Material` surface (create / apply / get / set), which is the gameplay-safe layer this one is built on. Reach here to *make* materials; reach for `Material` to *apply and tweak* them.
## Material properties
Beyond the keys a tool reads itself (`name`, `shader`, `overwrite`, and `slot` on `fromTexture`), every option names a property of the shader the material is authored against — so anything `pbr` declares is reachable in one call: `roughness`, `metallic`, `clearcoat`, `transmission`, `anisotropy`, `ior`, `uv_scale`, and the texture slots. A custom shader's own properties work the same way, since the vocabulary is read from the shader.
Spell a property in `snake_case` or `camelCase` (`uv_scale` or `uvScale`); `tiling` names `uv_scale` and `color` names `base_color`. A single number fills a vector property's components, so `tiling = 300` tiles 300×300. An option the shader doesn't declare is refused, naming the closest accepted spelling — the material is not written.
```lua
tools.use("MaterialAuthor", "fromTexture", "cliff_diff.texture",
{ name = "Cliff", tiling = 300, roughness = 0.9 })
```
## Slot inference
When no slot is given, the texture stem picks the PBR slot: `albedo` / `basecolor` / `base_color` / `diffuse` / `col` → base colour; `normal` / `nrm` → normal; `roughness` / `metallic` / `metalness` / `metallic_roughness` / `orm` → roughness-metallic; `emissive` / `emission` / `emit` → emissive; `ao` / `occlusion` → occlusion. Pass an explicit slot to override.
# Field edits
Scene authoring uses FieldEdits to keep structured field intent separate from generated data. Each edit carries a path, the value that field was based on, and the authored value, with explicit presence flags for additions and removals.
```lua
local Fields = require("@builtin::modules.fieldEdits")
local base = {position={0,0,0}, light={intensity=1}}
local visible = {position={2,0,0}, light={intensity=1}}
local edits = Fields.diff(base, visible)
local rebuilt = Fields.compose({position={0,0,0}, light={intensity=3}}, edits)
assert(not rebuilt.blocked)
assert(rebuilt.value.position[1] == 2)
assert(rebuilt.value.light.intensity == 3)
```
- `copy(value)` validates and copies structured data without sharing mutable tables.
- `diff(before, after)` creates deterministic field edits. Objects merge by string key; arrays and asset references are atomic values.
- `compose(generated, edits)` applies authored values and reports divergence from their stored baseline. Missing parents, missing edited targets and conflicting root additions block the result. Satisfied paths identify intent the generated value already matches.
- `update(generated, previous, current, edits)` records a new authoring operation while retaining existing baselines and satisfied intent. An addition followed by its removal cancels that addition.
- `updateChanges(generated, current, changes, edits)` records original observed changes against their merged visible result. A change already satisfied by the current generated value remains an authored intent for subsequent builds.
- `keep(generated, edits, paths?)` acknowledges reviewed generated changes while retaining the authored values at the selected exact paths.
Inputs are copied, edit paths are non-overlapping dense arrays of strings, and values are finite serializable data with bounded nesting. Scene-level hierarchy, reference and component validation belongs to the scene composer consuming these field results.
# material_records
The material GPU records this session has released and nothing has filed again.
A `.material` asset files its GPU record at its point of use — `matRef:handle()`
— and memoises the handle it filed on the ref's runtime, so a second bind of the
same material costs a table read where the first cost a parse and an upload.
That memo names a record the renderer's registry holds, and
`renderer.material.destroy` takes the record away while the asset and its memo
stand. The asset is what files the next record, so it has to know which names
that applies to.
This set is that knowledge: a release puts the key in, filing a record under the
key takes it out, and the point of use reads it for the cost of one table index.
Written by `renderer.material.destroy` and `renderer.material.create`; read by
the `.material` assetType's `handle()`.
## API
```luau
local MaterialRecords = require("modules.material_records")
-- A point of use holding a memo asks whether the record it names still stands.
if MaterialRecords.released[identity] ~= nil then
-- The record is gone: file another one, which takes the mark off.
end
MaterialRecords.noteReleased(key) -- the record under `key` has been released
MaterialRecords.noteFiled(key) -- a record stands under `key` again
```
## Lifetime
The set lives in the session store, so it holds for as long as the GPU records
it answers for: a VM reload leaves those records standing and leaves this
standing with them, and both die with the engine process.
# enum_values (module)
The `enum` field-constraint validator. Registers itself with
`field_constraints.module`'s registry on load so any component field
carrying `constraint = { kind = "enum", values = { ... } }` — which is
what `Field.enum` emits — is checked against it.
## What it does
Given a field's written value and its constraint:
1. Passes `nil` — an enum field may be left unset.
2. Rejects a constraint carrying no members, since there is nothing to
check against.
3. Rejects a non-string value, naming the members and the type it got.
4. Answers whether the value is one of `constraint.values`.
Every rejection lists the whole member set, so the message tells the
caller what they may write instead of only what they may not.
## Where the members come from
`Field.enum(values, default, mode)` validates the member list at
construction: the members must be non-empty, distinct strings, and a
non-nil default must be one of them. A field whose members are wrong is
therefore a load-time error rather than a runtime surprise, and this
validator only ever sees a well-formed set.
The engine carries `constraint` verbatim and never reads inside it, so
the member list lives entirely in Luau.
## Exports
- `M.check(value, constraint) -> ok, reason?` — the validator function,
also registered under the `enum` kind.
# api
Discover the engine's own documentation when you don't yet know the path — browse the docs tree and search it by keyword.
Browse the documentation under `/zero/docs`: with no argument it lists the top-level categories (api, tools, guides, components), a partial path lists a directory's entries, and a full path returns the document. Searching splits the query into words and matches a document when every word appears in its path or its body, across `/zero/docs` and the `.guide` assets (the prose guides), so a concept finds the docs that describe it and not only docs named after it. When you already know the path, reading it directly is quicker; these are for finding your way when you don't.
# asset_tag (module)
The `assetTag` field-constraint validator. Registers itself with
`field_constraints.module`'s registry on load so any component field
carrying `constraint = { kind = "assetTag", tag = ... }` — which is
exactly what `Field.taggedRef` emits — is checked against it.
## What it does
Given a field's written value and its constraint:
1. Passes `nil` — an unset slot holds nothing to check.
2. Reads the value's identity — a bare string, or a table's `__ref` /
`guid` / `identity` / `name`.
3. Resolves it as an asset of any type (`asset.resolve(identity)`), since
the tag is the whole gate.
4. Answers `asset.has_tag(identity, constraint.tag)`.
Acceptance rides on the tag rather than the asset's type, so an asset
becomes assignable to a tagged slot the moment it is tagged — no edit to
the field or to anything that reads it.
A rejection names the tag the slot wants, the tags the asset carries
instead, and the `asset.list({ fields = { tags = ... } })` call that
enumerates what would fit, so the message carries its own next step.
## Exports
- `M.check(value, constraint) -> ok, reason?` — the validator function,
also registered under the `assetTag` kind.
# world_sync
Grafts sync-durability status and per-item conflict resolution onto the
`world` namespace. In a live world every `/source` write is synced to
the backend; a write that has not yet reached the backend is a *pending*
write, and a write that collides with a change another collaborator made
since you last saw the path is a *conflict*. This module surfaces both
and lets you resolve conflicts one path at a time.
## `world.syncStatus()`
Returns a snapshot of the world's sync state:
```lua
local s = world.syncStatus()
-- s.subscribed : bool: attached to a live world
-- s.content_synced : bool: incoming: the world's content, and every change to it the stream delivered, is applied to this client
-- s.outgoing_synced : bool: outgoing: every /source change this session made reached the world
-- s.uploads_outstanding : number: upload jobs queued, in flight, or held for another attempt
-- s.uploads_in_flight : number: the outstanding upload jobs a flush has taken and is carrying to the world
-- s.progress : { applied: number, expected: number?, unapplied: number }
-- s.pending_writes : number: local /source writes and removals not yet round-tripped whose durable record stored
-- s.unrecorded_writes : { string }: owed /source paths whose durable record did not store, which a restart loses
-- s.owed_paths : { string }: /source paths written or removed that the manifest does not reflect yet (the list vfs.pendingWrites() returns)
-- s.unsaved_writes : { string }: /source paths whose write or removal the server never took
-- s.held_uploads : { { path, reason } }: owed changes whose upload failed and is being tried again
-- s.uploads_abandoned : number — uploads the queue stopped carrying
-- s.conflicts : { { path, base_sha, local_sha, backend_sha, isBinary } }
```
Content sync runs in two directions, and the status answers each apart.
`content_synced` is the incoming direction: the world's content has been
applied to this client, and so has every change to it that the world's
stream has delivered since. A survey uses it to tell "still syncing" from
"empty world": a freshly attached session reads `content_synced = false`
until the backend content has landed. Later, while changes other sessions
made are still being applied here, it reads `false` again, and
`progress.unapplied` counts the delivered changes still waiting; once it
reads `true` with `outgoing_synced` true as well, `/source` here lists what
the world holds. It reads nothing about this session's own changes
reaching the world.
`outgoing_synced` is the outgoing direction: every `/source` change this
session made has reached the world. It reads `false` while any write or
removal is queued, uploading, held for another attempt, not yet reflected
by the manifest, kept in a durable record (`pending_writes`,
`unrecorded_writes`, a conflict among them), or refused by the server. It
is the field that answers "is my work saved?". Both booleans read `false`
while no world is subscribed.
`uploads_outstanding` counts the upload jobs `outgoing_synced` is still
waiting on, each once, and `uploads_in_flight` the ones among them a flush
has taken and is carrying to the world: a flush runs apart from the frame
loop, so those are sent without waiting for a frame, while the rest wait
for a frame, a blob transfer or another attempt.
`pending_writes` moves as the queue drains, so it reads the same for a
queue working through a backlog and for one that has given content up.
`unsaved_writes` and `uploads_abandoned` separate them: the first names
the `/source` paths whose bytes are on this client only, the second counts
the uploads the queue stopped carrying after they failed on it repeatedly
while the connection reported itself live. A path listed there stays on
this client until another session's reconcile carries its durable record.
`held_uploads` names the owed changes whose last upload attempt failed and
went back to the queue, each with the reason that attempt gave: a blob
transfer that ran past its deadline, a refused connection. The queue tries
each again on its own schedule until it lands or is given up on. A held
upload holds nothing else up: a stage or commit of other paths goes ahead,
and a bulk stage passes over it. A call that names the held path waits on
it and, when it does not land, reports the path and the reason. Removing
the path ends the hold, since the removal is what the path owes from then
on.
`unrecorded_writes` names the owed `/source` paths whose durable record
this machine could not store, because the pending-write store or the local
blob store could not be written. This session still carries them to the
world; a restart before they arrive loses them. `pending_writes` counts the
owed records that did store, so it leaves these out.
## `world.resolveConflict(path, mode, content?)`
Resolves one path this session owes the world: a conflicted one, or one
whose write or removal the server refused or the queue gave up on (listed
in `unsaved_writes`). Waiting never carries such a change, and while one
is held a `world.swap` or `world.checkout` away from the world refuses,
naming it; `"discard"` drops it, `"take-local"` makes it again. `mode` is
one of:
- `"merge"` — for text, runs a 3-way merge of the common ancestor, your
bytes, and the current backend bytes, and returns `{ merged, clean }`.
A clean merge produces ready-to-apply text; a conflicted merge returns
the text with `<<<<<<<` / `=======` / `>>>>>>>` markers to resolve.
Merge is unavailable for binary content or a path with no common
ancestor.
- `"apply"` — writes `content` (the finalized bytes you pass) to the
path and clears the conflict.
- `"take-local"` — keeps your bytes.
- `"take-backend"` — keeps the backend's bytes.
- `"discard"` — drops your pending bytes, keeping the backend's.
Retained conflict bytes are also readable under
`/zero/runtime/sync/conflicts/`, so you can inspect a conflict before
choosing how to resolve it.
# layers
Top-level scene-management global + Scene proxy. § 17 step 9 of
`docs/plans/2026-05-01-player-camera-unification.md`. Renamed from the
legacy `scene.*` global to match `/runtime/layers/` and to give
scene-management state (active root, additives, callback registries)
a single anchor distinct from per-scene authoring.
## Global surface
| Symbol | Type | Notes |
|---|---|---|
| `layers.active` | `Scene \| nil` | Current root non-additive scene as a proxy. Live read; updates on every load/unload. |
| `layers.list()` | `{ Scene }` | Every loaded scene (root + additives) as proxies. |
| `layers.find(ref)` | `Scene \| nil` | Lookup by `AssetRef<scene>` or layer-id string. |
| `layers.is_loaded(ref)` | boolean | |
| `layers.load(ref, opts?)` | — | Loads ref. `opts.additive = true` layers on top; default = non-additive (replaces root). |
| `layers.unload(ref?)` | — | Unloads ref; nil = active root. |
| `layers.reload(ref?)` | — | Equivalent to unload + load with same ref. |
| `layers.onLoad(cb) -> handle` | function | Subscribe to any scene-load event. Returns handle for `offLoad`. |
| `layers.offLoad(handle)` | function | |
| `layers.onUnload(cb) -> handle` / `offUnload(h)` | function | Same shape for unload events. |
| `layers.observe()` | `SceneObservation` | What every load did and what each loaded scene costs, in one read. |
| `layers.lastLoad()` | `SceneLoadReport \| nil` | The last load's report; nil when nothing has loaded. |
| `layers.lastUnload()` | `SceneUnloadReport \| nil` | The last unload's, under the name the layer was loaded with. |
| `layers.loadHistory()` | `{ SceneLoadReport }` | The completed load reports still held, oldest first. |
| `layers.problems(ref?)` | `{ SceneLoadFailure }` | What a layer failed to produce, and why. |
| `layers.whyPartial(ref?)` | `(reason?, detail?)` | The nearest cause a layer is not whole, from a closed set. |
| `layers.inventory()` | `{ SceneLayerInventory }` | What the engine attributes to each loaded layer. |
| `layers.cost()` | `{ SceneLayerCost }` | Each layer's per-frame entrypoint tick, summed across the window. |
| `layers.resetCostWindow()` | — | Open a new cost window. |
## Scene proxy surface
A `Scene` proxy is a sealed table with fields and `:method` callables.
| Field / method | Notes |
|---|---|
| `s.asset` | `AssetRef<scene>` |
| `s.name`, `s.path` | informational (logging, debug) |
| `s.guid` | the scene asset's guid — the layer's identity |
| `s.sceneIdentity` | the identity of the scene asset the layer was loaded from (e.g. `@builtin::scenes.test_arena`), whichever VM loaded it |
| `s.additive` | boolean — additive overlay vs root scene |
| `s.parent`, `s.children` | additive ownership chain |
| `s:root()` | walks `.parent` to the non-additive root; returns self for roots |
| `s.players`, `s.camera` | populated by §17 step 10 (player + camera spawners) |
| `s.entrypoint` | `AssetRef<script> \| nil` |
| `s.visible` | boolean — read via field, toggle via `s:set_visible(b)` |
| `s.state` | `"loading"` / `"loaded"` / `"ready"` / `"partial"` / `"unloading"` — the layer's lifecycle state. Both `"ready"` and `"partial"` are terminal: the load has settled. |
| `s.ready`, `s.loaded` | booleans in lock-step with `state`. `ready` is true once the layer has settled, in either terminal state — it is the flag to wait on. |
| `s.ok` | boolean — whether everything the scene declared was produced and the layer has run clean since. False whenever `state` is `"partial"`, including when the tick starts raising long after the load settled. |
| `s.failures` | `{ SceneLoadFailure }` — every distinct failure the load and the layer's per-frame tick produced, each with the `count` of how often it repeated. |
| `s:unload()` | unload this scene; additives use `layers.unload(layerId)`, roots use `layers.active:reload()` |
| `s:reload()` | unload + reload same ref |
| `s:set_visible(b)` | show/hide without unloading |
| `s:load_additive(ref)` | load a sibling additive overlay; returns the new proxy |
## Example
```lua
-- Switch root scene
layers.load(asset.ref("@builtin::scenes.baseline_visual"))
-- Subscribe to all loads
local h = layers.onLoad(function(scene)
print("loaded:", scene.name)
end)
-- Layer an HUD overlay on top
layers.load(asset.ref("@builtin::scenes.hud"), { additive = true })
-- Iterate every loaded scene
for _, scn in ipairs(layers.list()) do
print(scn.name, scn.additive and "(additive)" or "(root)")
end
layers.unload() -- unload the active root
layers.offLoad(h)
```
## What a load did, and what a scene costs
Every load writes one record at its own completion point; the readings below
compose that record, so a caller that did not make the load can still ask what
it did. A load that produced failures settles into `"partial"` rather than
`"ready"`, and names the nearest cause from a closed set: `loaderRaised`,
`entrypointCompileFailed`, `entrypointBodyRaised`, `entrypointRaised`,
`buildRaised`, `entityFailed`, `parentMissing`, `parentRefused`,
`parentAbandoned`, `componentUnresolved`, `componentRefused`,
`subscriberRaised`, `updateRaised`.
```lua
layers.load(asset.ref("scenes.arena", "scene"))
-- Did it come up whole?
if not layers.active.ok then
local reason, detail = layers.whyPartial()
print(reason, detail)
for _, f in layers.problems() do
-- `count` rises when the same failure happens again, so a per-frame
-- tick that keeps raising stays one line.
print(f.phase, f.reason, f.entity, f.component, f.hook, f.count)
end
end
-- What did the swap do?
local r = layers.lastLoad()
print(r.name, r.outcome, r.durationMs)
print("replaced", r.replaced and r.replaced.name) -- the root that went
print("cascaded", #r.cascaded) -- the overlays with it
print(r.entities.added, "arrived,", r.entities.removed, "left")
print(r.phases.teardown, r.phases.instantiate, r.phases.settle)
-- Which loaded scene is expensive? `totalMs` is a SUM across the window, so
-- reset it first and read `avgMs` for the per-tick figure.
layers.resetCostWindow()
task.wait(1)
for _, c in layers.cost() do
print(c.name, c.avgMs, "ms/tick over", c.calls, "ticks")
end
-- What does each layer hold, and what does no layer claim?
for _, l in layers.inventory() do print(l.name, l.entities, l.ok) end
print(layers.observe().totals.unattributed)
```
The `scene` toolbox carries the same two readings as `scene.observe` and
`scene.whyPartial`.
## Authoring surface
`layers.*` is the sole public scene-management surface. It accepts
AssetRefs (not paths), drives a callback registry, and constructs
Scene proxies that carry players / camera / hooks. The previous
`scene.*` global has been removed — its low-level FFI bindings now
live behind `layers.*` and the Scene proxy methods.
# renderError
Shared "this render is broken" marker. `visibleError(entityId)` swaps an entity
to the builtin ERROR text model + error material, so a failed render reads as an
unmistakable 3D "ERROR" sign on screen instead of empty pixels — empty silently
reads as "fine" and a broken object gets mistaken for working.
Every render component (built-in `Model` / `SkinnedModel`, or a user-authored
one) calls this, so the error model is defined in one place: change it here and
every render component updates.
# preset
A preset holds typed values for one declarer's settings schema: an
assetType's, an importer's, a component's, or any asset that declares its
own settings. `preset.capture` saves the settings something has now,
`preset.apply` writes a preset's values into something its target governs,
`preset.values` reads them checked against the target's current schema, and
`preset.setValues` replaces them, checked first. Exposed as the `preset`
global via `--!global preset`.
A preset's `preset.yaml` names its target as a guid envelope,
`target: { __ref: <guid>, type: <type>, name: <name> }`, which the
preset's `.refs` pins by guid with the target's checksum. A target written
as an identity string is accepted on read, resolves by identity, reads as
unpinned, and is rewritten as the envelope on the preset's next local
edit.
## Exports
- `preset.values(source: AssetRef<preset>) -> ({ [string]: any }, Report)` — the values that pass the target's current schema, and a report naming every one that does not.
- `preset.apply(source: AssetRef<preset>, into: AssetRef | ComponentTarget) -> ApplyResult` — write the valid values into an asset the target governs, or into a component on an entity whose component is the target. Struct groups merge field by field. Raises when another declarer governs `into`.
- `preset.capture(from: AssetRef | ComponentTarget, name: string, opts?: CaptureOpts) -> AssetRef<preset>` — save an asset's settings, or a component's live values on an entity, as a new preset targeting the declarer that governs them. A bare name lands in `/source/presets/`; an absolute `.preset` path lands where it says.
- `preset.setValues(source: AssetRef<preset>, values: { [string]: any })` — replace the whole values table; any violation refuses the write, naming every one.
- `preset.defaults() -> { DefaultRow }` — the world's Preset Manager rows, in order, each resolved with its problems.
- `preset.setDefaults(rows: { DefaultRowInput })` — replace every row; every row is checked first and any problem refuses the write, naming every one.
- `preset.addDefault(source: AssetRef<preset>, opts?: { filter: string?, at: number? }) -> number` — add a row for the declarer the preset targets; returns its index.
- `preset.removeDefault(index: number)` — remove one row, keeping every other row as written.
- `preset.defaultFor(declarer: AssetRef | string, path: string) -> ({ [string]: any }?, Match?)` — the values a new thing at `path` would take from the rows, and the row that gives them.
Types:
- `ComponentTarget = { entity: string, component: string }` — a component on an entity.
- `Report = { format: string, target: string, targetGuid: string?, pinned: boolean, targetChanged: boolean, rejected: { Violation } }` — `target` is the target's identity; `pinned` is true when `.refs` pins the target's guid; `targetChanged` is true while the pinned checksum differs from the target's current one.
- `Violation = { path: string, message: string }`
- `ApplyResult = { applied: { string }, rejected: { Violation }, targetChanged: boolean }`
- `CaptureOpts = { overwrite: boolean? }` — `overwrite = true` re-authors an existing preset, keeping its guid.
- `DefaultRowInput = { preset: any, target: any?, filter: string? }` — a preset, its declarer (the preset's own target when omitted) and a filter (empty matches everything).
- `DefaultRow = { index, target, preset, filter, targetGuid, presetGuid, targetName, presetName, problems }`
- `Match = { index, target, preset, path, rejected, problem? }` — the row a creation took and the path it read.
## Usage
```luau
-- Capture a texture's settings, then apply them to another texture
local p = preset.capture("hero_sprite", "pixel_art")
preset.apply(p, "enemy_sprite")
-- Apply a component preset to a component on an entity
preset.apply("synty", { entity = id, component = "Locomotion" })
-- Capture a component's live values
local tint = preset.capture({ entity = id, component = "Model" }, "red_tint")
-- Read the values and what the target rejects
local values, report = preset.values("pixel_art")
for _, v in ipairs(report.rejected) do print(v.path, v.message) end
-- Replace the values
preset.setValues("pixel_art", { filter = "nearest", generateMipmaps = false })
```
## Notes
- Every read re-checks the values against the target's current schema, so a value a later schema drops or retypes is reported by path rather than applied.
- `asset.create("preset", name, { target = <identity or guid>, values = { ... } })` authors a preset directly, with the same checks as `preset.capture`.
- The Preset Manager rows are documented in `preset.defaults`; the filter grammar in `preset.glob`.
- Submodules: `preset.document` (the `preset.yaml` format), `preset.target` (target resolution and checking), `preset.heal` (rewriting an older preset document in the current form on a local edit).
# p5_menu
A UI template screen.
# outline
The public outline API — mark entities to draw with a coloured silhouette rim.
Its registry (entity id → `{ color, thickness }`) is read every frame by the
`@builtin::renderFeatures.outline` render feature, which draws a screen-space
jump-flood rim hugging each marked entity's silhouette (uniform width, no gaps on
hard-edge or multi-part meshes). The feature is ensured live on first use, so
`outline.set(entity)` is all a caller needs.
`thickness` is the rim's width in output pixels at any resolution and distance,
and its outer edge is antialiased.
## What stands in front of the entity: `occluded`
Each outline states what its rim does where opaque geometry stands between the
camera and the entity:
| `occluded` | the rim | default for |
|---|---|---|
| `"hide"` | grows only from the part of the entity the camera sees and stands at that part's depth, so a wall, a floor or any other opaque surface in front of the entity hides its rim exactly as it hides the entity, and an entity hidden entirely draws no rim | `outline.set` |
| `"dashed"` | is drawn all round the entity, solid where the entity is seen and in dashes of its full colour where something stands in front of it, so the entity stays marked through the wall, over a bright surface as over a dark one, the way an editor marks its selection | `outline.setEditorHint` |
A game outline (a pickup's glow, a hovered unit) keeps the default `"hide"`. An
outline that has to mark an entity wherever it is, such as a teammate seen
through a wall, states `"dashed"`:
```luau
outline.set(teammate, { color = { 0.2, 0.6, 1, 1 }, occluded = "dashed" })
```
A `Model` or `SkinnedModel` drawing its outline from its outline fields states
the same choice in `outlineOccluded` (`"hide"` unless set), so a through-wall
marker can be authored as scene data.
## Editor hints
`outline.setEditorHint(entity, opts)` draws the outline the editor uses to mark
an entity out (the selection, a player spawn point). It is drawn on the
`EditorUI` render layer, so a capture or camera that leaves the editor's chrome
out leaves it out too, it reads `"dashed"` unless `opts.occluded` states
otherwise, and it is drawn only in edit mode: the world leaving edit mode clears
every hint, and a call made outside edit mode registers nothing and returns
`false`, so a hint never draws in play.
An entity's outline lasts as long as the entity: when it is despawned, by
`entity.despawn`, a parent's cascade, a scene rebuild or reload, its id leaves
the registry, so the feature's per-frame cost follows the outlined entities in
the world. A `Model` or `SkinnedModel` drawing an outline from its outline fields
clears it when the component is removed.
```luau
local outline = require("modules.outline")
outline.set(entity, { color = { 1, 0.5, 0, 1 }, thickness = 3 })
outline.set(entity, { color = { 1, 0.5, 0, 1 }, thickness = 3, occluded = "dashed" })
outline.clear(entity)
outline.clearAll()
```
# editor_ops
Delete and duplicate the current editor selection, each as one undo step. Delete
despawns every selected entity and clears the selection; duplicate clones each
selected entity via `entity.duplicate` — a full component, attribute, visual,
and material clone that includes descendants — and selects the copies. Both wrap
the batch in a multiplayer undo operation so a single Ctrl+Z reverts the whole
action. The editor scene entrypoint binds these to Delete and Ctrl+D.
# lighting
The canonical scene-lighting toolbox — ambient light, directional sun, sky, clear color, and point / spot / area lights, each with modify-or-spawn semantics: every call leaves the scene in the requested lighting state, spawning the canonical `sun` / `ambient` entities (or switching the renderer-level sky) when the scene has none.
Set the whole environment in one call (sun, ambient, sky, and clear color, all optional), or set each independently: the directional sun, the ambient light, or the sky — swapped from a preset word, a project material matched by name, or a material ref. Add a point light as an entity at a position. Update any point, spot, or area light by name — its color, intensity, reach, shadows, and its shape controls (spot cone, area rect). Read the full lighting state back — every light with its values, clear color, authored sky, live sky config — in the same shape the whole-scene setup accepts.
These are the interactive authoring surface, for setting a scene's lighting from `execute()`. The behaviour lives in the runtime lighting capability (`modules.api.engine.lighting`); a component, entrypoint, or the scene saver that adjusts lighting at runtime uses that capability directly, not a tool.
# script_context
Builds the environment of a file the engine loads itself, from the context its asset type declares.
An asset type states, in the `contexts:` block of its `type.yaml`, which of its files run in an environment of their own and what that environment holds:
```yaml
contexts:
- name: sceneBuild
file: "build.luau"
surface: "scene's `build.luau`"
globals:
build: "the build surface ..."
hooks: [content, editorOnly]
modules: true
```
- `name` is the context's name.
- `file` is the file of the type's asset folder that runs in it.
- `surface` is how a diagnostic names that file.
- `globals` are the names the loader binds into each chunk, each with the note an unknown-global message gives a file that lacks it.
- `hooks` are the functions the engine calls by name, which the language server does not report as unused.
- `modules: true` says the loader binds the modules that join the context.
A module joins a context with a line in its leading comment block, and its exports are then globals in every file of that context:
```luau
--!context sceneBuild sceneModule
local M = {}
function M.Mesh(geometry, material) ... end
return M
```
A name that starts with `_` stays inside its module.
`ScriptContext.bind(env, path, values)` binds a file's context into the environment it runs in: the loader's own values, which must be names the context declares, then each joining module's exports. Two sources binding one name is an error naming both. It returns the modules it bound, so a loader can call what they export around a run of the file (a scene build calls `_beginRun` and `_finish`).
`asset.context(path)` reads the declaration a file runs in, and the language server declares the same names from it, so what a file may use and what it finds when it runs are one answer.
# toolExec
Run a script that drives the engine's toolbox catalogue.
This is the engine half of `tool_exec`. A harness hands over a script; this runs it on ZeroJS, the engine's own JavaScript runtime (a subset of modern JavaScript: the language and its standard library, with no Node or browser APIs), with exactly two globals — `zero.<toolbox>.<tool>(...)` to call a tool, and `tools.toolboxes()` / `list()` / `describe()` / `search()` / `use()` to find one. No engine globals, no VM.
**It is not "execute, but JavaScript."** A raw runtime with the engine's globals is `execute` with different syntax. What a shell command and a tool-calling loop both lack is the ability to hold an intermediate result: you cannot list 200 entities, filter them in-process and act on the 6 that matched without the whole list passing through the model. That is the gap — composition, not capability. Every tool reachable here is reachable from `zero` in bash and `tools.use` in Luau, under the same names.
**A tool returns an engine value.** Tables arrive as plain JavaScript objects and arrays; `null` and `undefined` arrive as themselves.
**Every binding is async, and that is not a style choice.** A tool may yield — `zeromind.search` makes an HTTP round trip — and a yield cannot cross the JS→Luau call boundary. The failure is silent: the call returns and its value is lost. So no tool is ever called from inside the interpreter. `__start` spawns a Luau task that may yield freely and hands back a ticket; `__poll` reads the settled result without yielding; the prelude turns the pair into a promise. The script says `await zero.scene.list()` and the yielding happens outside the VM, where it is allowed.
The caller's source is wrapped in an async function that opens on the caller's first line, so `await` works on the first line and the line numbers in a syntax error are the caller's own. ZeroJS has no top-level await, and an agent should not have to know that.
```js
const boxes = await tools.toolboxes();
const camTools = await tools.list("camera");
const spec = await tools.describe("camera.lookAt"); // or tools.describe("lookAt") when one toolbox holds it
const hits = await tools.search("low poly tree");
const scenes = await zero.scene.list();
return scenes.filter(s => s?.name?.startsWith("level")).length;
```
A library's toolbox is registered as `@<lib>::<toolbox>`, and a script reaches it as `zero.libs.<lib>.<toolbox>.<tool>(...)`. `zero.<toolbox>` reaches it too when no other toolbox answers to that name; a name several libraries hold is refused naming each holder, and a library or toolbox that does not exist is refused naming the nearest ones.
`tools.describe(name)` answers with the tool's signature, arguments, return type and examples. A bare tool name reaches the tool when exactly one toolbox holds it; a name several toolboxes hold, or none does, is an error that lists the candidates or the nearest names.
## The result
`run` returns `{ ok, value, error, failure, trace, logs }`.
| Field | Holds |
|-------|-------|
| `ok` | `true` when the script finished and returned. |
| `value` | What the script returned. A script that returned a value but left work running past its time limit (an armed `setInterval`, say) keeps the value here with `ok = false`. |
| `error` | One sentence saying what failed and where. |
| `failure` | The same facts as data: `kind`, `message`, `completed` (calls that succeeded), and `step` and `tool` when a call ended the script. |
| `trace` | Every call in order of completion: `step` (the order calls began), `tool`, `ok`, `durationMs`, and `error` for a call that failed. |
| `logs` | One entry per `console` call, formatted the way a JavaScript console formats it. |
`failure.kind` is `"tool"` (a call's rejection ended the script, whether the script let it propagate, rethrew it in its own words, or never awaited it), `"script"` (the script threw by itself), `"syntax"`, `"timeout"`, `"budget"` (the call limit) or `"setup"`.
# toml
Pure-Luau TOML parser and emitter. Use whenever a script needs to read
or write a TOML file — settings, importer rules, tool configs, or any
other authored config the user touches by hand. Auto-injected as the
global `toml` by the prelude — no `require` in user code.
`vfs.read` returns bytes. JSON has built-in parsing via `json`, but TOML
— the format used for `.world_settings`, `pyproject`-style configs, and
any human-friendly key=value file — needs a parser. `toml` provides one
with no native dependency, so it works the same on native and WASM.
## Exports
- `toml.parse(src: string) -> { [string]: any }` — TOML bytes to nested Luau table. Throws with the line number on syntax errors.
- `toml.encode(root: { [string]: any }) -> string` — Luau table to canonical TOML bytes (alphabetical section/key order; deterministic output).
- `toml.replaceArrayTables(src: string, name: string, rows: { { [string]: any } }) -> string` — replace every `[[name]]` block of a document with `rows` (appended at the end, one block each) and keep every other byte.
## Usage
```luau
-- Parse
local body = vfs.read("/zero/source/myconfig.toml")
local config = toml.parse(body)
print(config.render.culling_mode)
-- Mutate + write back
config.render.culling_mode = "cpu"
vfs.write("/zero/source/myconfig.toml", toml.encode(config))
```
## Supported TOML
- Sections, including dotted (`[a.b.c]`)
- Arrays of tables (`[[name]]`, `[[a.b]]`), with sub-tables of a row
(`[name.sub]` after `[[name]]`); read as a sequence of tables and
written back as one block per element
- Key/value pairs with dotted keys (`a.b.c = 1`)
- Strings: `"..."` (escaped) and `'...'` (literal); triple-quoted
variants for multi-line bodies
- Integers (with `_` digit separators) and floats (incl. `inf`,
`-inf`, `nan`, exponents)
- Booleans (`true` / `false`)
- Inline arrays (`[1, 2, 3]`)
- Inline tables (`{ a = 1, b = 2 }`)
- `#` comments
## Not implemented
These are rare in settings/config files; add when a real call site
needs them rather than carrying dead code.
- Hex / octal / binary integer literals (`0xff`, `0o77`, `0b1010`)
- Date / time literals
## Notes
- `--!global toml` directive promotes the module's typed functions
onto the runtime universe's globals bucket, so `toml.parse` /
`toml.encode` are available without any per-source `require`.
- The encoder is fully deterministic: sections and keys are sorted
alphabetically, integer-shaped numbers are emitted without a
decimal point (`2` not `2.0`), and nested tables become dotted
section headers (`[a.b]`).
- Parser errors carry the line number for fast diagnosis.
# camera
Author and manage the cameras in a scene: create one, list every camera, read its full parameters, change them, aim it, frame a subject, or make it the primary camera. A physical camera on the machine (a webcam, a phone camera) is `cameraInput`, covered by the `topics/camera-input` guide.
## Create & inspect
- **create** — spawn a camera entity at a position, with any starting parameters in one call: fov, near/far, priority, render layers, a follow target, a behavior, a `lookAt`, and `target` (render-to-texture — `true` or `{ width, height, name }` renders the camera offscreen instead of to the viewport). Returns the new camera's full parameter record.
- **list** — every camera in the scene, enumerated from the live ECS so a just-spawned, hidden, or runtime camera is never missed, sorted by descending priority, each row marking whether it is the on-screen (`active`) camera, whether it is the `player` camera (the one the PlayerPrototype uses), and its main/editor role.
- **get** — the full parameter record for one camera (position, rotation, fov, near, far, priority, render layers, debug channel, render target, behavior, follow). Defaults to the active/main camera when you name none.
## Modify
- **set** — change any of these camera parameters in one call: `fov`, `near`, `far`, `priority`, `debugPass` (the diagnostic view this camera renders, by name), `debugChannel` (the same as a raw numeric channel), `renderLayers` (the layer-name spec, e.g. `"all !ui"`), `behavior` (a `cameraBehavior`-tagged component), and `follow` (the entity the behavior tracks). Pass no camera to modify the active one. A camera's render target is set when it is created (`create` with `opts.target`).
- **lookAt** — aim a camera at a world position or at another entity.
- **frame** — position and aim a camera to frame a target entity from a distance and angle in one step.
- **bindToPlayer** — make the joining player use a camera in play by binding it to the scene's PlayerPrototype: it re-parents the camera into the prototype (so it is cloned with the player) and sets the prototype's `camera` role to it. Pair it with a static behavior (`set { behavior = "@builtin::controller.menu" }`) for a fixed PS1-style camera the player moves within, or a follow behavior (`orbital_follow`, `third_person_follow`, `first_person`, …) for a tracking one. A player-less scene has no prototype — there the rendering camera is simply the highest-priority one, ordered with `set { priority = N }`.
## Related surfaces
- Capturing an image from a specific camera is the `capture` toolbox (`capture` with a camera, or `oneshot`) — it renders any camera's authored pose offscreen without changing what is on screen.
- Putting geometry ON a render layer is the `renderLayer` toolbox (`renderLayer.set`); `renderLayer.camera` is the layer-system-side way to set a camera's include filter, the same field `camera.set { renderLayers = ... }` writes.
- The scene's primary camera is normally spawned for you from the scene's PlayerPrototype; `camera.create` adds additional cameras (a security view, a cutscene angle, a render-texture feed).
# content_terms
The terms of service a person accepts before they put content other people see under their OrigoZero account: a world made, forked or published, a comment, rating note, issue or review, a world chat post or direct message, an upload. An agent's tool call and an engine that booted offline are let through without a read. The ZeroMind ops that post content (`zeromind.world`, `zeromind.engage`) refuse a person's act the same way in the trusted layer, with `termsRequired = true` on the outcome.
## Exports
- `NOT_ACCEPTED`, `UNREAD` — the codes a refusal starts with.
- `PROMPT_SECONDS` — how long an act waits on the person's answer to the terms prompt.
- `gate(answer)` — what a terms read lets through: `{ allow }`, or `{ allow = false, prompt }`.
- `check()` — where the account stands for the act about to be made: `{ allow, exempt?, prompt? }`. Yields.
- `accept(version)` — record the version in force; the engine's dialog asks the person to confirm it. Yields.
- `present(fn)` / `presenting()` — register the screen that asks the person, and whether one is.
- `ask(prompt)` — ask the person through that screen; true once they accepted.
- `ensure(verb)` — hold an act to the terms: return when it may go ahead, ask first when it may not, raise the refusal otherwise.
- `askAgain(outcome)` — for an op the trusted layer refused over the terms: ask, and answer whether to send it again.
- `refusal(verb, prompt)` / `isRefusal(err)` — the refusal text, and whether a text is one.
- `heldBackText(err)` — the line a screen shows for an act held back because the account has not accepted the terms, in the person's language; nil for any other error.
# sourceEdits
Checks for authored source before it is written. `candidate` validates a
source's syntax and derives the checksum, size, kind and reference table that
storing it would state, without writing anything. `folderChecksum` derives a
folder asset's checksum from its leaves, `newIdentity` mints a UUID, and
`checkWrite` answers the canonical path a source write may take.
```luau
local sourceEdits = require("modules.api.engine.sourceEdits")
local checked = Json.decode(sourceEdits.candidate(path, text))
local guid = sourceEdits.newIdentity()
```
# kanban_planner
A UI template screen.
# json_utils
Safe JSON decoding helpers and a WASM-safe number formatter. Wraps
`Json.decode` with `pcall` so engine-provided JSON strings can't
propagate parse errors into call sites. Also handles the engine
convention of writing the literal string `"null"` when a JSON value is
absent.
## Exports
- `M.decodeOrNil(jsonStr: string?) -> any` — safe decode; returns `nil` on empty input, `"null"`, or parse failure.
- `M.decodeOrEmptyTable(jsonStr: string?) -> table` — safe decode; returns `{}` on any failure or non-table result.
- `M.safeDecode(jsonStr: string?) -> any` — historical alias for `decodeOrNil`.
- `M.formatNumber(n: number, decimals?: number) -> string` — truncate a number to N decimal places using only string ops. WASM-safe.
## Usage
```luau
local JsonUtils = require("@builtin::modules.json_utils")
local payload = JsonUtils.decodeOrNil(engineJsonString)
local table = JsonUtils.decodeOrEmptyTable(maybeMissing)
local label = JsonUtils.formatNumber(3.14159, 2) -- "3.14"
```
## Notes
- `decodeOrNil` short-circuits on `nil`, empty string, and the literal
string `"null"`. The Json.decode call itself is wrapped in `pcall`, so
malformed input is never observable to callers.
- `decodeOrEmptyTable` is intentionally strict: non-table decode results
(numbers, strings, booleans, nil) collapse to `{}`. Use `decodeOrNil`
if you need to distinguish those.
- `formatNumber` uses `tostring` + `string.sub` so it avoids the
`string.format` numeric specifiers that don't work reliably under
WASM in Luau. Pass `decimals = 0` to drop the fractional part
entirely; a count below `0` reads the same as `0`, and a fractional
count counts the whole places in it.
- `formatNumber` truncates the mantissa of a value `tostring` renders in
exponent form (`1.5e-07`) and keeps the exponent, so the result still
reads back through `tonumber`.
# headset_flight
The editor camera's flight in a headset: the person flies along the direction
they look, head pitch included, and the speed follows how long they have been
flying.
```lua
local Flight = require("@builtin::modules.headset_flight")
local state = Flight.newState()
local basis = Flight.basis(camera.facing(id, "forward"), camera.facing(id, "right"))
local dx, dy, dz = Flight.step(state, { strafe = 0, forward = 1, vertical = 0 }, basis, 5, 100, dt)
```
## Exports
- `Flight.basis(forward, right?) -> Basis?` the axes flown along: the view's
forward in three dimensions, its right on the level plane, the world's up.
- `Flight.speed(base, top, held) -> number` metres per second after `held`
seconds of continuous flight: `base` at the start, `top` after
`Flight.RAMP_SECONDS` (3), growing exponentially.
- `Flight.newState() -> State` a flight at rest.
- `Flight.step(state, controls, basis, base, top, dt) -> dx, dy, dz` advances
the flight; the velocity eases towards its target over `Flight.RESPONSE_SECONDS`
(0.12) and the speed returns to `base` after the controls rest for
`Flight.IDLE_RESET_SECONDS` (0.3).
# blocks
The accounts the person signed in blocked on OrigoZero, and blocking and
unblocking one. A blocked account's world chat, direct messages, comments and
presence stop reaching the person on every device and session they sign in
on, and so do the agents working for it. The blocked account is not told.
ZeroMind keeps the list (`/v1/me/blocks`) and withholds what it serves: the
comment threads, reviews, the inbox and a world's activity. The engine reads
the list with the person's own credential when they sign in and every two
minutes after, and withholds what a world carries between engines:
- `messages`: the world chat and direct messages, for the person and for
their agents (no notice tells an agent of one);
- the People tab of the app menu and the editor's people dropdown: the
account and its agents leave the people listed and the counters;
- the ZeroMind tab: its comments.
`blocks.isBlocked(account)`, `blocks.ids()` and `blocks.state()` read the list
as the engine holds it, in any VM, without yielding. `blocks.block(id, label)`
and `blocks.unblock(id, label)` ask the person in the engine's confirmation
dialog, which names the account by `label`, then change the list on ZeroMind,
yielding until it answers. `blocks.start(op, id, label)` runs either on a task
of its own for a button, and `blocks.pending(id)`, `blocks.lastFailure()` and
`blocks.onSettled(fn)` say how it went.
Block is offered beside Report on each person, agent and chat post of the
People tab, on each person and chat post of the editor's dropdown, and on each
comment and creator page of the ZeroMind tab. The People tab lists every
blocked account with Unblock.
Reading and changing the list needs the person's own sign-in on OrigoZero:
ZeroMind refuses it to a device link, an API key and an agent's credential,
and `blocks.state()` then reads `refused` with ZeroMind's reason.
# modules.api.engine.player_lifecycle
Wires the UserIdentity component's avatar-bind events into the
`localPlayerReady` lifecycle hook. Owns the local-avatar-bound latch
(fires once after the avatar entity is bound + has settled past the
bundle.instantiate deferred-mutation pipeline) and the opt-out path for
legacy v6 scenes that declare the avatar slot as `""`.
Exposes the `__layers_local_avatar_bound` + `__layers_local_avatar_opt_out`
dispatch channels wired in `install()`; the UserIdentity component's
lifecycle and the legacy v6 player_spawner route through them.
# defaultAvatars
The platform's default avatars: the set a person chooses their avatar from on
the app menu's Outfits tab, and the one a person wears in place of the
library's humanoid (the development avatar) while their account keeps no look
of its own.
```luau
local defaultAvatars = require("@builtin::modules.defaultAvatars")
for _, e in defaultAvatars.list() do
print(e.name, e.style, e.author, e.licence, e.triangles)
end
local doc = defaultAvatars.document("vita") -- { v = 1, avatar = <guid> }
print(defaultAvatars.default().name) -- what a new person wears
print(defaultAvatars.find(doc.avatar).name) -- "Vita"
```
Each entry is `{ id, name, avatar, style, picture, author, licence, licenceUrl,
credit?, source, triangles }`:
| field | what |
|-------|------|
| `avatar` | the avatar's guid; an outfit document wears it by this guid in every world (`avatarAppearance.publishedAvatar` mounts it from the world that published it) |
| `style` | `anime`, `stylised`, `creature`, `robot` or `lowPoly` (`defaultAvatars.styles`) |
| `picture` | the texture the chooser shows |
| `author`, `licence`, `licenceUrl`, `credit` | who made it, the licence that lets the platform give it to every person, and the credit line its author states |
| `source` | where it comes from |
| `triangles` | its triangles over every mesh of the body |
`avatarAppearance.accountAppearance` answers `from = "default"` with
`defaultAvatars.default()` worn as its author made it when a person's account
keeps no outfit and no profile descriptor. Their body wears it where it stands
as the library's humanoid (`avatarAppearance.DEVELOPMENT_AVATAR`); a world that
chose its own play avatar keeps it. An agent account with neither wears none.
Every avatar of the set is published in the world `defaultAvatars.world`.
# asset_residency
Compute backends for the **lazy** residency properties on every `AssetRef`
(`has_backing_asset`, `has_runtime_changes`, `cpu_resident`, `gpu_resident`).
The AssetRef
metatable's `__index` dispatcher (`assetType.shared.ref`) calls these only when a
caller actually reads a flag — nothing is computed at resolve time, so an asset
costs nothing for residency until it is observed.
The three backing/runtime states:
| `has_backing_asset` | `has_runtime_changes` | Meaning |
|---|---|---|
| true | false | USED, UNMODIFIED |
| true | true | USED, MODIFIED (copy-on-write fork) |
| false | true | RUNTIME-GENERATED |
`cpu_resident` and `gpu_resident` are orthogonal to those three, and to each
other. `cpu_resident` asks *"is this asset referenced from a live
script-component context, so its bytes are warmed in memory?"* (the
`/runtime/assets/` CPU layer); `gpu_resident` asks whether the device holds a
texture or mesh under the asset's guid. They are separate pools and an asset
can be in one and not the other — `asset.observe()` lists both. See
`docs/specs/runtime-asset-copying.md` — "CPU residency vs GPU residency".
The backing/runtime flags are derived from where the asset lives — source under
`/zero/source/…` (backed), a copy-on-write fork / runtime-generated asset under
`/zero/runtime/assets/<identity>.<category>/` (runtime change) — using the
canonical `<identity>.<category>/` suffix shape, generic over any category.
`cpu_resident` and `gpu_resident` are live queries through `asset.cpuResident`
and `asset.gpuResident`.
# services
Generate real content — 3D meshes, textures, audio — from a prompt, by spending credits. This is the whole surface for it: discover what you can make, start a generation, track it, and find what you've made. You never touch the underlying asset type or task plumbing.
When a build needs a recognizable thing — a treasure chest, a snowboard, a character, a sound — you **generate** it. You don't assemble it from boxes and spheres.
## The loop
Discover what you can make: each service lists its operations, and each operation is self-describing: its inputs, the kind of asset it produces, and its credit cost. Check your credit balance if you want. Start a generation with a service and a prompt; this returns immediately with a handle and runs in the background, because a generation takes minutes and blocking would trip the execute time limit. When the run ends it posts a notice, `generation finished` naming its id and the job's `asset` (the spawnable asset path, which you can drop straight into a blocked-out slot) or `generation failed` naming its id and the error, and the notice reaches you on your next tool call; `services.status` reads a run's progress by its id meanwhile. A run files its output where your writes landed when you started it: one started in edit keeps its asset on source even when it finishes after you entered play, and one started inside your play session leaves it on the play shadow, where a play-exit discard takes it back; `durable` in the input states it outright. The notice and `services.status` both say where the output stands (`durable`, and the shadowed paths when the play shadow holds any of it). Alongside the live per-session job view, a durable outputs record survives restarts by reading the provenance stamped on each generated asset.
## Describing your assets
`describe` is the one tool here that makes text, not content. It finds the assets in your world that lack the description their type asks for (for the built-in types that ask, a README, or the `about.yaml` texts of a type) and fills them in: `{ mode = "find" }` lists what is missing and what filling it costs, `{ mode = "all" }` fills it, and `{ assets = { ... } }` fills the assets you name. A call costs 1 credit and covers many assets, and `find` reports the number of calls before anything is spent. What it writes is an ordinary file in the asset, there for you to edit.
# water_surfaces
The water surfaces a scene holds, gathered from the systems that make them.
A system with water — a terrain's lakes, rivers and seas, an ocean — registers
a provider here, and whatever stands things on water asks every provider at
once. A procedural graph reads them all through `scene.water`.
A provider is a table of two functions:
- `version()` names what its water is now. A surface that moves every frame
answers differently every frame, which is what makes a reader stand its
points again.
- `stand(request)` puts points on its water on the device. `request` holds:
- `run`: the points' GPU positions, in the graph's space;
- `count`: how many points there are;
- `out`: the `P`, `normal`, `slope` and `wet` GPU columns to write;
- `place` / `unplace`: graph to world and back, 16 numbers each;
- `offset`: metres above the surface;
- `keepY`: whether a point's own height rides on the surface's.
It writes the points over its water, leaves the rest as they are, and
returns the names of the kernels it dispatched.
```luau
local water = require("@builtin::modules.water_surfaces")
water.register("myWater", { version = versionNow, stand = standOnMyWater })
for _, p in water.list() do
print(p.name, p.provider.version())
end
```
# fresh_open
Open the world this client is bound to fresh, the way a player's engine opens
it, and report how it opened.
- `open(opts)`: reload the bound world from the top (content taken cold,
entrypoint and startup scene run, components woken once), then run
`opts.code` and `opts.play` seconds of play on it.
- `installAndOpen(assets, opts)`: install each asset (`guid` or `guid@ref`)
first, then open, and require every module each install names.
The report states whether the open finished and how long it took, each
install, each require, the code's answer, and the errors and warnings logged
while the check ran with their distinct messages. `zeromind.freshCheck` runs
`installAndOpen` in a sub-client on a world made for the check, so the world
holds those assets alone.
# 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(ctx)` builds the asset (usually with
`asset.create`) and returns `{ output, container, source }`: the asset
it made, the container a re-import regenerates, and the file the asset
keeps as its source. `ctx` carries `path`, `bytes`, `extension`,
`settings`, `output`, `container`, `retainSource`, `stem` and `dir`.
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.
7. **A lost live session.** While the live world session is lost and
reconnecting (`vfs.sessionLost()`), every write to authored source is
refused, so an import asked for then is owed rather than started, and
one a drop catches part way is owed rather than failed, its job carrying
the refused write as `error`; when the import had already moved its
source into the asset it makes, it runs again on the source there,
regenerating that asset around it. The job reads `owed` (reason
`session-lost`), the notice `import owed until the live session
re-establishes` names it, and it imports once the session is back,
when the notice `import resumed: the live session re-established`
names it and `import finished` (or `import failed`) settles it. A
generation waiting on such an import completes with the asset it
produces. Content this machine keeps to itself (`vfs.isSaveExcluded`:
`/source/tmp/`, `/source/local/`) is written while the session is lost,
so an import of a source there into an asset there runs at once.
## 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. One
the lost live session holds back answers `owed` with `reason`
`session-lost`, and runs when the session re-establishes.
`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).
- Write the asset to `ctx.output`: on a first import that is
`<dir>/<stem>.<produces>`, beside the source. The asset lands where
the source was, and a re-import regenerates it in place.
- 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`: a declarative content generator; an importer converts a
file that already exists, a service makes content you don't have yet.
## 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.
# `lut` module
`require("@builtin::modules.lut")` — colour lookup tables: build one, import one
a colourist exported, read one back, and install it as the `.texture` asset the
`lut` post-process effect binds.
## What a LUT is here
An N-entry colour cube: for N³ input colours the table stores what each becomes,
and everything between them is read by trilinear interpolation. A grade of any
complexity therefore costs the same eight texel reads — which is why a look is
delivered as a table rather than as a chain of operations.
The cube is stored as a **strip**: N square tiles in one row, so the image
measures `N*N` wide by `N` tall. Tile `b` holds the plane of constant blue index,
red runs across a tile, green runs down it. That is the layout every grading tool
means by "2D LUT", and it is what `lut.install` writes.
The `lut` post shader reads N from the image's own height, so one shader serves a
16-, 32- or 64-entry cube with nothing to configure. A texture that is not shaped
like a strip — including the 1×1 fallback bound when the effect has no table —
leaves the frame exactly as it arrived.
## Applying one
```luau
local lut = require("@builtin::modules.lut")
local ref = lut.install("warm_evening", lut.fromGrade({
exposure = 0.3,
temperature = 0.25,
saturation = 1.1,
lift = { 0.01, 0.01, 0.03 },
}))
tools.use("pp", "add", "lut", "lut", { texture = ref.guid, amount = 1.0 })
```
`amount` cross-fades between the ungraded frame and the table's answer, so a look
can be dialled in or tweened.
The effect works on the display's code values — the usual place for a look
exported from a grading tool, since the chain applies it after `__display__`,
the chain's own display transform, has already run.
## Surface
| Call | What it does |
|---|---|
| `lut.build(size, fn)` | Ask `fn(r, g, b)` what each lattice colour becomes. |
| `lut.identity(size?)` | The table that changes nothing — the A/B control. |
| `lut.grade(spec)` | The `GradeSpec` transform as a plain function. |
| `lut.fromGrade(spec, size?)` | Bake that transform into a table. |
| `lut.fromImage(bytes)` | Import a strip PNG/JPEG/WebP. |
| `lut.fromCube(text)` | Import `.cube` text (Resolve, Photoshop, …). |
| `lut.toCube(table, title?)` | Write `.cube` text back out. |
| `lut.sample(table, r, g, b)` | The trilinear read the shader performs. |
| `lut.strip(table)` | The channel values, its width and its height. |
| `lut.install(name, table, opts?)` | Write it as a `.texture` asset. |
## The grade
`GradeSpec` fields compose in the order a colourist works in: exposure, white
balance (`temperature` / `tint`), `contrast` about `contrastPivot`, `saturation`
about Rec. 709 luminance, then `lift` / `gamma` / `gain` / `offset` per channel,
then a `curve` hook applied last. Every field is optional and every omitted field
is the identity, so `{}` is the grade that changes nothing.
White balance is a von Kries adaptation: the spec's temperature and tint name an
illuminant, and the table carries the LMS ratio between it and D65 — the same
model a grading tool's temperature slider drives.
## Storage
A table's entries are addresses, not an image, so `lut.install` writes them as a
float raster (`rgba32f`, `nearest`, no mip chain) and uploads the same strip to
the GPU under that asset's guid as `rgba16f`, the float format a texture slot
samples on every device. The entries reach the shader as they were written, and
the shader reads its corners with `textureLoad` at exact texel coordinates, so
each blue plane is read from its own tile.
The upload is also what makes the guid `lut.install` returns bindable from the
next frame — the `.texture` write itself settles at the end of the step that
made it — and what puts a re-baked look in front of the camera under the name it
already had.
A 16-entry cube is the common default and is enough for most looks; pass a
larger `size` where a grade has a steep region and the interpolation between
entries shows. The largest is 90: the strip is `size*size` wide, and 8192 is the
texture width every device guarantees. A strip imported from a colourist's
8-bit PNG carries that image's precision, which the float raster then preserves
exactly.
# playerSetupValidation
Agent-facing validation for authored player setups. A player-spawn scene is built from PlayerSpawn entities (each naming a PlayerPrototype subtree to instantiate on join) and PlayerPrototype roots (marked PrototypeOnly, carrying a Camera in their subtree and a `body` field naming the entity to adopt). `checkEntity` inspects one such entity and returns human-readable messages that name what is wrong and what to do about it; `checkScene` validates the scene's player intent against its PlayerSpawn / Camera counts; `checkActiveScene` runs both across the live active-layer scene and returns a flat `{ entity, message }` list — the queryable surface an agent reads to see what to fix.
`checkActiveScene` answers for the settled scene: it holds while a scene load or a mode-flip transition is rebuilding the live tree, then judges what the rebuild lands on. Each PlayerSpawn's prototype resolves wherever the materialisation holds it — the live entity in edit, and in play, where the loader keeps authored prototype subtrees out of the scene, the captured authored template each joining player is cloned from — so the same rules run over the same authored structure in both modes, and a prototype removed from a scene that materialises prototypes reads as the missing reference it is.
Location: `src/lua/lib/modules/api/engine/playerSetupValidation.module`
# lighting
Scene-lighting base capability: ambient + directional ("sun") light and procedural-sky setup with modify-or-spawn, read-merge-write semantics, plus clear color, and the per-frame reads of the resolved lights. Identity is the component, never the entity name: the sun is the `Light` the renderer's snapshot names as the directional holder, the ambient is the light-role component of kind "ambient", and the sky is the entity carrying a sky-role component. Name-based lookup, word resolution, and sky-material orchestration (presets, material swap) live in the `lighting` toolbox.
`sun` and `ambient` configuration patch the scene's resolved sun / ambient light components, spawning a carrying entity when the scene has none. A partial update (e.g. only `intensity`) reads the component's current fields first and merges the given fields on top, so unspecified fields keep their authored values instead of resetting to a default. `sky` writes the sky entity's ProceduralSky component the same way — any of its fields, plus `enabled = false` to remove the sky component.
## Types
- `SunOpts` — `{ direction?, color?, intensity?, castsShadows? }`.
- `AmbientOpts` — `{ color?, intensity? }`.
- `ProceduralSkyOpts` — ProceduralSky component fields, plus `enabled = false` to remove the sky.
- `SetupOpts` — `{ sun?, ambient?, sky?, clearColor? }`.
- `SetupResult` — `{ sun?, ambient?, sky? }`, the entity ids each provided section resolved to.
- `Sun` — `{ direction, color, intensity, castsShadows, entityId? }`.
- `Ambient` — `{ color, intensity, entityId? }`.
- `LightRow` — one punctual light as the renderer resolved it.
## Exports
Writes — each takes the opts above and answers with the entity the light resolved to:
- `M.setSun(opts: SunOpts) -> string` — set the scene's sun, returning its entity id.
- `M.setAmbient(opts: AmbientOpts) -> string` — set the scene's ambient term, returning its entity id.
- `M.applySetup(opts: SetupOpts) -> SetupResult` — apply a lighting setup in one call. All fields optional — only provided fields change. `clearColor` is `{r, g, b}`.
- `M.setProbeVolume(key: string, volume)` / `M.removeProbeVolume(key: string)` — publish or retract a baked irradiance probe volume.
Reads — each takes no arguments, and answers from the resolved lighting state at a cost independent of scene size:
- `M.sun() -> Sun` — the sun the frame is shaded by.
- `M.ambient() -> Ambient` — the ambient term the frame is shaded by.
- `M.lightRows() -> { LightRow }` — every punctual light the renderer resolved this frame.
Identity:
- `M.lightKind(componentType: string, component: any?) -> string?` — the kind a light-role component names.
- `M.lightOfKind(entityId: string, kind: string) -> any` — the light-role component of that kind on one entity.
## Usage
```luau
local lighting = require("@builtin::modules.api.engine.lighting")
lighting.setSun({ direction = { 0.3, -1, 0.2 }, intensity = 2.0 })
lighting.setAmbient({ intensity = 0.3 })
lighting.applySetup({
sun = { direction = { 0.3, -1, 0.2 }, intensity = 2.0 },
ambient = { intensity = 0.3 },
sky = { timeOfDay = 14 },
})
local sun = lighting.sun()
print(sun.intensity, sun.entityId)
```
A reader takes no arguments and a setter takes the opts table, so `lighting.sun(opts)` is refused with the name of the call that applies it.
# editor_observe
What an editor action committed, and why it committed less than it was asked for.
Every editor action — a gizmo drag, a delete, a duplicate, a command dispatch, a
selection gesture — closes by publishing one record here, and returns that same
record to its caller. Nothing is measured per frame: a record is written where
the work happens and read lazily.
```lua
local Obs = require("@builtin::modules.api.editor.editor_observe")
Obs.observe() -- the whole document: last of each kind, history, counts
Obs.last() -- the most recent action of any kind
Obs.last("drag") -- the most recent drag
Obs.history() -- every retained action, oldest first
```
The same reading is a tool: `tools.use("editor", "observe")`.
## What every record carries
- `action` — `drag`, `grab`, `delete`, `duplicate`, `command` or `select`.
- `outcome` — `committed`, `partial`, `refused`, `cancelled` or `noop`.
- `reason` — the nearest cause, from the closed set below, when the outcome is
anything but a clean commit.
- `detail` — the engine's own words for that cause.
- `entities` — one row per entity the action touched or tried to, each with
`before`, `requested` and `after`, and its own `reason` when it is not a clean
commit.
- `committed` / `changed` / `refused` — how many rows fall in each.
- `seq`, `atMs`, `durationMs` — which action this is and how long it was open.
## The reason set
`selectionEmpty`, `entityMissing`, `writeRefused`, `writeDiverged`, `pivotLost`,
`userCancelled`, `commitFailed`, `duplicateRefused`, `despawnRefused`,
`unchanged`, `commandMissing`, `commandDisabled`, `predicateRaised`,
`bodyRaised`, `hitNothing`, `pointerBlocked`. `Obs.REASONS` maps each to its
one-line meaning, so a caller can enumerate the set rather than guess at it.
## A drag that moved less than asked
The drag record separates the three quantities that are usually conflated:
- `pointerAsked` — what the pointer's position asked for, before snapping.
- `applied` — what the gizmo handed the engine, after snapping. `snapping` and
`snapIncrement` say why the two differ.
- each entity's `after` — the transform the engine **holds**, read back from the
engine rather than recomputed from the drag's own arithmetic.
An entity whose `after` differs from its `requested` reads `writeDiverged`; one
whose write raised reads `writeRefused` with the message; one despawned mid-drag
reads `entityMissing`. A drag that ended on Esc reads `cancelled` /
`userCancelled`, and one whose selection emptied under it reads `cancelled` /
`pivotLost` — three terminal states a single "the object did not move" cannot
tell apart.
## A drag that never began
A press that lands on a handle and starts no drag publishes a `grab` record
instead — `Obs.last("grab")`, or `Gizmo.lastGrab()`. `pointerBlocked` says the UI
layer held pointer focus, so the press never reached the handle. A press away
from every handle is a selection click rather than a grab, and records nothing.
One record per press: a frame that ticks the gizmo more than once reports the
press once.
`unit` names what `pointerAsked` and `applied` are measured in: `metres` for a
translate or plane drag (a world-space `{x,y,z}` delta), `radians` for a rotate
(`{radians}`), `factor` for a scale (`{factor}`).
## Per-frame cost
The editor's own per-frame work is named in the profiler rather than pooled into
`lua_update`: `script.editor.gizmo.tick`, `script.editor.viewport.select`,
`script.editor.selection.highlight`, and `script.editor.panel.<id>` for each
dock panel's rebuild. Read them with `profiler.stats()`.
# zeromind_inbox
The ZeroMind inbox as engine notices. ZeroMind keeps an inbox for each account, with an entry for each comment on the account's content, reply to its comment, rating of its content, issue filed on its content or by it, comment on such an issue, contribution sent to its world, and review, comment, merge, close or reopen of a contribution it sent. Each entry carries the account's own gap-free sequence number (`seq`).
An inbox reads the entries after the last `seq` it read and posts one notice for each unread entry, oldest first, naming the call that acts on it. A notice that asks for work is a community notice (`modules.community`), so the person's community setting decides whether it wakes an agent: comments, ratings and issues on their content ask to `answer`, a contribution sent to them asks to `review`, a review of a contribution they sent asks to `contribute`. A notice that asks for nothing (an issue they filed closed or reopened, a contribution merged, closed or reopened) is a background notice. Each notice carries its catalog key, so the editor's notification bell shows it in the person's language, and a name another account chose is quoted as untrusted text (`modules.untrusted_text`).
The last `seq` read is kept for each account in the person's home folder (`CURSOR_FILE`), so the next engine, on this world or another, reads on from it: an entry is posted once and none is passed over. With no `seq` kept, the newest `BACKLOG` entries are read and one `backlog` notice counts the unread entries older than them. An inbox's first read with a `seq` kept posts that notice too when the unread entries an earlier engine read are still waiting.
On an editor engine bound to a world and signed in to ZeroMind, the inbox is read every `POLL_S` seconds once `start()` runs as the world becomes ready.
## Exports
- `POLL_S`, `PAGE`, `MAX_PAGES`, `BACKLOG`: how often a started inbox is read, the page size of a read, the most pages one poll reads, and how many of the newest entries a poll with no `seq` kept reads.
- `CURSOR_FILE`: where in the home folder the last `seq` read for each account is kept.
- `NOTICES`: each notice by key, with the sentence an agent reads, the catalog key a person reads, and the community work it asks for.
- `INBOX_CALL`: the call that lists the unread entries.
- `callOf(item)`: the Luau call that acts on one entry (the thread, review, issue or pull request it names).
- `noticeOf(item)`: the notice one entry states, `{ key, sentence, message, community?, params }`, or nil for a kind no notice states.
- `describe(item)`: that notice's sentence with its values in place.
- `accountNote(account)`: for an agent account acting for a person, the sentence saying the entries for the person's content are written to the person's inbox; nil otherwise.
- `new(ops, store?, session?)`: an inbox over other operations (`{ account, list, post }`) and another cursor store; `inbox:poll()` reads it once and answers `{ posted, cursor?, first?, skipped?, error? }`.
- `engineOps()`: the operations over this engine: the signed-in account, the trusted `inboxList` op, and notices posted to every caller.
- `live()`: the engine's one inbox, over `engineOps()` and the home folder.
- `start()`: read the live inbox every `POLL_S` on an editor engine bound to a world; the first read is made now.
- `withdraw()`: withdraw every notice the inbox posted; `zeromind.markRead("all")` calls it.
## Usage
```luau
local inbox = require("@builtin::modules.zeromind_inbox")
local result = inbox.live():poll()
print(result.posted, result.cursor)
```
# packages Module
Public Luau surface over the `__packages` Internal FFI namespace —
list and look up registered packages.
## Purpose
Wrap the raw `__packages.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.packages` via the prelude. A package is a
folder marked with a `package.yaml`; its assets are aliased under
`~name.<tail>` so callers can require / resolve them without
knowing the folder's physical location.
## Usage
```luau
for _, p in ipairs(packages.list()) do
print(p.name, p.scope, p.root_path, p.identity_prefix)
end
local p = packages.lookup("audio")
local q = packages.lookup("@builtin", "audio")
```
## Exports
- `packages.list() -> { PackageEntry }`
- `packages.lookup(name) -> PackageEntry?` —
`packages.lookup(scope, name) -> PackageEntry?`.
# xr_guide
The headset's controls guide: a panel an arm's length away, turned to the
person's left so the world ahead stays clear, that says how to do the basic
things with the hand controllers they hold.
| Line | Shown | Named from |
|---|---|---|
| Move | while a live control `move` binds the pad | `Zin.scheme.legend("move", "gamepad")` |
| Turn | while a live control `look` binds the pad | `Zin.scheme.legend("look", "gamepad")` |
| Up and down | editing | `Zin.scheme.legend("flyVerticalHeadset", "gamepad")` |
| Point and select | always | the pointing hand's trigger, `Zin.gamepad.label` |
| Grab and move | editing | the pointing hand's grip, `Zin.gamepad.label` |
| Show or hide the editor | in the editor | the menu button, `Zin.gamepad.label("start")` |
| Open the menu | outside the editor, while the pause action binds the pad | `Zin.scheme.legend("menu", "gamepad")` |
| Talk to the agent | editing | `edui.voicePrompt.talkControl()`, and the talk gesture |
| Open worlds | the editor's dock, or the menu's ZeroMind tab | the dock's world button, or the pause action |
The hand controllers present as one pad while a headset session holds input
focus, so a control's `gamepad` bindings are what the controllers press, and
`Zin.gamepad` names each pad button by the name printed on the controllers
(`X`, `A`, `Right grip`, `Left thumbstick`, `Menu button`). A line whose
control answers to nothing on the controllers is left out, so the guide states
only what works where the person is.
It opens the first time a headset session holds input focus while the client
setting **Show the controls on entering VR** (`xr.guide`) is on; its own
button turns that setting off. **Controls** in the VR settings
(`xr.controls`), the **Controls** row of the editor's dock and the Scene's
hint in a headset open it again. It follows the mode, the pointing hand and
the live controls while it shows, and goes when the headset gives up focus.
```luau
local Guide = require("@builtin::modules.api.engine.xr_guide")
Guide.open() -- in a headset
for _, row in Guide.rows() do print(row.action, row.control) end
```
# camera Module
Public Luau surface over the `__camera` Internal FFI namespace —
script-facing camera queries.
## Purpose
Wrap the raw `__camera.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.camera` via the prelude. The engine-level
`scheduleRender` lives on the companion `__cameraBindings` Internal
namespace and is consumed directly by `Camera.component`; this
module is the small public surface scripts use to find the active
viewport camera.
## Usage
```luau
local camId = camera.main()
if camId then
local cam = entity(camId)
-- ...
end
```
## Exports
- `camera.main() -> string?` — entity id of the active viewport
camera, or nil if none is active this frame.
# inputSim
Every simulated input, across every device a player might hold. Drive the
world as a keyboard-and-mouse player, as a phone, or as someone with a
controller — and read back what actually reached the game.
## Why all three, always
A world checked only from a keyboard is a world whose keyboard experience
is the only one anybody verified. That is how a game ships playable on a
desktop and dead on a phone: not because the touch path was written badly,
but because nothing ever drove it.
So this toolbox covers the three classes symmetrically, and `device` makes
a desktop session present as any of them.
## Driving the game: actions
A game reads its input through the controls its input maps declare —
`move`, `jump`, `sprint`. `action` drives one by name with the value the
game should read, which is how a test or an agent plays a game: the same
call works whatever device the player would hold, and nothing about a
device — which key a map binds, where the pointer is — has to be worked out.
```lua
tools.use("inputSim", "bindings") -- the live controls and their kinds
tools.use("inputSim", "action", "jump") -- tap a button
tools.use("inputSim", "action", "move", { 0, 1 }, 2) -- walk forward for 2 s
tools.use("inputSim", "action", "sprint", true, nil, true) -- hold until `release`
tools.use("inputSim", "fired") -- reported under class "driven"
```
A button takes `true`, a 1-D axis a number, a 2-D axis `{ x, y }`. The
value joins the control like another device: its shaping applies, its
press and release fire, and a context or a suppression that stands the
control down stands it down too. `release` lets go of every driven control.
The device verbs below prove the devices themselves: that a key, a pad or
the touch overlay reaches the control a player would press it for.
## The loop
```lua
tools.use("inputSim", "device", "touch") -- present as a phone
tools.use("inputSim", "bindings") -- what controls are live?
tools.use("inputSim", "layout") -- what is on screen?
tools.use("inputSim", "tapButton", "jump") -- tap it where a player would
tools.use("inputSim", "fired") -- did it reach the game?
```
`bindings` first, always. Nothing is live until a component activates an
input map, so an empty list means no awake component asked for input —
which is a different problem from a control that fires and does nothing.
`fired` is what turns a simulated input into an assertion. A capture can
look identical whether or not the input landed; this cannot. Its `count` is
the number of engine frames the control was active, so a tap that holds a
button across two frames reads 2 for one press. To count presses, subscribe
with `control:onPressed`.
## One argument shape
Every verb here takes its arguments POSITIONALLY, in one order across the
whole toolbox: **what** first — the button, key, stick, trigger, label or
contact id — then **where** as flat `x, y` (or `dx, dy`), then **how long**
in seconds or **how far spread** in frames, then **which pad slot**. Every
optional argument trails. No verb wraps its arguments in an options table,
so a verb's shape is known from having called its neighbour.
```lua
tools.use("inputSim", "click", 0, 400, 300) -- what, where
tools.use("inputSim", "mouseDown", 0) -- the same what
tools.use("inputSim", "touch", 400, 300, 0.5) -- where, how long
tools.use("inputSim", "padStick", "left", 0, -1) -- what, where
```
Every surface that names arguments resolves those names against the same
positional list, so one call is written four ways and reaches the same
slots: `click(0, 400, 300)` in Luau, `{ button = 0, x = 400, y = 300 }`
through `tools.use`, `{ button: 0, x: 400, y: 300 }` through `tools.use` in a
`tool_exec` script, and `--button 0 --x 400 --y 300` in the shell. A verb whose every argument is optional takes `{}` for
"no arguments at all", and a name the verb does not declare is refused with
the ones it does.
## Who the input is for
What this toolbox simulates is the game's input: a key, click, motion, wheel
or touch reaches the scene alone. It reaches the scene whatever a person at
the window has focused — a panel they clicked, a terminal they are typing a
message into — and it reaches no UI widget, so a run driving the game never
types into the person's panel and the person's typing never stands the run
down. Every key, pointer and touch verb takes a trailing `target`:
`"game"`, the default, or `"ui"`, which reaches the UI the way a person's
device does. Driving a UI by its elements — clicking a button, typing into a
field — is the `gui` toolbox's work.
```lua
tools.use("inputSim", "key", "KeyW", 1) -- walks the player
tools.use("inputSim", "key", "KeyA", nil, "ui") -- types into the focused field
```
A mouse button is written either way, index or name: `0` / `"left"`,
`1` / `"right"`, `2` / `"middle"` — the same pair `Zin.state.mouseButtonDown`
reads. A standard pad's button is a canonical position name (`"south"`,
`"dpad_up"`, …), because a standard pad has no index a player could
recognise; a wheel's, a stick's or a button board's own elements are moved
by their index with `padDeviceAxis` / `padDeviceButton`.
## Where a point is measured from
`mouseMove`, `click`, `touch`, `touchDown` and `touchMove` take their
point in physical pixels, measured in the space the input's receiver reads
positions in, so `target` decides it.
With `target` `"game"` (the default) the point is in the space `capture`
reports: the scene's own pixels, measured from the top-left of the picture
a capture returns. That is the space `Zin.state.get().mouse_position` reads
a pointer back in, `Zin.touch.slots()` a contact, `Zin.events` every
pointer and touch event, and the space `worldToScreen` answers in, so a
point read off any of them is a point the others take.
```lua
tools.use("inputSim", "mouseMove", 300, 200)
Zin.state.get().mouse_position -- 300, 200
local id = tools.use("inputSim", "touchDown", 300, 200)
Zin.touch.slots()[1] -- x = 300, y = 200
```
The window can hold the scene inside a rect with editor chrome above and
to the left of it; the verbs carry that offset themselves.
With `target` `"ui"` the point is on the window: the space every UI widget
is recorded in, wherever its screen draws (the window itself, or the
picture a Scene panel presents). A widget's `gui.bounds` rect is in logical
points, and times `ui.pixelRatio()` it is the point to aim at:
```lua
local b = tools.use("gui", "bounds", "play-button")
local r = ui.pixelRatio()
tools.use("inputSim", "click", 0, b.centerX * r, b.centerY * r, nil, "ui")
tools.use("inputSim", "touch", b.centerX * r, b.centerY * r, nil, "ui")
```
`gui.clickElement` does the same by id and refuses a widget the last frame
did not draw where its rect claims, so it is the call for pressing a named
button. The gui pointer verbs speak logical points and convert by the ratio
themselves: `gui.clickAt` takes one, `gui.clickElement` and
`gui.hoverElement` answer the one they aimed at, and
`gui.clickAt(b.centerX, b.centerY)` presses the same place as the `click`
above.
A `macro`'s ops are those same verbs, so an absolute point written for one
is the point the other takes.
A mouse event the primary touch contact drives carries that contact's id
as `touch` in `Zin.events`, so a reader tells a finger's press from a
mouse's.
## Keyboard and mouse
| Tool | What it does |
|---|---|
| `key` | Tap a key — down, optional hold, up |
| `keyDown` / `keyUp` | Hold and release |
| `click` | A full click, optionally at a point |
| `mouseDown` / `mouseUp` | Hold and release a button |
| `mouseMove` | Move the cursor to a point; the delta is what look bindings read |
| `mouseMoveBy` | Move the pointer by a motion, over `steps` frames — repeat it to hold a look axis |
| `scroll` | Turn the wheel |
| `lockPointer` | Lock or release the pointer — mouse-look is usually gated on it |
`keyDown` and `mouseDown` hold until something releases them, and a hold
outlives the call that made it — including a driver task that was cancelled
mid-press. `held` says what is down; `release` puts all of it down at once.
## Touch
| Tool | What it does |
|---|---|
| `touch` | A whole tap at a point |
| `touchDown` / `touchMove` / `touchUp` | One finger, by contact id — several at once |
| `stick` | Push the on-screen movement stick |
| `drag` | Drag across the look zone, spread over frames |
| `pinch` | Pinch or spread two fingers |
| `tapButton` | Tap an on-screen button by its `id`, its `actionName` or its `label` |
`tapButton` takes any of the three names `layout` lists per button. The `id`
and the `actionName` read the same in every language, so a test that names a
button by either keeps working for a player in any language; the `label` is
the words on the button as they read now. It aims at the button's real
centre and raises when no live button answers to the name, listing the ones
that do. That is deliberate: a tap
that silently lands on nothing looks exactly like a control that works.
## Gamepad
| Tool | What it does |
|---|---|
| `pad` / `padOff` | Connect or disconnect a simulated pad |
| `padPress` | Press a button — down, optional hold, up |
| `padDown` / `padUp` | Hold and release |
| `padStick` | Push a thumbstick |
| `padTrigger` | Squeeze a trigger to an analog travel |
| `padDeviceAxis` | Move one of the pad's own axes by index: a wheel, a pedal, a throttle |
| `padDeviceButton` | Push or release one of the pad's own buttons by index |
Buttons are named by POSITION, never by the letter printed on them:
`south`, `east`, `west`, `north`, `left_shoulder`, `right_shoulder`,
`left_trigger`, `right_trigger`, `left_stick`, `right_stick`, `select`,
`start`, `guide`, `dpad_up`, `dpad_down`, `dpad_left`, `dpad_right`. The
same call works whatever pad is connected.
The name passed to `pad` decides which legends a prompt draws, so
connecting `"Sony DualSense Wireless Controller"` is how a scheme's
PlayStation prompts get checked.
A controller that is not a standard pad, a steering wheel with pedals, a
flight stick, a button board, is connected with its element counts and
driven by index:
```lua
local slot = tools.use("inputSim", "pad", "Racing Wheel", { axes = 6, buttons = 25 })
tools.use("inputSim", "padDeviceAxis", 2, 1) -- floor the third axis
tools.use("inputSim", "padDeviceButton", 19, true) -- hold the twentieth button
```
A device's own axes start at 0 unless `rest` says where they rest:
`tools.use("inputSim", "pad", "Pedals", { axes = 3, rest = -1 })` connects a
pedal box with every pedal released, the way a real one reports on connect.
A simulated pad offers rumble unless connected with `rumble = false`, and
force-feedback effects when connected with `force = true`;
`Zin.gamepad.get(slot).rumble` and `.force` read back what a game played on
it.
## Reading back
| Tool | What it answers |
|---|---|
| `device` | Which class the session presents as — and forces one |
| `bindings` | Which controls are live, and which map contributed each |
| `layout` | What the on-screen controls are actually drawing |
| `fired` | Which controls were active since last asked, for how many engine frames, and from which device |
| `held` | What the session is holding down right now, across every device |
`layout` is how a phantom control is caught: a label on screen that no
entry in `bindings` explains is a button nothing consumes.
`held` is how a leftover hold is caught: keys, mouse buttons, fingers, the
stick and connected pads in one answer, with `atRest` true when the session
holds nothing. A control that keeps firing after a take ended reads here as
the key that is still down, so recovering from it is a `release` rather than
a guess at what was pressed.
## Replaying a sequence
A run of events worth repeating becomes a `.inputMacro` asset, so the
same sequence drives the same world on every later check.
| Tool | What it does |
|---|---|
| `recordMacro` | Capture real input for `duration` seconds |
| `saveMacro` | Write an event list to a `.inputMacro` asset |
| `macro` | Play an event list back through the input surface |
| `listMacros` | Every `.inputMacro` asset in the project |
An event is `{ t, op, arg }`. `op` names one of the verbs above that drives
input and `arg` carries that verb's arguments — the value itself when the
verb takes one, a table keyed by the verb's parameter names when it takes
several — so every device class a verb reaches is a device class a macro
reaches. A `touchDown` event's `arg.id` is the name its contact goes under,
and the `touchMove` and `touchUp` events carrying that `id` drive it.
```lua
tools.use("inputSim", "macro", {
{ t = 0.0, op = "pad" },
{ t = 0.4, op = "padDown", arg = "south" },
{ t = 0.6, op = "padUp", arg = "south" },
{ t = 0.8, op = "touchDown", arg = { x = 714, y = 984, id = 1 } },
{ t = 1.2, op = "touchUp", arg = 1 },
})
```
`recordMacro` reads what every device is HOLDING each frame — keys, mouse
buttons, pad buttons, the pad itself, fingers on the glass — and what each
one is MEASURING every `sampleInterval` seconds — mouse motion, the wheel,
thumbsticks, triggers, a sliding contact.
`release` is the reset between takes — it lifts every contact, drops the
on-screen stick, releases every held key and mouse button, and disconnects
every connected pad, so one take never leaks a held control into the next.
It reports how many of each it let go, and `held` reads the same set before
or after.
# client
Your sub-client and the user's client: list, check, create, restart and
delete the clients of this world you work in.
Every agent works in a sub-client (subclient): a headless client of the same
world that the user's editor runs for it. An editor runs one sub-client per
world, which every agent working on that world shares. The tools that run code
(`execute`, `bash`, `capture`, `play`, `edit`, `pause`, `wait`, the file
tools, `use_tool`, `tool_exec` and `input`) run in your sub-client when the
call names no client, so the user's screen never stalls, never shows your
errors, and keeps its own play or edit mode. `client: "user"` on a call runs
it in the user's client, which has the same world open and shows the person
what the call does: a camera move, simulated input or a mode change alters
what they are looking at. Running a call there is your decision whenever the
task needs it (showing the person something, seeing what they see, a test
your sub-client cannot run, or a sub-client that is not available), and it
needs no confirmation from the person. `client: "<id>"` runs a call in
another sub-client.
- `list`: the user's client and every sub-client, with id, state, branch,
scene, start, whose it is and who called it lately, plus the limit and
the memory available.
- `status`: one sub-client, yours when no id is given.
- `create`: start a sub-client under an id you choose, optionally on another
branch, scene, profile or world; `--wait` answers once it is ready. An editor runs
one sub-client per world, so on a world that has one already `create`
answers that one, marked `shared`, and starts nothing.
- `restart`: start a sub-client afresh on the world and branch it is on,
optionally on another scene or profile; `--wait` answers once it is ready.
- `delete`: stop a sub-client and free its process, port, world session and
memory.
`man subclient` explains how sub-clients work.
# component_snapshot
Serialized snapshots of script-component public data.
A component's `public` table is a live proxy — its fields live behind
`__iter` / `__index` metamethods, so copying or JSON-encoding the proxy
directly yields an empty table. This module materializes the plain,
serializable form. It is the script-component parallel to `ecs.snapshot`
(native components).
```lua
local componentSnapshot = require("modules.component_snapshot")
-- one component: live proxy -> plain table
local data = componentSnapshot.snapshot(entity(id).component.get("Camera"))
-- whole entity: { [type] = data }, named/multi instances nested as
-- { [type] = { [instanceName or "__default"] = data } }
local all = componentSnapshot.snapshotEntity(entity(id))
```
`componentSnapshot.plainCopy(value)` materializes ONE live value the same
way — a table behind a proxy is walked into a plain table, every other
value passes through — for callers reading a single field rather than a
whole component.
Serialized form: entity refs become id strings, asset refs become
`{ __ref, name, type }` envelopes, vectors and colors their plain-table
forms; framework functions are omitted. `snapshot` returns nil for a proxy
with no serializable fields.
Persistence (scene serializer, bundle capture, prototype spawn) and
inspection tooling (`debug.inspect`) read component data through this
module. Live gameplay reads and writes stay on the proxy itself via
`entity(id).component.get` / `getAll`.
# renderer
GPU-resource factory plus CPU codec/store wrappers — the GPU/CPU half of the asset↔resource split. Moves a resource Disk → CPU → GPU in explicit steps and returns inert handles describing each live resource. assetType behaviours, components, and every other module call `renderer.*`.
A resource moves through three states, each an explicit call:
- `ref:load()` → `renderer.<res>.loadCpu(ref)` decodes the asset's primary content into the guid-keyed CPU store and returns a CPU handle (holds only a guid plus dims/counts and the read/encode/unload ops).
- `renderer.<res>.create(cpuHandle | rawData, guid?)` uploads CPU → GPU, keyed by guid, and returns a GPU handle. `create` never takes an `AssetRef` — load the CPU first.
- `renderer.destroy(handle)` frees the GPU resource; a CPU handle's `:unload()` frees the CPU copy.
A `MeshHandle` / `TextureHandle` / `MaterialHandle` is an inert data record (`{ kind, category, guid, name, ... }`) describing one live GPU resource. Every GPU op lives on `renderer.*` and takes the handle.
Anywhere a call names a resource it takes any of the forms you already hold — the handle `create` returned, the CPU handle `loadCpu` returned, the guid, or the `AssetRef` `asset.resolve` returned. Handles compose: what one call hands back, the next call accepts.
## Types
- `Aabb` — `{ min = {x,y,z}, max = {x,y,z} }`.
- `MeshHandle` / `MeshCpuHandle` / `MeshGeometry` / `MeshBuffers`.
- `TextureHandle` / `TextureCpuHandle` / `TexturePixels`.
- `MaterialHandle` / `MaterialContent`.
## renderer.mesh
- `encode(geom) -> string?` / `decode(zmsh) -> (geom?, errmsg?)` — the ZMSH CPU codec.
- `loadCpu(ref) -> MeshCpuHandle` — Disk → CPU load (called by `meshRef:load()`).
- `create(src, guid?) -> MeshHandle` — create or fetch a GPU mesh from a `MeshCpuHandle`, raw geometry `{positions, indices, normals?, uvs?, colors?}`, compute buffers `{vertexBuffer, indexBuffer, vertexCount, indexCount, aabbMin?, aabbMax?}`, or a `MeshHandle`.
- `geometry(mesh) -> MeshGeometry` — the mesh's vertex data, the read that pairs with `create`.
- `update(handle, src) -> MeshHandle` — overwrite the GPU resource in place under the same guid.
- `readback(mesh, into?) -> MeshCpuHandle`: GPU → CPU recovery of a runtime mesh's geometry. `into` lands the copy under a CPU-store key of the caller's own, which stays resident until the caller unloads it, whatever re-registers or unloads the mesh itself.
- `isResident(mesh) -> boolean` / `isCpuResident(mesh) -> boolean`.
- `clusters(mesh)` / `scheduleClusters(mesh, opts?)` / `clusterBakes()` — the mesh's level of detail. Every static mesh draws through clusters, and a baked hierarchy of them (`kind = "dag"`) is cut by the GPU per view and per instanced copy, so detail falls off continuously with distance with no authored LOD meshes; `kind = "lod0"` draws full detail at every distance until a bake lands. `guides { path = "topics/world-detail" }` covers which meshes bake on their own.
Geometry moves in four directions, two per axis — DATA the caller holds, and the geometry of a mesh the ENGINE holds:
| From | → bytes | → geometry |
|---|---|---|
| geometry (data the caller holds) | `encode(geom)` | — |
| ZMSH bytes (data the caller holds) | — | `decode(zmsh)` |
| a mesh the engine holds | `encodeCpu(mesh)` | `geometry(mesh)` |
`geometry(mesh)` reads the resident CPU copy when there is one and reads the geometry back off the GPU when there isn't (yielding a frame or two), so a mesh straight out of `create` answers it:
```luau
local h = renderer.mesh.create({ positions = P, indices = I, tangents = T })
local geom = renderer.mesh.geometry(h) -- { positions, indices, tangents, ... }
```
An optional stream is present only when the mesh carries one. The GPU vertex layout has no "unset" — it holds a zeroed tangent, a zeroed skin binding, and a second UV set copied from the texture UVs for every mesh — so a stream saying only what its absence already says is reported absent. `geom.tangents == nil` is therefore the answer to whether a mesh has a tangent basis, and `geom.uvs1 == nil` to whether it has a second UV set.
## renderer.texture
- `encode(rgba, width, height, opts) -> (string?, errmsg?)` / `encodeFromImage(bytes, opts) -> (string?, errmsg?)` / `decode(ztex) -> (rgba?, width?, height?)` — the ZTEX CPU codec.
- `withSampler(ztex, { filter?, wrapU?, wrapV?, anisotropy? }) -> (string?, errmsg?)` — the same payload with only its recorded sampler state changed; every level is byte-identical.
- `loadCpu(ref, encodeOpts?) -> TextureCpuHandle` — Disk → CPU load with per-pixel access.
- `create(src, guid?) -> TextureHandle` — from a `TextureCpuHandle`, raw pixels `{rgba, width, height, srgb?}`, a `TextureHandle`, or render-target dimensions `{width, height, name?}` (an empty GPU texture a render pass writes into).
- `update(handle, src) -> TextureHandle`, `destroy(handle)`, `capture(handle) -> string` (CPU readback result key), `readback(texture) -> TextureCpuHandle`, `isResident(texture) -> boolean`.
## renderer.material
- `create(content, key) -> MaterialHandle` — register or update a material's GPU record (`content = { shader, properties, textures, aliases?, name? }`) under its canonical registry key.
- `animatedTexture(texture, opts?) -> MaterialHandle` — a material that PLAYS a layered texture: its layers bound as the frames, its timing beside them, the built-in `animatedTexture` shader turning the clock into the layer showing now. One call from an imported GIF / APNG / animated WebP to a material an entity can wear. `guides { path: "topics/animated-images" }` is the whole surface.
- `setProperty(key, name, value)` — push one changed uniform.
- `setTexture(key, slot, ref)` — push one changed texture slot (the texture must already be GPU-resident).
- `destroy(key) -> boolean` — drop the definition filed under `key`, so `describe` and `list` stop answering for it. A surface already wearing the handle goes on drawing it.
A `MaterialHandle` and its `guid` are two different currencies. What a surface wears is the HANDLE — `Model:applySessionMaterial(handle)`, or a Model's `material` field. The handle's `guid` is the material's registry key, which is what `setProperty`, `setTexture`, `describe` and `destroy` take. A component field resolves an asset, so a bare registry key in one leaves the component waiting for an asset to register under that name.
## renderer.instanceData
Four `vec4` lanes of generic shader data per entity — the channel that lets ONE material serve many entities that differ in a value, instead of one material per entity. A surface shader reads lane `i` back as `input.shader_data[i]`, and the engine attaches no meaning to what a lane holds.
- `laneCount() -> number` — lanes per entity, so a lane index runs `0 .. laneCount() - 1`.
- `set(target, lane, x, y?, z?, w?)` — write one lane of an entity's block. `target` is an entity proxy or an entity-id string naming a live entity; `y` / `z` / `w` default to 0. The lane reaches the block where the call is made, and the draw on the next frame.
- `clear(target)` — drop the entity's whole block, so its draws read zero again. Takes an entity that has already gone, and does nothing for one holding no block.
A lane index outside the block, or a target no live entity answers to, is an error at the call rather than a write that lands nowhere. A feature picks the lane indices it owns and names them where it writes them: `@builtin::systems.globalIllumination.lightmap` holds lane 0 for a receiver's atlas rect and lane 1 for its layer and enable flag, which is the shape to copy.
The same lanes reach a GPU-driven population through `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, on slots no entity owns.
## renderer.featureTexture
The texture analogue: a shared `rgba16f` 2D array every surface shader can sample as `zero_feature_texture(uv, layer)`, and the array a `SpotLight` projects a layer of through its cone via `cookieLayer`.
- `configure(width, height, layers)` — size the array. A call for the size it already has is left alone; one that changes the size reallocates, and the replacement is zeroed, so it empties every layer in the array — the layers other features and other cookies own along with your own.
- `setLayer(layer, textureKey, x, y)` — copy a GPU-resident `rgba16f` texture into one layer at that offset, GPU to GPU with no readback. Several small images pack into one layer at different offsets.
- `state() -> { width, height, layers, filled, fills }`: the extent the array carries and `filled`, the ascending 0-based indices of the layers a fill has landed in since it was last sized. One array is shared by every feature and every light cookie, and it has no allocator, so this is what a feature asks to tell whether the array it sized and filled is still the array it is writing into. A layer some other `configure` emptied leaves `filled` without it, which is what separates that from a fill that never landed. What it describes is the array a shader samples: the source texture a `setLayer` copied from is a GPU resource of its own and keeps the bytes it was written with, so `filled` is the reading that answers whether the layer behind a `cookieLayer` is live right now. `fills` counts the fills that have landed in each layer since the array was last sized, `fills[layer + 1]` for a 0-based layer: a fill of a layer already holding content leaves `filled` as it was and moves this count, so a feature re-filling its own layer reads its fill arriving here. Measured at the end of the last rendered frame, like every reader below.
```luau
renderer.featureTexture.configure(256, 256, 4)
renderer.featureTexture.setLayer(0, "my_gobo", 0, 0)
-- ... elsewhere in the scene, another feature sizes the array ...
local ft = renderer.featureTexture.state()
if ft.width ~= 256 or table.find(ft.filled, 0) == nil then
-- layer 0 was emptied under us: size it back and re-fill.
end
```
## Reading back what the renderer did
Every call above states an intention. What the renderer made of it is a separate
document, published once per frame and read through these:
- `drawDiagnostics() -> { DrawDiagnostic }` — every renderable that is NOT
drawing what its material says. A surface rendering as the magenta
placeholder, one the renderer could bind nothing for, and one drawing a
program whose most recent compile failed all land here, each naming the entity,
the program asked for, the program bound, and the one cause. It covers every
renderable the renderer holds, whether or not a camera reached it — a row with
`observed = false` and `outcome = "notDrawn"` is the renderer's own resolution
for one this frame drew nowhere, so a broken surface off-screen reads the same
as one in frame. An empty result means every renderable the renderer holds is
drawing the program its material named. **Start here when a surface looks
wrong.**
- `material.renderState(key) -> MaterialObservation?` — the blend / cull /
topology / queue / depth key the renderer holds a material under, and whether
a pipeline exists for it. `nil` means the renderer holds no material under
that key, which is what writes reaching nothing on screen look like. `index`
is the material index its row is filed under, and `textures` the texture key
each slot of that row names, so a `setTexture` the renderer has taken up
reads there.
- `materialCost() -> { MaterialObservation }` — draws, instances, placeholder
draws and material-owned bind groups (`binds` set, `bindsElided` skipped) per
material, over the published frame.
- `shaderCost() -> { ShaderCost }` — pipeline build time and permutation count
per program, summed since engine start, beside the compile gate's word.
- `observe() -> RenderObservation` — the whole document the four above read.
`/zero/runtime/generated_materials` serves the same document as files. Every
`notDrawn` row names why no pass reached it in `notDrawnReason`:
`meshNotResident`, `hidden`, `layer`, `culled` or `viewCull`.
## renderer.destroy
- `destroy(handle) -> boolean` — free the GPU resource behind a `MeshHandle` / `TextureHandle`, routing by the handle's `category`.
## Parts
The module is a folder of parts, each a module of its own that `init.luau` requires:
- `renderer.refs`: guid minting and the coercion from whatever names a material, mesh or texture to the key the renderer indexes it by.
- `renderer.sources`: the `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take, and the bounds and counts raw geometry implies.
- `renderer.shading`: the readings `renderer.shadingOf` builds out of the document the renderer publishes.
## Usage
```luau
local renderer = require("@builtin::modules.api.engine.renderer")
local gpu = renderer.mesh.create({ positions = { ... }, indices = { ... } })
renderer.destroy(gpu)
```
# cutscene
Drive the cutscene playing now — put one on screen without waiting for whatever
would have triggered it, land on an exact moment inside it, freeze it while you
work on the frame, and read where its clock is.
A cutscene is written to be watched from its start, which is the whole reason
this toolbox exists: reaching the shot at 0:48 by watching costs 48 seconds
every iteration, and `cutscene.seek 48` puts it on screen in one call.
## The loop this is for
```
cutscene.play mygame.scenes.intro -- put it on screen
cutscene.seek 6.5 -- land on the shot you are working on
cutscene.pause -- stop the clock and the scene; the frame stays put
… edit the cutscene module via the VFS …
cutscene.play mygame.scenes.intro -- play it again on the edit
capture -- look at the result
```
`cutscene.rate 0.25` runs a fast move slowly enough to read; `cutscene.rate -1`
runs it backwards.
## The tools
| Tool | What it does |
|---|---|
| `play <module> [paused]` | Play a cutscene from the module its definition is returned from. |
| `status` | Name, clock, shot, progress, paused, rate. |
| `seek <t>` | Land on an exact moment. The frame is re-derived, not fast-forwarded to. |
| `pause` / `resume` | Freeze the clock and start it again. |
| `rate <r>` | 1 real time, 0.25 slow motion, -1 backwards. |
| `skip` | Skip to the closing fade, the way a player does. Cues past here still fire. |
| `stop` | End it and give back the camera, the overlay and the player's controls. |
## Reaches the cutscene you are watching
The clock belongs to whichever scope started the cutscene — a scene entrypoint,
a `CutsceneTrigger`, an `execute`. These tools reach it through engine state
rather than through a module handle, so `cutscene.pause` freezes the cutscene on
your screen rather than a private copy of it.
## Requires play mode
A cutscene runs in play. In edit there is no clock to drive, and every tool here
says so rather than pretending it moved something.
# decals
Registry of oriented **box decal projectors**. Each entry is an entity whose
Transform is an oriented projection box plus the **material** the projector
stamps. The `@builtin::renderFeatures.decals` render feature reads this registry
every frame, groups the projectors by the material they share and packs them
eight to a pass. Each pass reconstructs a covered pixel's world position from
scene depth, transforms it into each projector's box space, and shades it from
the material — projecting a textured material's texture (or a flat-colour
material's colour) onto every surface inside the box, fading on faces turned away
from the projection axis so the decal wraps the surfaces facing the projector.
A pass is enqueued per **channel the material provides**: base colour when the
material binds a `base_color_texture` or states a `base_color` its shader does not
declare, while that colour's alpha covers something; emissive when it binds an
`emissive_texture` or states a non-black `emissive`. A material that provides
neither stamps nothing and says so in the log.
The base colour is part of the surface it lands on: it is stamped before
anything shades, into the `@scene.decal` channel, and each opaque surface takes
it into its own base colour before it is lit. A decal in shadow reads as dark as
the surface under it, a decal under a bright light as bright, on the forward and
the deferred path alike, and on the deferred path `@scene.material` carries the
decal's colour. The emissive is light the decal gives off, added over the lit
surface whatever light reaches it.
The `@builtin::components.DecalProjector` component is the authoring front end;
it calls into this registry. Use the module directly for code-driven projectors.
A projector's entry lasts as long as its entity: when the entity is despawned,
whatever despawned it, its id leaves the registry.
## Surface
| Function | Meaning |
|----------|---------|
| `set(e, opts)` | Register entity `e` (ref or id) as a projector. `opts = { material, opacity? }`. Re-calling updates it. |
| `clear(e)` | Stop projecting from `e`. |
| `clearAll()` | Remove every projector. |
| `has(e)` | Whether `e` is a registered projector. |
| `entries()` | The live `{ [id] = { material, opacity } }` registry (read by the feature). |
## Example
```lua
local decals = require("@builtin::modules.decals")
local p = entity.spawn("splat")
p.localPosition = { 0, 3, 0 }
p.localScale = { 5, 5, 4 }
p.localRotation = { 0.70710678, 0, 0, 0.70710678 } -- project down
decals.set(p.id, { material = "@builtin::materials.decal_default", opacity = 1.0 })
```
# scene_module_inspector
The `SceneModule` component's card on an entity. It replaces the card's generic
`settings` section with one built from the bound `.sceneModule`: the module's
identity, the file that states the placement, one editable row per **declared**
input, and a Rebuild action. The component's `inspector.luau` returns this
module, so the editor's inspector framework
(`edui.inspector.componentSections`) shows it wherever the component is on an
entity.
A sceneModule declares its own inputs, so the set of properties a placement can
edit is per module. Each declared input gets one row: a bool row for a bool, an
enum row for a closed set, a number row for a number, a text row otherwise.
Editing a row writes the value into the component's `params`, which re-runs the
build in place.
`buildFieldSpecs(declared, params)` is the pure row mapping: one spec per
declared input carrying its kind, its current value (the param override when
set, else the declared default), and the members a closed-set input accepts.
```luau
local Inspector = require("@builtin::modules.editor.scene_module_inspector")
local specs = Inspector.buildFieldSpecs(moduleRef:inputs(), { seed = 3 })
```
`statedIn(entityId)` answers which file states a placement's params: the
`build.luau` or `init.luau` of the build that placed the entity, or nil for a
placement an author made.
# globalIllumination system
Production-grade baked global illumination for the Zero engine. Two
complementary techniques share one baking pipeline:
- **Lightmaps** — bake full irradiance (direct + multi-bounce indirect)
into a per-entity texture sampled in UV space. For static surfaces.
- **Volume probes** — path-trace incoming radiance at points in a 3D
grid, encode as spherical harmonics (SH L2), and publish the field
into the renderer's irradiance-volume set: every standard-PBR fragment
inside the volume samples the nearest probes by world-space position.
For moving entities and any static surface without lightmap UVs.
Both bake the same lighting model from the same scene: every sample is
path-traced through the scene BVH for up to `bounces` surface
interactions. Each path vertex contributes its emissive plus its albedo
times the shadowed direct light there, so the bake captures indirect
light, color bleed between surfaces, emissive surfaces acting as area
lights, and sky occlusion — the transport that is too expensive to
evaluate at runtime.
## Mobility decides who bakes
`Model.mobility` (`"auto"` | `"static"` | `"movable"`) is the single
selection axis for the whole system:
- **Static geometry** receives lightmaps and occludes / bounces baked
light. `Lightmap.bakeAll()` bakes every static receiver — no
per-entity setup.
- **Movable geometry** (and every player / skinned character) samples
the published probe fields — renderer-level, no per-entity setup. It
never bakes: a moving mesh baked as an occluder would freeze its
shadows into the world and walk away from them.
`"auto"` derives the answer per entity: a non-static `Physics` body, a
`SkinnedModel`, a `ClipPlayer`, a `Mover`/`FreeMover`, or a non-world
runtime participation (players, editor viz, prototypes) makes it
movable, and so does motion: geometry the running world places on more
than one frame (a script's update walking it in play, an engine system
posing it), or carries on an ancestor it places so, reads
`entity.inMotion` true and resolves movable. Everything else is static,
a prop a script places once included. An explicit `"static"`/`"movable"`
on the field overrides the derivation — that is the exclusion switch
when the derivation gets an entity wrong.
## Files
```
globalIllumination.package/
VolumeProbe.component/ -- define a probe volume (bounds + resolution)
BakedLighting.component/ -- keep the bake in step with the scene
lightmap.module/ -- Lightmap.bake / .bakeAll / .applyFromAsset / .clear
volumeProbe.module/ -- VolumeProbe.bake / .restore / .retire
scenarios.module/ -- Scenarios.capture / .blend / .mix
skyResponse.module/ -- SkyResponse.calibrate / .apply / .combine
bakeState.module/ -- BakeState.affects / .invalidate / .rebake
bakeViz.module/ -- the two debug overlays that make a bake visible
baking.module/ -- Shared utilities: light gather, surface
-- attributes, static mesh-instance gather
lightmap_bake.computeShader/ -- Compute shader: per-texel path-traced bake
probe_bake.computeShader/ -- Compute shader: per-probe path-traced bake
```
## A sky that moves without a re-bake
A probe bake follows each path until it escapes, and what escapes carries the
sky's colour — so an ordinary bake fixes the sky the moment it finishes.
The sky enters as `throughput * sky` where a ray escapes, and `throughput` does
not depend on the sky, so the field splits exactly, per channel:
```
field(sky) = lights + sky * aperture
```
```lua
local skyResponse = require("@builtin::systems.globalIllumination.skyResponse")
skyResponse.calibrate(volId) -- two bakes, once
skyResponse.apply(volId, { 0.3, 0.6, 0.9 }) -- no bake
```
`SkyResponse.component` is the authored form: calibrate once, then move
`skyR` / `skyG` / `skyB`.
Both terms come from bakes at the same settings, and the bake seeds each path
from the probe and sample index alone — so the two runs trace the same paths
and the subtraction that isolates the aperture carries no sampling residual.
## Lighting scenarios
A volume holds one bake, so a scene lit for noon cannot become a scene lit for
dusk without baking again — which takes far longer than a transition is allowed
to. Capture each bake under a name and blend the captures:
```lua
local scenarios = require("@builtin::systems.globalIllumination.scenarios")
-- light the scene for noon, bake, then:
scenarios.capture(volId, "noon")
-- light it for dusk, bake again, then:
scenarios.capture(volId, "dusk")
scenarios.blend(volId, { noon = 0.25, dusk = 0.75 })
```
`LightingScenario.component` is the authored form of the two-state case: name a
`from` and a `to` and drive `blend` from 0 to 1.
Irradiance adds, so blending the SH coefficients is the same as blending the
light that produced them. Each coefficient's fourth lane carries the probe's
per-axis visibility reach rather than light, and is taken whole from the
heaviest-weighted scenario — the mean of two distances describes no wall that
exists.
## A bake stays true to its scene
A bake is a photograph of a moment. Move a baked wall and its lightmap
goes on describing where the wall used to be — the shadow it cast stays
painted on the floor it no longer touches.
So a bake maintains itself. `BakedLighting` watches the engine's
authored-change feed (`layers.onEntityChanged`) and reacts the moment an
edit reaches the bake: the artifacts that described the old scene are
dropped, the withheld lights come back, and the scene re-bakes once the
edits settle. The bake attaches that component itself, so a scene that
has been baked is a scene that maintains its bake — there is nothing to
remember to run.
Dropping the artifacts (rather than flagging them) is what makes the
staleness visible: the viewport goes from baked to honest realtime light
the moment the edit lands.
Static geometry and every light the bake consumes reach it. Movable geometry
and dynamic lights never entered one, so editing them reaches nothing.
`BakeState.affects` is the answer, measured against a signature of what
the bake actually reads — which is also why the bake writing its own
bookkeeping back onto the entities it just baked cannot re-trigger it.
Turn off automatic re-baking (invalidation stays) with:
```luau
entity.find("scene").component.add("BakedLighting", { autoBake = false })
```
## Seeing the bake
Baked lighting is the one thing in a scene with no silhouette — texels on
surfaces and coefficients in a grid — so "did this actually capture the
room?" is otherwise a question you answer by reasoning rather than by
looking. Two overlays answer it directly, in the editor's Visualization
panel:
- **Baked Probes** — every baked probe drawn where it sits, tinted by the
light it captured, inside its volume's bounds. Light falling off through
the volume becomes visible and a dead probe reads as a black dot.
Displayed on a gamma curve: indirect light spans orders of magnitude, so
a linear scale against the brightest probe would draw most of a room as
black and claim a good bake captured nothing.
- **Lightmapped Surfaces** — a box around every surface currently drawing
baked texels, so lightmapped and probe-lit geometry are told apart at a
glance.
Both appear in the panel only while the scene holds what they draw. An
unbaked scene lists neither; baking makes them appear. That comes from
`debugViz.registerProvider(name, fn, { label, default, available })` — a
package contributes an overlay and declares when it has something to
show, without the debug driver needing to know it exists.
## How a bake works
1. `Baking.gatherMeshInstances` collects every static mesh-bearing
entity as `{ guid, transform, attributes }` — the attributes carry
the surface's linear albedo (base_color × average base-color texture
color) and emissive, read through the material's own asset behavior.
2. `compute.buildBvh` builds the scene BVH engine-side and uploads the
node + triangle buffers; each triangle carries its instance's
attributes, so the kernels know how every surface reflects and emits.
3. The bake kernel runs one thread per texel (lightmaps) or probe
(volumes). Each thread traces `samples` paths of up to `bounces`
surface interactions, with shadowed next-event estimation at every
vertex and sky on escape.
4. The work is planned, not dispatched whole. `Baking.planChunks` splits it
into dispatches that each stay inside a per-frame ray budget
(`Baking.RAY_BUDGET_PER_FRAME`, 2^20 estimated ray traversals), sized from
a cost model (`Baking.lightmapRays`, `Baking.probeRays`: a lightmap texel
spends `17 + 64 * direct + 64` rays on direct light and contact occlusion
and `bounces * (1 + lights)` per chain; a probe spends `bounces * (1 +
lights)` per sample). Each dispatch carries its stage and range in the
kernel's `params` uniform, and the running sums live in the bake buffer
between dispatches, so how the work was split does not change the result.
5. A `Baking.newGpuScheduler` issues the dispatches, one per pass, a frame's
worth at a time. It waits for the kernels to compile first, ends each frame
with a fence (a read of a one-vec4 buffer the batch records after the
frame's dispatches), keeps at most `Baking.MAX_FRAMES_IN_FLIGHT` fenced
frames queued, and checks the render device on every wait. A device that
was lost or replaced raises `[Bake] the render device was lost during the
bake` with what the device reported (`renderer.deviceErrors`), and
releases what the pass made. The budget bounds each frame, not the bake: a
bake of billions of rays is hundreds of frames of work, which is what keeps
the device alive on an integrated GPU and in a browser.
6. A receiver lights up when its texels are read back with the resolve's
completion flag set. Its bake buffers (144 bytes a texel) are freed once the
texels are persisted, and a `bakeAll` starts a receiver only when what it
holds fits half the device's memory budget (`Baking.bakeLimits`).
### What a device bakes
`renderer.deviceLimits()` states the largest buffer, the largest storage
binding, the workgroups per dispatch and the memory budget the device affords.
The largest lightmap a bake makes is the largest power of two within the atlas
page whose bake output (64 bytes a texel) fits one storage binding (a baseline
WebGPU device binds 128 MiB, which holds a 1024 lightmap and a 2048 one needs
more) and whose bake (144 bytes a texel) fits the bake memory budget. A derived
resolution is cut there with a warning naming the limit; a pinned `resolution`
past it raises.
### When a bake fails
A bake raises with its cause: the stage, a lost device, a dispatch the engine
refused (a buffer past the storage binding limit is refused by name before it
can invalidate the frame's command buffer), an error the device reported. It
leaves nothing applied. `BakeState.rebake` drops the artifacts its stages left
and posts `bake.rebake_failed` instead of "baked lighting is current again";
`baking.all` raises naming each stage that failed; `VolumeProbe.autoPlace` raises naming
the volumes that failed when any did, and marks no light baked. A failed automatic re-bake holds
automatic re-baking until an explicit bake succeeds.
## Quick start
### Lightmap
```luau
local Lightmap = require("@builtin::systems.globalIllumination.lightmap")
-- Bake every static receiver in the world. Without `resolution` each surface
-- derives its own from its area at 32 texels per metre, rounded up to a power
-- of two and capped by what the device can bake.
Lightmap.bakeAll({ samples = 32 })
-- Pin a resolution (a power of two from 32 up to what the device bakes) and, when
-- a scene wants a different pace, the per-frame ray budget: a larger budget
-- finishes in fewer frames, a smaller one leaves more of each frame to the
-- editor.
Lightmap.bakeAll({ resolution = 128, samples = 32, rayBudget = 2 ^ 21 })
-- Bake a single static entity
Lightmap.bake(floorId, { resolution = 256, samples = 64 })
-- Tear down (frees the bake resources + restores the original material)
Lightmap.clear(floorId)
```
### Volume probes
```luau
local VolumeProbe = require("@builtin::systems.globalIllumination.volumeProbe")
-- Author a probe volume that covers a room
local vol = entity.spawn("level_probes")
vol.localPosition = { 0, 0, 0 }
vol.component.add("VolumeProbe", {
sizeX = 20, sizeY = 6, sizeZ = 20,
resX = 8, resY = 4, resZ = 8,
})
-- Bake: publishes the field renderer-wide and persists it into the
-- scene's baked-lighting container. Every entity inside the bounds
-- receives it — no per-entity binding.
VolumeProbe.bake(vol.id, { samples = 256 })
```
## What's static vs dynamic
| Quantity | Static at bake time | Dynamic per frame |
|---|---|---|
| Geometry positions / rotations | yes | no |
| Lights (positions, colour, intensity) | yes | no |
| Sky / ambient values | yes | no |
| Material base colour | no | yes (modulated against lightmap) |
| Object position (inside a probe volume) | n/a | yes (samples nearest probes each frame) |
Re-bake when any of the "static" inputs change. Lighting changes that
are too dynamic to bake (e.g. flickering torch) should be added on top
of the baked term as additional realtime lights.
## Engine integration
This package is Luau / WGSL over generic engine capabilities: compute
shader dispatch, `compute.buildBvh` (scene BVH with per-instance
attributes), component lifecycle, the renderer's irradiance-volume set
(`lighting.setProbeVolume`), and the baked-lighting container asset
(`lightmapData`).
## See also
- `man shaders` — the WGSL bind-group layout these shaders extend
- `man compute` — compute dispatch + buffer management
- `man /Light` — the Light component baked into the result
- `man /Material` — material registry that lightmaps and receivers extend
# prototype_lifecycle
The play-mode invariant for authored player prototypes and EditorOnly entities. In play a PlayerPrototype subtree is the clone source, not a live scene entity: the scene loader spawns it only in edit, and the spawn-on-join flow instantiates a clone per joining user in play. This module deactivates and hides any prototype still live when play begins (the fallback when the loader spawned one) and every EditorOnly entity, so neither is simulated nor rendered in play; in edit both are fully live. Runtime clones are tracked here and despawned on the return to edit.
Location: `src/lua/lib/modules/api/engine/prototype_lifecycle.module`
# modules.memory
Agent memories in two scopes. Personal memories (`scope = "personal"`) are
the signed-in person's own, kept the same way in their home world's
authoring folder (shown at `/zero/home/<owner>/.authoring/memory/`); the
engine's trusted runtime keeps them: it runs each verb of their store
(`memory.personal`) only for a tool call of the person's own agent, shows the
person each change, and refuses every other caller naming why. `store(place)`
is the store of one scope, and every change keeps the version it replaced in
`memory-history/` beside it (`history`, `restore`) and a record of itself
there (`changes`, `change`, `undo`).
World memories: what a world's writers and their agents keep for each other
across conversations (decisions, conventions, the layout, what is done and
what is left). Each entry is one markdown file in the world's authoring
folder, `/zero/source/.authoring/memory/`, opened by a header block:
```markdown
---
name: lighting-conventions
description: Scenes use one sun at 45 degrees and moodLight presets.
agent: terrain
harness: dotbot
person: ada
updated_at: 2026-11-12T10:00:00Z
---
The body, markdown.
```
`name` is unique in the world (lowercase letters, digits and dashes, at most
64 characters), `description` is the one line the brief shows (at most 200
characters), and the body holds at most 16 KiB. The world keeps at most 256
entries and 1 MiB of them. A new entry's file is named by an id derived from
its name, the next id when another entry's file holds that one; a file a
person writes there by hand is an entry too, named by its header (or by its
file name when it has none) and read, edited and removed by that name.
Every read answers the entry's `revision`, the checksum of its file as
stored. Replacing an entry takes the revision it was read at, and a write
over a newer one answers the current entry instead; `edit` replaces one
occurrence of a text in the body, so agents changing different parts of an
entry do not overwrite each other. A write whose text reads as a credential
(an API key, a token, a private key block, a password field with a value) is
refused, naming what it found.
The folder is the world's authoring folder, so the world's writers and their
own code (the editor, an agent's tools, `execute`) reach it, code a world
ships never does, and no pack, export or play session carries it.
`brief()` is the index every agent working in the world is given when its
conversation starts and again after an entry changes.
Every write, edit, removal, restore and undo is also recorded as one JSON
file in the scope's `memory-history/` (`/zero/source/.authoring/memory-history/`
for the world), beside the folders of earlier versions: the kind of change
(created, replaced, edited, removed, restored, undone), the entry's name and
file, who made it (agent, harness, person; a person's own edit in the editor
names the signed-in person) and the entry's file as it stood before and
after. The record is written before the change, so a change the history
cannot record is refused, and each changing answer names it as `change`.
`changes(scope, limit?)` lists the newest first, `change(scope, id)` answers
one with both versions, and `undo { id, revision?, scope? }` puts the entry
back byte for byte as it stood before the change: a created entry is
removed, any other brought back. An undo over a later change writes nothing
unless `revision` names the revision the entry stands at now (`absent` when
it is gone), and answers both versions instead. A scope keeps the
`CHANGES_MAX` (64) newest changes.