Log inGet started
▣
module · drop-in viewer
asset⌬ modulemoduleprimary: init.luau·part ofprocnode engine.procNode·originates fromworld 07158574-5…

engine

No description provided.

by◐lumi·posted 1mo ago
What it does

No description provided yet.

Interface

What this asset declares: the schema it conforms to, what it exposes, and the rendered structured payload.

conforms to

zero/source-extract/v2

io engine: the engine API functions the core reading and writing nodes call through the Luau node. Every function answers plain Luau tables. A column of values is a list of numbers (Float), a list of `{ x, y, z[, w] }` records (a vector column) or `{ type = "String", values = { ... } }`, which the calling node hands to `op.transfer.upload`.

procgen( ) → any

behaviorOf(assetType: string) → any

argtypedescription
assetTypestring

graphOf(assetType: string) → any

argtypedescription
assetTypestring

convertibleTypes(records: any) → void

Every asset type whose behavior states a graph conversion, by its short name and sorted.

argtypedescription
recordsany

instantiableOf(ref: any, assetType: string) → any

The asset as a reference that can instantiate, or nil when its type defines no `instantiate`.

argtypedescription
refany
assetTypestring

nativeRows(id: string, catalog: { [string]: boolean }) → void

The native components of a live entity as the `ecs` rows a saved record lists: each public component the entity holds (`ecs.snapshot`, the row a saved record states), a field holding a GPU handle written as the guid of its asset. `Transform` is left to the record's own position, rotation and scale.

argtypedescription
idstring
catalog{ [string]: boolean }

instantiatedRecords(held: any) → void

The entities an asset's `instantiate` produces, as the records `elementsOf` takes: the script components and attributes `EntityRecords.compose` captures, and each entity's native rows. The asset is instantiated under a temporary root that is internal, hidden and inactive, read, and despawned before this returns, whether the read succeeds or raises.

argtypedescription
heldany

importAsset(ref: any, options: any?) →

An asset as the value a graph uses, in the form its asset type states in its `graph` conversion: `import` (a record, of which the members the type names in `columns` are lists the graph puts on the device: a texture's texels, a landscape's heights), else the record kind it names in `record` (one element holding the record, as the node that makes one answers: a material), else `read` (the value itself: a mesh as a Geometry). An asset whose type states no `graph` and defines `instantiate` is instantiated, and the entities that produces are answered as elements, the form `elementsOf` answers. states none), which `transfer.upload` puts on the device and `withColumns` puts back.

argtypedescription
refanyAn AssetRef: the reference a graph writes with `asset.resolve("<identity>", "<type>")`.
optionsany?What the type's conversion reads the asset with, passed on as it is (a landscape's `cols` and `rows`).

examples

local value, columns = engine.importAsset(meshRef, {})

vec(value: any, n: number, fallback: { number }) → void

argtypedescription
valueany
nnumber
fallback{ number }

guidRef(value: any, category: string) → any

argtypedescription
valueany
categorystring

elementsOf(records: { any }) → any

The elements a list of saved entity records stands for, in the form `io.output` stands and `io.export` saves: one point a record, numbered from 0 in record order, carrying `name`, `parent` (the number of the record it hangs under, -1 for none), `P`, `orient` and `scale`, the `Mesh` and `Material` it draws with, and one attribute per script component, named after the component's type and holding its data. What a record draws is read the one way every saved record is read (`EntityRecords.drawn`): its native `Mesh` and `Material` rows, or the mesh and material of its `Model`, whose shadow settings ride on the `Mesh` record and which then carries no attribute of its own. The detail attribute `reported` lists what an element does not carry: a native row of any other component, a `Model` that is hidden (that element carries no `Mesh`), a `Model` field that dresses the draw (tint, outline, light channels, mobility) set away from a fresh `Model`'s, and a second mesh on one record. A `SkinnedModel` stays an attribute of its own.

argtypedescription
records{ any }The records: `{ name, original_id, parent_id?, position?, rotation?, scale?, components?, ecs? }`.

examples

local elements = engine.elementsOf(bundleRef:getTemplate())

populationElements(ref: any) → any

A population as the copies it places: one point a copy, posed by `P`, `orient` and `scale` (taken from its matrix), `Mesh` holding the number of the piece it draws, `Material` the material that piece draws with, and the detail `labels.Mesh` listing the pieces (each `{ mesh = <reference> }`) and `population` naming the attributes, the form `instances.to_points` answers.

argtypedescription
refanyThe population asset.

examples

local copies = engine.populationElements(populationRef)

m(index: number) → number

argtypedescription
indexnumber

sceneElements(ref: any) → any

A scene's entities as elements, the form `elementsOf` answers for saved records: each entity of its `scene.json` is a record, its parent the entity its `parent` names.

argtypedescription
refanyThe scene asset.

examples

local elements = engine.sceneElements(sceneRef)

withColumns(value: any, columns: any) → any

A value with the columns the device holds put back under their names: what `importAsset` left out, once `transfer.upload` has placed it.

argtypedescription
valueanyThe value `importAsset` answered.
columnsanyThe device columns by name; empty for a value that holds none.

examples

local texture = engine.withColumns(value, placed)

guidOf(ref: any, fallback: any) → any

The stable reference a record names an asset by.

argtypedescription
refany
fallbackany

writeChannel(bytes: buffer, offset: number, format: string, value: number) → void

argtypedescription
bytesbuffer
offsetnumber
formatstring
valuenumber

textureValue(record: any, asFormat: string?) → any

The Texture value the texture asset type writes, made from a Texture record: its texels as the bytes its format states, or the bytes it already holds.

argtypedescription
recordany
asFormatstring?

writeTexture(record: any, name: string, place: { [string]: any }) → any

argtypedescription
recordany
namestring
place{ [string]: any }

writeMesh(geometry: any, name: string, place: { [string]: any }) → any

argtypedescription
geometryany
namestring
place{ [string]: any }

writeMaterial(record: any, name: string, place: { [string]: any }, kinds: any?) → any

A Material record written as a `.material`, by the record kind it names; a record naming none is of the kind the material asset type names. `kinds` is the `records` map the record travelled with.

argtypedescription
recordany
namestring
place{ [string]: any }
kindsany?

variantMaterial(material: any, name: string, place: { [string]: any }, variant: { [string]: any }) → void

The material reference a population variant draws with: a Material record is written beside the population, an asset reference travels by its guid, and a name the renderer holds travels as a key.

argtypedescription
materialany
namestring
place{ [string]: any }
variant{ [string]: any }

isPopulation(geometry: any) → boolean

Whether a Geometry is a population: points, no primitives, each carrying the `Mesh` it stands.

argtypedescription
geometryany

readPopulation(geometry: any) → any

What a population stands: one variant per source and material its points draw, each with the points that stand it, and the placement of every point as flat runs. A source is the geometry a point carries as its `Mesh`, or the one its `Mesh` index names in the detail's `labels.Mesh`; its material is the one the point carries as its `Material`, else the one its piece record states, else the source's own.

argtypedescription
geometryanyA Geometry whose points carry a `Mesh`.

examples

local read = engine.readPopulation(points)

rankOf(record: any) → void

argtypedescription
recordany

writePopulation(geometry: any, name: string, place: { [string]: any }) → any

A population written on its own holds the meshes and materials its variants draw with inside its own folder, as `<name>_mesh<n>` and `<name>_mat<n>`.

argtypedescription
geometryany
namestring
place{ [string]: any }

referenceGuid(value: any) → string

The guid a value states for an asset it holds as a reference: an AssetRef, or the table a record writes for one.

argtypedescription
valueany

shapeKey(value: any, depth: number) → string

A string that names the same Material record for any two tables that state it alike.

argtypedescription
valueany
depthnumber

newContent(into: { [string]: any }) → Content

The assets the entities of one export use. Everything it writes goes under `into`, a place the asset being exported owns (its bundle folder, the scene's `prefabs` folder): `mesh<n>`, `material<n>`, `texture<n>`, `population<n>`, one per distinct value, numbered in the order first used.

argtypedescription
into{ [string]: any }

assetFor(content: Content, value: any, noun: string, where: string) → string

The guid of the asset `value` stands for where a `noun` asset is needed: a reference is used as it is, an asset-valued record is written as an asset once, and any other value is refused naming the accepted forms.

argtypedescription
contentContent
valueany
nounstring
wherestring

defaultMaterial( ) → string

The guid of the material a geometry draws with when it states none.

kindAsset(content: Content, value: any) → string

The guid of the asset a record of a kind saves as, written once inside the place content goes: `<kind><n>`, numbered per kind in the order first used.

argtypedescription
contentContent
valueany

assetsIn(content: Content, value: any, where: string, depth: number) → any

A value with every asset-valued record found in its fields written as an asset and replaced by its guid.

argtypedescription
contentContent
valueany
wherestring
depthnumber

nativeRow(content: Content, typeName: string, record: any, where: string) → void

The `ecs` row a native component record states: every handle-typed field holds the guid of an asset and every other field the value the component's plan converts it to.

argtypedescription
contentContent
typeNamestring
recordany
wherestring

newRecord(name: string, id: string, parentId: string?) → Record

argtypedescription
namestring
idstring
parentIdstring?

addDrawing(content: Content, rec: Record, mesh: any, material: any, where: string) → void

Mesh and Material as the native components an entity draws with: the asset guids, which loading turns back into handles.

argtypedescription
contentContent
recRecord
meshany
materialany
wherestring

onCpu(value: any) → any

argtypedescription
valueany

numbers(geometry: any, attribute: string) → void

argtypedescription
geometryany
attributestring

records(geometry: any, attribute: string) → void

argtypedescription
geometryany
attributestring

savedRow(content: Content, native: any, where: string) → void

A native row of a prefab record in the shape a saved record states it: each mesh, material and texture field holds the guid of an asset, a graph value (a Geometry, a Material record) written as one, a name or identity the guid of the asset it names, and a material field holding nothing the default material.

argtypedescription
contentContent
nativeany
wherestring

prefabRecords(content: Content, prefab: any, reported: { string }) → void

A Prefab's records with every asset-valued record in their fields written as an asset. A `Model` whose geometry is the placeholder `__procGeometry` becomes the native Mesh and Material, and each native row takes its assets' guids.

argtypedescription
contentContent
prefabany
reported{ string }

entitiesOf(value: any, name: string, into: { [string]: any }) → any

The entities a value stands as, in the shape a saved record takes, with every asset the entities use written inside `into`.

argtypedescription
valueanyA Geometry (with primitives: one entity drawing it; points: one entity per point), a list of Geometries (one entity each), an asset reference (one entity placing the asset) or a Prefab.
namestringThe base name of the entities that state none, and of the root.
into{ [string]: any }The place content is written to: `{ folder = <path> }`, the folder of the asset being exported. Meshes, materials, textures and populations are written there as `mesh<n>`, `material<n>`, `texture<n>` and `population<n>`, once per distinct value.

examples

local described = engine.entitiesOf(points, "rocks", { folder = bundle.path })

standsAsEntities(value: any) → boolean

Whether a value stands as entities: a Prefab, a Geometry, a list of Geometries or an asset reference.

argtypedescription
valueany

describeInto(ref: any, value: any, name: string, folder: string) → any

The entities of `value` with their assets written under `folder`. A value that cannot be described leaves nothing behind: the asset being written is removed with what had been written into it.

argtypedescription
refany
valueany
namestring
folderstring

writeBundle(value: any, name: string, place: { [string]: any }) → void

argtypedescription
valueany
namestring
place{ [string]: any }

qualifyComponent(kind: string) → string

argtypedescription
kindstring

writeScene(value: any, name: string, place: { [string]: any }) → void

argtypedescription
valueany
namestring
place{ [string]: any }

targetOf(value: any) → string

The asset a value saves as when the caller names none.

argtypedescription
valueany

writeAsset(value: any, name: string, folder: string, as: string?) → any

Persist a value as the asset its type states, placed under the world source.

argtypedescription
valueanyA Geometry (a mesh, or a population when its points carry a `Mesh`), a Texture record (texture), a Material record (material), or what stands as entities for a bundle or scene: a Geometry (with primitives one entity, points one entity each), a list of Geometries, an asset reference or a Prefab.
namestringThe asset's name. A bundle writes the meshes, materials, textures and populations its entities use inside its own folder, a scene inside its `prefabs` folder, as `mesh<n>`, `material<n>`, `texture<n>` and `population<n>`, one per distinct value.
folderstringA subfolder of the world source; empty uses the default generated folder.
asstring?The asset type to write: `mesh`, `texture`, `material`, `population`, `bundle` or `scene`; empty takes the type the value states.

examples

local ref = engine.writeAsset(prefab, "village", "levels", "scene")

countEntities(value: any, as: string?) → number

How many entities a value stands as when it is written as a bundle or scene: the records of a Prefab; one for a Geometry with primitives or an asset reference; a root and one per point for points; a root and one per Geometry for a list; 0 for one element holding one record saved as its kind's asset, and for any other value.

argtypedescription
valueanyA value read back from the device.
asstring?The asset type the value is written as; empty takes the type the value states.

examples

local count = engine.countEntities(prefab)

writeMaterial(record: any, name: string, folder: string) → any

Write a Material record as a material asset, with the textures its slots hold written beside it as `<name>_<slot>`.

argtypedescription
recordanyA Material record.
namestringThe material's name.
folderstringA subfolder of the world source.

examples

local ref = engine.writeMaterial(material, "preview", "tmp/preview")

textureValue(record: any, format: string?) → any

The Texture value a Texture record states, its texels held as the bytes its format stores.

argtypedescription
recordanyA Texture record: `{ width, height, format, texels }`.
formatstring?The format the bytes are held in; the record's own when left out.

examples

local texture = engine.textureValue(record, "rgba8")

entityIds(query: any) → void

argtypedescription
queryany

requireLive(ids: { string }, what: string) → void

The entities of `ids` that no longer exist, refused by name.

argtypedescription
ids{ string }
whatstring

poseColumns(ids: { string }, space: string, want: { [string]: string }, out: { [string]: any }) → void

argtypedescription
ids{ string }
spacestring
want{ [string]: string }
out{ [string]: any }

readEntities(query: any, fields: any, space: string) → any

Read live entities into columns, one element per entity.

argtypedescription
queryany`{ ids }`, `{ name }` (a Name or glob), `{ component }` or `{ colliders = true, sensors = false }`.
fieldsanyA list of field names, or `{ pose = true, space = "world" | "local" }`. Names: `position`, `rotation`, `scale`, `id`, `shapeType`, `params` (a collider's shape and size), or `Component.field` for a number or vec3 field of a component.
spacestring"world" or "local" for the pose fields of a list.

examples

local read = engine.readEntities({ component = "Light" }, { "position", "Light.intensity" }, "world")

readEntitiesLive(query: any, fields: any, space: string) → any

A value that changes when what `readEntities` answers does: the entities the query names and every column it reads, or the reason it cannot be read.

argtypedescription
queryanyThe query `readEntities` takes.
fieldsanyThe fields `readEntities` takes.
spacestring"world" or "local" for the pose fields of a list.

examples

local live = engine.readEntitiesLive({ component = "Light" }, { "position" }, "world")

importWater( ) → any

The water the scene holds: every provider's name and version.

examples

local water = engine.importWater()

Sub-parts

Everything contained inside this part. Assets are composite children (clickable cards). Files are leaf payloads. Expand any row to view its source.

Showing the 199 items nearest this part. It holds more than this page lists.

199+items
❒
package · born here
❒asset
▲ 1↑ born
❒
package · pulled in
❒asset
ZeroJS is a JavaScript interpreter for the Zero engine, written in Luau. It parses and executes ES2017-practical JavaScript entirely inside the Luau VM — no native code, no WebAssembly, no external dependency — and marshals values back to Luau transparently. ## Importing ```luau local zerojs = require("~zerojs.api") ``` `~zerojs` is this package's alias, registered from the `name` in its `package.yaml` wherever the package sits. The same spelling therefore works from the world that authors the package and from a world that installed it, at any depth. Every module is reachable the same way — `~zerojs.parser`, `~zerojs.stdlib.promise` — and the package's own modules reference each other with those ids. ## API surface ### Module-level | Symbol | Type | Description | |--------|------|-------------| | `zerojs.eval(src)` | `(string) -> any` | Parse and execute `src` in a fresh one-shot VM. Returns the marshaled JS completion value. Raises a Luau error on a JS exception. | | `zerojs.new(opts?)` | `(table?) -> VM` | Create a persistent VM. `opts.env` seeds additional JS globals from a Luau table. `opts.engine` picks the tier (`"auto"`, `"compiled"`, `"interp"`). `opts.console` is a table of writers by level (`log`, `info`, `debug`, `warn`, `error`): each receives the formatted text of one console call, untagged, and a level without a writer uses `log`'s. With no `opts.console`, the console writes `[zerojs]`-tagged lines to the engine log. | | `zerojs.null` | sentinel | The JS `null` value (distinct from Luau `nil`). | | `zerojs.undefined` | sentinel | The JS `undefined` value, which marshals to Luau `nil` when returned. | | `zerojs.version` | `string` | Version string of this package. | | `zerojs.lastError(vm)` | `(VM) -> table?` | Returns the structured payload `{ name, message, stack }` from the most recent JS exception on `vm`. `nil` if no exception has occurred on that VM. | ### VM instance | Method | Description | |--------|-------------| | `vm:run(src, opts?)` | Execute `src` in this VM's persistent realm. `opts.sourceName` names the source for error messages and stack frames. Returns the marshaled completion value. Raises directing to `runAsync` when the script leaves a timer armed or a coroutine suspended across a frame. | | `vm:runAsync(src, opts?)` | Execute `src`, driving its event loop across engine frames until it settles. Returns a `RunHandle` immediately. `opts.timeoutMs` rejects the run if it outlasts that many milliseconds. Only one `runAsync` may be in flight per VM at a time; a second call while the first is unsettled raises. | | `vm:get(name)` | Read a global from the VM's realm. | | `vm:set(name, value)` | Write a marshaled Luau value as a JS global in the VM's realm. | ### `RunHandle` (returned by `vm:runAsync`) | Field | Description | |-------|-------------| | `done` | `false` until the run reaches a terminal state, then `true`. | | `ok` | Once `done`, `true` for a resolved run and `false` for a rejection or timeout. | | `value` | The marshaled completion value on a resolved run. A run that timed out after its script had already completed with a value (an armed `setInterval`, say, kept the run open) keeps that value here; every other failure leaves it `nil`. | | `error` | The rendered message text on a rejected or timed-out run. | | `lastError` | The structured `{ name, message, stack }` payload for a failed run. | | `thread` | The engine `task.spawn` driver pumping the loop each frame — present only while the run is still pumping, and `nil` once the run settles on its arming frame (a synchronous or microtask-only completion needs no per-frame driver). | | `handle:await(maxFrames?)` | From a yieldable Luau context, poll `done` frame-by-frame until the handle settles, then return it. | A `runAsync` stays pending while the loop has work: an armed `setInterval` keeps it pending exactly as an un-`unref`'d handle keeps Node alive — clear the interval or bound the run with `timeoutMs`. ## Marshaling Luau values passed to `opts.env` or `vm:set` are converted to JS values. JS values returned from `run`/`eval` are converted back to Luau: numbers, strings, and booleans are transparent; arrays become 1-based Luau tables; objects become string-keyed Luau tables; JS functions become callable Luau closures; `undefined` becomes `nil`; `null` becomes `zerojs.null`. ## Step-budget sandbox Each VM runs with a default execution budget of 1,000,000 interpreter steps. A script that exceeds the budget raises a JS `RangeError: step budget exceeded`, which surfaces as a Luau error. The budget resets on each `run`/`eval` call. ## Language scope - Variable declarations: `var` (function-scoped hoisting), `let` and `const` with full TDZ enforcement - Functions: declarations, expressions, arrow functions, closures, rest parameters, default parameters - Classes: declarations and expressions, inheritance via `extends`, `super()` in constructors and methods, getter and setter accessors, instance fields, static fields and methods, computed method keys, named class expressions, TDZ before declaration - Destructuring: object and array patterns in declarations, assignment, and function parameters; nested patterns; rename, default, rest; computed keys in object patterns; elision in array patterns - Spread: array literals, call arguments, `new` arguments, object literals - Template literals (untagged) - Optional chaining: `a?.b`, `a?.[k]`, `f?.(x)`. A `null` or `undefined` base ends the whole chain with `undefined` and skips every later link and argument; parentheses end the chain; the chain is not an assignment, update or `new` target - Nullish coalescing `??` and the logical assignments `??=`, `||=` and `&&=`, which evaluate the right side and write only when the current value calls for it. `??` does not mix with `||` or `&&` without parentheses - Full coercion and equality semantics: `==`/`!=` abstract equality, `===`/`!==` strict equality, `typeof`, `instanceof` - `try`/`catch`/`finally`, `throw` - All loop forms: `for`, `while`, `do-while`, `for-in`, `for-of`; `switch` with fallthrough - `async`/`await` — real event-loop semantics: an async function returns a promise, runs synchronously up to the first `await`, and resumes from a microtask when its awaited operand settles - Property enumerability: `for-in` yields only own enumerable keys; object rest excludes prototype methods ### Asynchrony and the event loop - `Promise` with the full ES surface: `then`/`catch`/`finally`, `resolve`/`reject`, and the combinators `all`, `allSettled`, `race`, and `any` (with `AggregateError` when every input to `any` rejects) - `queueMicrotask` for scheduling a microtask directly - Timers: `setTimeout`/`clearTimeout` and `setInterval`/`clearInterval`, with extra arguments forwarded to the callback - `vm:runAsync(src, opts?)` drives a script's timers, microtasks, and promise settlements across engine frames and returns a `RunHandle` (see the VM table above) - A long synchronous loop under `runAsync` yields at each step-budget boundary and resumes on a later frame instead of raising `RangeError`; the same script under `vm:run` still raises ### Standard library - `Object`: callable coercion plus `keys`, `values`, `entries`, `assign`, `freeze`, `isFrozen`, `create`, `getPrototypeOf`, `defineProperty`, `fromEntries`, `hasOwn`, and the `Object.prototype` methods (`hasOwnProperty`, `toString`, `isPrototypeOf`) - `Function.prototype`: `call`, `apply`, `bind` - Global conversions and predicates: `parseInt`, `parseFloat`, `isNaN`, `isFinite`, `String`, `Number`, `Boolean` - `Array` and `Array.prototype`: construction, `isArray`, `from`, `of`, and the iteration/mutation/query methods (`map`, `filter`, `reduce`, `forEach`, `find`, `some`, `every`, `slice`, `splice`, `concat`, `join`, `indexOf`, `includes`, `sort`, `reverse`, `push`, `pop`, `shift`, `unshift`, `flat`, `fill`, `keys`, `values`, `entries`) - `String.prototype`: `slice`, `substring`, `substr`, `split`, `indexOf`, `includes`, `startsWith`, `endsWith`, `repeat`, `padStart`, `padEnd`, `trim`, `trimStart`, `trimEnd`, `toUpperCase`, `toLowerCase`, `charAt`, `charCodeAt`, `codePointAt`, `at`, `concat`, `replace`, `replaceAll`, `match`, `matchAll`, `search` - `Number`: `isInteger`, `isSafeInteger`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`, `MAX_SAFE_INTEGER`, `MIN_SAFE_INTEGER`, `MAX_VALUE`, `MIN_VALUE`, `EPSILON`, `POSITIVE_INFINITY`, `NEGATIVE_INFINITY`, `NaN`, and `Number.prototype` (`toFixed`, `toString`, `toPrecision`) - `Math`: the constants and functions (`abs`, `floor`, `ceil`, `round`, `trunc`, `sign`, `min`, `max`, `pow`, `sqrt`, `cbrt`, `hypot`, `exp`, `log`, `log2`, `log10`, the trig family, `random`) - `Date`: construction as `new Date()` (now) and `new Date(ms)` (epoch milliseconds), `now` (the wall clock at the moment of the call, never ahead of it and never moving backwards; whole-second readings of the wall clock bound it until a reading crosses a second boundary), `getTime`, `getFullYear`, `getMonth`, `getDate`, `getHours`, `getMinutes`, `getSeconds`, `getMilliseconds`, `getDay`, `toISOString`, `toJSON` - `JSON`: `parse` and `stringify` (indent argument and array replacer whitelist) - `Map` and `Set`: construction from iterables, `get`/`set`/`has`/`delete`/`clear`, `add`, `size`, `forEach`, `keys`, `values`, `entries`, insertion-order iteration - `RegExp`: literals and the constructor, `test`, `exec`, `lastIndex`, `source`, `flags`, `global`, `ignoreCase`, `multiline`, `dotAll`, and the `String` regex methods above - Errors: `Error`, `TypeError`, `RangeError`, `ReferenceError`, `SyntaxError` constructors and inheritance; `Error.prototype.name`, `message` and `toString`, so `String(e)`, `${e}` and `"" + e` read `<name>: <message>` - `console`: `log`, `info`, `debug`, `warn`, `error`, `dir` and `assert`. Values print the way a JavaScript console prints them: strings bare at the top and quoted inside, `{ a: 1, b: [ 1, 2 ] }`, `Map(1) { 'a' => 1 }`, `[Function: f]`, errors as `Error: message`, nested values below depth 2 as `[Object]` and `[Array]`, arrays and collections cut after 100 entries, a self-containing value as `<ref *1> { self: [Circular *1] }`, and a rendering wider than 80 characters across lines. A leading `%s`, `%d`, `%i`, `%f`, `%j`, `%o`, `%O`, `%c` or `%%` formats the arguments after it - `performance.now()` (milliseconds on a monotonic clock since the VM was created) and `performance.timeOrigin` - `globalThis`, `NaN`, `Infinity` ### Out of scope by design - Generators and iterators (`function*`, `yield`) - `Proxy` and `Reflect` - Labeled statements and `with` - Tagged template literals The full divergence list — where ZeroJS behavior differs from a browser engine — lives in the guide's divergence section. ## Test suites Eleven suites ship with the package, in its `tests/` folder, run via `tools.tests.run`: ```luau tools.tests.run({ suite = "zerojs_lexer" }) -- tokenization tools.tests.run({ suite = "zerojs_parser" }) -- AST construction and error recovery tools.tests.run({ suite = "zerojs_semantics" }) -- runtime semantics end-to-end tools.tests.run({ suite = "zerojs_language" }) -- ?., ??, logical assignment, error text, console, Date.now, performance.now tools.tests.run({ suite = "zerojs_stdlib" }) -- the standard-library surface tools.tests.run({ suite = "zerojs_typed_arrays" }) -- typed arrays, ArrayBuffer, DataView tools.tests.run({ suite = "zerojs_regex" }) -- the regex engine and RegExp methods tools.tests.run({ suite = "zerojs_async" }) -- the event loop, promises, and timers tools.tests.run({ suite = "zerojs_modules" }) -- the module graph tools.tests.run({ suite = "zerojs_assettype" }) -- the zJs asset type tools.tests.run({ suite = "zerojs_smoke" }) -- unmodified real-world JS programs ```
▲ 1↓ import
·
assettype · born here
❒asset
# 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**.
▲ 0↑ born
·
assettype · born here
❒asset
# Package (asset type) A package is an asset — a `<Name>.package/` folder that bundles components, modules, scenes, presets, tools, and any other typed sub-assets under one identity, installed into a world as one unit. Packages are how authoring sets get distributed across worlds. A **library** is the addressable root scope content resolves under (`@builtin`, `@<name>`) — a whole world mounted into this one under a namespace, via `zeromind.installLib` / `world.installLibrary`. A package is an asset that lives inside such a root, and one library holds as many packages as its author put there. A package is installed by guid the way every asset is (`zeromind.installAsset`). ## When to use one - You're authoring a coherent feature suite (character controller stack, voxel engine, UI kit, animation library) and want to ship it as one install target. - You want a stable identity worlds can install and resolve sub-assets against (`@<lib>::pkg.sub_module`). - You want versioning + a per-package metadata layer that travels with the contents. If you're authoring inside a single world and don't need a separate install lifecycle, you don't need a package — drop your `.component` / `.module` / etc. directly in `/zero/source/`. Packages are for cross-world distribution. ## Where it lives - Source: `/zero/source/.../<Name>.package/` (or, for legacy packages, a folder containing `package.yaml` at its root). - Identity: `<Name>` (the `.package` suffix collapses in identity — mirrors `.module`). A file at `<Name>.package/<sub>/init.luau` resolves under the same identity it would at `<Name>/<sub>/init.luau`. - Folder shape (container-style — open child set): - `package.yaml`: metadata (name, version, description) and the packages it depends on (`dependencies`). **Required.** - `README.md` — instance documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** - Sub-asset folders: any combination of `.component/`, `.module/`, `.scene/`, `.preset/`, `.tool/`, `.toolbox/`, `.material/`, `.shader/`, etc. The validator permits unlisted children (`allow_unlisted: true`) by design — packages are open containers. ## How to create one ```luau asset.create("package", "<Name>") -- Creates: /zero/source/<Name>.package/ -- package.yaml (metadata scaffold) -- README.md (instance README template) -- `folder` places it in a subfolder of /source instead of the root: asset.create("package", "<Name>", { folder = "systems" }) ``` Then scaffold sub-assets inside it: ```luau local pkg = asset.resolve("<Name>.package") asset.create("component", "Spinner", { into = pkg }) asset.create("module", "util", { into = pkg }) ``` ## `package.yaml` ```yaml name: inkBlocks # optional; the folder stem when absent version: "1.0.3" description: "Ink and paper style blocks" dependencies: - { name: starterBlocks, version: "1.0.8" } - styleKit # a bare name states no version ``` `dependencies` lists the packages this package needs. Each entry's `name` is a reference the package records, the same kind of reference a `require` or an asset name in a data file makes: - **It resolves in the author's world.** Install the dependency here first (`zeromind.installAsset`); the entry then names the copy this world holds. A push refuses a package whose dependency resolves to nothing, naming it. - **An install brings it along.** Installing the package installs every dependency it lists, at the version this world holds when the package is pushed, under `/source/deps/<owner world>/`, deduplicated against what the installing world already holds. `zeromind.preview` lists each one before anything is written, and the install's `deps` lists what it brought. Uninstalling the package leaves a dependency that another installed package still uses. - **`version` is checked, not chosen.** A stated `version` has to equal the `version` the dependency's own `package.yaml` states in this world; `asset.validate` (and so the push) refuses the package naming both when they differ. To depend on another version, install that version here. An install lands one release of each dependency its closure names, so in a world the package is installed into, itself or as a dependency of the package installed, it runs the release the install placed, and `asset.validate` names a stated `version` that release does not state as a warning. ## How it operates 1. **Registration.** Writing `package.yaml` indexes the package with the package registry. 2. **Install.** A package is read before it is installed: `zm ls-tree @<guid>` in the shell lists what it contains, and `zm show @<guid>:<path>` and `zm grep <pattern> @<guid>` read it, so candidates are compared by what they do. The one that fits is installed by guid, the way every asset is: `zeromind_install` over the engine's MCP, or `tools.use("zeromind", "installAsset", <guid>)` inside the engine. The install writes the package's files (and the deps its `.refs` record, the packages its `package.yaml` lists under `dependencies` included) into this world's source, so its sub-assets resolve here. `tools.use("zeromind", "preview", <guid>)` reports what an install would write before it writes anything. 3. **Sub-asset resolution.** Because `.package` collapses in identity, sub-asset paths work whether the package folder is suffixed (`<Name>.package/<sub>`) or not (`<Name>/<sub>`). 4. **Updates.** `tools.use("zeromind", "updates")` lists installed content with upstream changes available; re-running the install pulls them. 5. **Metadata.** `package.yaml::name` overrides the folder stem if present (rare); `version` + `description` are surfaced in the package index. 6. **Hot reload.** Edits to sub-assets hot-reload as normal; edits to `package.yaml` reload package metadata. ## Discovery - `asset.list("package")` — every registered package. - `asset.inspect("<name>")` — sub-asset catalog, source, this type README. - `ls /zero/source/<Name>.package` lists the files the folder holds. - `library.list()` — the library assets registered in this world, including the ones packages under an installed library contribute. ## Authoring conventions - Name packages by their feature (`voxels`, `cameraRigs`, `dialogSystem`), not by their owner — the host library is the `@<lib>::` scope prefix. - Cluster cohesive sub-assets together. A "character controller" package should ship the controller component, its preset configs, its supporting modules, and a demo scene — not just the component. - Document the package's surface in `README.md` — what install installs, what each sub-asset does, how they relate. Agents reading `cat /zero/source/<Name>.package/README.md` get the full picture in one shot. - Version conservatively — breaking a package means breaking every world that installed it. Use semantic version bumps. ## Common pitfalls - **Missing `package.yaml`.** Without it the folder isn't recognized as a package even if it has a `.package/` suffix. - **A dependency named only by a string the code builds.** A package whose files reach another package only through a name assembled at runtime records no reference to it, so an install arrives without it. List that package under `dependencies` in `package.yaml`. - **Identity collapse.** Sub-asset paths skip the `.package` suffix. Don't include `.package` in `require` strings. ## Referencing inside a package: the `~` rule `~` means **this package**, resolved structurally from the referring file's own location. It is the only package-specific syntax. It is rename-safe (no package name is ever written) and library-agnostic (it never names the host library, so it survives `@builtin` being renamed or the package being mounted elsewhere). `~.tail` maps to `<pkg>.package/tail` from anywhere inside the package. | Referencing from | Use | Example | |---|---|---| | An asset/module **inside this package** | `~.tail` | `require("~.modules.myThing")`, `shader: "~.shaders.myThingBlend"` | | A **different package** under the same root | root-relative identity | `require("@root::systems.otherPkg.modules.x")` | | A **different library's** public API (a deliberate external dependency) | `@otherlib::…` | `require("@physics::modules.rigidbody")` | **Never write `@builtin::` (or any host-library name) to reference your own package** — that couples the package to the library it currently lives in and breaks if the library is renamed or the files move. Use `~.`. It works from Luau `require()` and from asset-reference strings in data files (a material's `mat.yaml` `shader:` field, a component's default asset ref); the engine resolves it against the referring file's own package. `asset.resolve` takes a `~.` name the same way, against the package of the file that calls it: `asset.resolve("~.materials.myThingStandard", "material")`. `~.` is the package-relative self-reference; `@root::` is the root-relative one (the library root, or the world source tree for non-library content). The `core/requiring-modules` guide covers the root model in full. A package that ships substantial functionality should include a `.guide` asset (a `<name>.guide/guide.md` folder anywhere under the package); the `guides` tool discovers it live, so collaborators find the system the way they find built-in guides. A package's test suite reaches the shared `Test` framework through its enclosing asset: `local Test = asset.containing(__FILE__).modules.shared` (`asset.containing` returns the deepest enclosing typed asset, the `.testSuite`, not the outer `.package`). ## Related types - Any of `.component`, `.module`, `.scene`, `.preset`, `.tool`, `.toolbox`, `.material`, `.shader`, `.style`, `.service`, `.importer` — packages bundle these. ## In the Inspector Package: the name, version and description package.yaml declares, how many things the package holds and what they are, and **Open** for package.yaml. A package.yaml that does not decode is listed under Problems with the decoder's error.
▲ 0↑ born
·
assettype · born here
❒asset
# agentSkill A skill packages what an agent needs to do one job well: the instructions, the assets and toolboxes the job runs through, and — for jobs with distinct branches — subskills that go deeper. Skills advertise themselves. Every registered skill's name and one-line description rides the agent's tool responses, so an agent discovers what this world knows how to do without being told to look. Invoking one returns the instructions plus the exact identities and tool names the job needs. ## Shape ``` <name>.agentSkill/ skill.yaml # the manifest: description, when, checks, dependencies, order instructions.md # the prose an agent receives on invoke README.md # what this skill is, for a human reading the tree .metadata # tags <sub>.agentSkill/ # optional subskills, reachable as <name>/<sub> ``` ## The manifest ```yaml $schema: zero/agent-skill/v1 description: Making a character a person can actually play. when: > Reach for this when the player should look like something else, or when you are about to build a camera and a body and wire them together by hand. checks: - check: Holding a movement key in play moves the body across the ground. observe: Read its position before and after holding the key; the numbers differ. - check: The body animates while it moves. observe: A time-sampled collage from a camera outside the player, while the key is held. dependencies: - "@builtin::tools.scene" - "@builtin::tools.scene.player" - "@builtin::components.PlayerPrototype" - "@builtin::docs.core.multiplayer" order: [spawn-points, camera-rig] ``` `description` is the line the roster carries, and the whole basis on which a skill is chosen. Name the job the skill makes a reader competent at, in the outcome they are after — "getting a scene's player and view right", "making content the engine will load". A reader scanning the roster is matching it against the job in front of them, so the closer it reads to their own sentence about that job, the sooner they open it. `when` is the longer trigger — the situations that should send a reader here, in the words they would use for their own task. `kind` says what the skill is to its reader, and `job` is assumed when it is left out. A `job` is work taken on and finished: opening it holds it, so it rides the reader's tool responses until it is released, and its `checks` say when it is done. A `reference` is knowledge for the whole session, such as how the engine fits together: opening it does not hold it, it is never released, and it states no `checks`, `stages` or `verdicts`, because it describes no job whose end they would mark. A check on a reference turns it into a step that one pass completes, after which its reader stops applying it. `checks` is what the reader of a job is answerable for at the end, and it leads the rendered skill, ahead of the procedure. Each entry pairs a **condition that must hold** with **where it is seen**, and both halves are required — a condition alone is satisfied by any glance, and the wrong vantage is how a job passes while every one of its faults sits outside the frame. Write them as observations someone else could repeat and disagree with: a number that changed, a thing visible in a named shot, a count that came back as one. A job publishes only once it carries at least one. `stages` models a skill whose passes run in order, when the order is load-bearing. Each stage is `{ name, detail?, checks? }`, and a check that sits in a stage is answered after that pass has run — which is the difference between a criterion that means something and one that misleads. A skill with no meaningful order leaves `stages` out and lists its checks flat; a skill that has one may do both, and the flat checks then read as the final gate. `verdicts` names the fixed set of outcomes a reader reports — at the end of each stage when the skill has stages, and once at the end when it does not. Each is `{ verdict, means }`: the word, and what reporting it asserts. Both halves are required for the reason both halves of a check are. A verdict is a check one level up, deciding a whole pass rather than one condition, and a bare `refine` is a label each reader fills in privately — so two runs report the same word about different states and nothing downstream can tell them apart. Saying what it means settles the boundary in the skill instead of in whoever happens to be reading it. A check marked `perRun: true` is one whose content is written for the job at hand: the manifest can say *keep a list of every feature this object must have and answer against it*, but not what is on that list, because that is per run. It renders with that instruction attached. ```yaml verdicts: - verdict: continue means: Every check in the stage held, and the next stage can build on it. - verdict: refine means: A check failed on something this stage can still fix. Run it again. - verdict: stop means: A check failed on something an earlier stage decided. Go back to it. stages: - name: blockout detail: Mass and proportion only. checks: - check: Every part on the identity list has a stand-in at roughly the right size. observe: A capture beside the reference, at the same angle. perRun: true - name: material checks: - check: Metal reads as metal and cloth as cloth. observe: The metallic and roughness passes, after the lighting stage has run. ``` `dependencies` is one flat list of asset **identities**: a toolbox, a single tool, a guide, a component, a module, another skill. Each entry is resolved when the skill is opened and reported with what it turned out to be, so a skill never declares "this one is a toolbox" — the asset says so, and the reader groups by that. Identities are what make a skill portable. They pin like any other reference, so installing a skill into another world brings the toolboxes and guides it runs through along with it. A bare name (`scene`) or a guide path (`core/multiplayer`) resolves to nothing and is refused before publish. A toolbox entry lists the tools it carries, and a tool entry carries its own signature, so the instructions never restate a call contract that can drift. An identity this world lacks is reported as missing rather than dropped. Write instructions that name the toolboxes and tools a job runs through, and leave the call form to the reader — an agent may be holding the MCP tool surface, the shell, or Luau, and the signatures are listed for it either way. ## Subskills A `<sub>.agentSkill/` folder nested inside a skill is a subskill. It has the same shape as its parent and is invoked as `parent/sub`. Subskills are reachable only through their parent: they are absent from the roster and from `skills.list`, and appear in the parent's invoke result. A skill can therefore carry a dozen narrow procedures while costing the roster one line. `order` in the manifest names the subskills that lead. Any subskill it omits still appears, sorted by name, after the ordered ones — so adding a subskill folder is the only step needed to publish it. ## Publishing one Make a skill and it is live: it joins the roster agents read and it opens by name from the moment it exists. Edit its description and that is the line agents see next. A skill lives anywhere under `/zero/source/`. `asset.create` hands you a valid one to fill in: ```luau asset.create("agentSkill", "waveSpawning", { folder = "skills" }) ``` A skill's scope — `builtin`, `library`, or `world` — comes from where it lives rather than from anything it declares, so a world's own skill always reads as the world's. ## Opening one ``` agent_skill {} -- the roster agent_skill { name = "scenes" } -- one skill's instructions + deps agent_skill { name = "scenes/player-setup" } -- a subskill ``` The same three through the toolbox — `skills.list`, `skills.invoke` — and from Luau via `tools.use("skills", "invoke", "scenes")`. `asset.inspect` on a skill ref returns the structured record all of them render. Skills authored in a world are the world's own, and are labelled as world content wherever they surface beside built-in ones. ## In the Inspector Skill: what the skill is for and when it applies, how many checks and verdicts it declares, its stages, a link to each asset it depends on (and a problem for each that does not resolve), its subskills, and **Open** for instructions.md.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_focusBars Four rows of bar pairs, 8 pairs across the top row and doubling on each row below: the focus chart a depth-of-field reading is taken off. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
·
assettype · born here
❒asset
# inputBinding assetType One control in a scheme — `jump`, `move`, `boost` — expressed as an asset. A `<name>.inputBinding/` folder whose `init.luau` returns the binding record, living inside a `.inputMap/` parent the same way a `.tool` lives inside a `.toolbox`. Containment is what records the reference, so a scene that carries its map carries every control the map declares. A scene pulled into another world cannot arrive somewhere `boost` binds to nothing. ```luau -- racer.inputMap/boost.inputBinding/init.luau local B = require("@builtin::modules.zinput.bindings") return { label = "Boost", kind = "button", kbm = { B.key("ShiftLeft") }, gamepad = { B.padButton("left_shoulder") }, touch = { B.touchButton({ zone = "right-lower" }) }, } ``` ## Every device class, always `kbm`, `gamepad` and `touch` are all required. A control bound on one device and not another is how a world ships playable on a desktop and dead on a phone, so a record missing a class is refused at activation, naming the binding and the class it lacks. Setting a class to `false` suppresses it deliberately — a text-entry control with no touch counterpart says so, and says it in the record where a reader sees it. The cost of that rule is paid at authoring time rather than by the author: the `inputAuthor` toolbox stamps canonical defaults for a control whose name the catalog knows, so a complete three-class binding is one call. ## Kinds | `kind` | Shape per class | What it is | |---|---|---| | `button` | an **array** of bindings — any one satisfies it | A press: jump, fire, interact | | `axis1` | **one** binding | A scalar: throttle, zoom, lean | | `axis2` | **one** binding | A vector: movement, look, aim | A button takes an array because a control usually has more than one way to be pressed on the same device (`ShiftLeft` and `ShiftRight`). An axis takes one because an axis evaluates exactly one binding per class. ```luau -- move.inputBinding/init.luau return { label = "Move", kind = "axis2", kbm = B.wasd(), gamepad = B.padStick("left"), touch = B.touchStick({ zone = "left" }), } ``` ## Shaping an axis An `axis1` / `axis2` control conditions its reading before a consumer sees it. Four optional fields, applied every tick in this order: | Field | What it does | |---|---| | `deadzone` | A magnitude below it reads 0. On an `axis1` that is the value; on an `axis2` it is **radial** — the magnitude of the pair — so a diagonal held past the threshold keeps both components | | `curve` | `"linear"` (the default), `"quadratic"` (squares, keeping the sign), `"cubic"`, or a function taking the reading and returning the shaped one | | `invert` | `true` negates the reading — both components, for an `axis2` | | `smoothing` | The time constant, in seconds, the reading approaches its target over. `0` (the default) arrives at once | ```luau -- look.inputBinding/init.luau return { label = "Look", kind = "axis2", deadzone = 0.12, curve = "quadratic", smoothing = 0.05, kbm = B.mouseDelta(), gamepad = B.padStick("right", { as = "delta", unitsPerSecond = 1200 }), touch = B.touchDrag({ zone = "right" }), } ``` The shaping lands on the reading the classes produced, after `as` / `unitsPerSecond` / `scale` have brought each of them into the control's own unit — so one `deadzone` is written once, in that unit, and covers the stick, the mouse and the finger together. `smoothing` carries the same value toward whatever the devices report next, so a control whose context leaves, whose group stands down, or whose gate closes drains to neutral rather than cutting to it, and reports its drop frame when it arrives. Shaping is refused on a `button`: it is held or it is not, so there is no magnitude to cut, bend or approach. Say when a button may read at all with `gate`. ## Events A binding exposes the events a controller subscribes to. Handlers take positional arguments, so a movement handler reads them directly rather than unpacking a table every frame. | Event | Fires | |---|---| | `input` | Every frame the binding is active, carrying `(value, dt, active)` — and once more on the frame it goes inactive, with `active = false` and the neutral value | | `pressed` | The press edge of a button | | `released` | The release edge of a button | | `changed` | When the value changes | `input` firing on the drop frame is what lets one handler both start and stop motion. Inside a component, whose hooks reach its fields through `public`: ```luau map.move:onInput(function(v, dt, active) public.moving = active if not active then return end local p = public.entity.position local step = public.speed * dt public.entity.position = { p.x + v.x * step, p.y, p.z - v.y * step } end) ``` ## Ref methods - `:record()` — the validated binding record. Raises when a class is missing or the record is malformed, naming what is wrong. - `:problems()` — every problem with the record, without raising. What an authoring tool reports so a whole map's faults surface at once. - `:inspect()` — `{ label, kind, classes }` for `asset.inspect`. - `.events` — the subscribe-only view over the four events above. ## Creating one `asset.create("inputBinding", name, opts)` writes a record carrying every device class, so a binding is complete the moment it exists: ```luau asset.create("inputBinding", "boost", { label = "Boost", kind = "button", kbm = '{ B.key("ShiftLeft") }', gamepad = '{ B.padButton("left_shoulder") }', touch = '{ B.touchButton({ zone = "right-lower" }) }', }) ``` ## In the Inspector Binding: the binding's label, its kind and the device classes it binds, every problem its definition has, and **Open** for its source.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_skyRamp A sky-blue ramp of light from 0.02 to 0.6 across: a clear sky's gradient. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
package · born here
❒asset
# 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 ```
▲ 0↑ born
·
assettype · born here
❒asset
# lightmapData A baked-lighting container: ONE asset per scene holding every baked lighting payload the GI bake flow produces — per-entity lightmaps and per-volume probe-field bricks. The container is what makes a bake persistent: a fresh boot (or a runtime-profile session) restores baked lighting from it with zero re-baking. ## How it's referenced Entities point at the container through typed fields and resolve their own entry out of its manifest: - `Model.lightmapData` / `SkinnedModel.lightmapData` — set by the bake flow on every per-texel receiver; the component's awake hands the ref to the lightmap manager, which rebuilds the runtime lightmap texture + material from the entry keyed by the entity's id. - `VolumeProbe.lightmapData` (+ its `fieldId`) — set when a volume's field is baked; the component's awake restores the SH buffer and republishes the volume into the renderer's irradiance set. Because every receiver shares one container, a scene with hundreds of baked entities stays ONE asset in the world listing. ## Layout ``` <name>.lightmapData/ manifest.yaml version + `lightmaps` (by entity id) + `probeFields` (by field id) lm_<key>.bin lightmap payload: raw LE f32 RGBA, resolution² × 4 floats pf_<key>.bin probe-field payload: raw LE f32 SH L2, 36 floats per probe, X-fastest ``` ## Lifecycle `baking.all` creates (or reuses) the scene's container and writes every baked entry; `baking.clear` removes entries (a full-scene clear empties the container). Entries are replaced atomically per key on re-bake. Instance methods (`:manifest()`, `:lightmap(key)`, `:probeField(key)`, `:setLightmap(...)`, …) are the read/write surface — see the behavior docs via `asset.inspect`. ## In the Inspector Selecting a lightmap container opens its **Bake** section, read from `manifest.yaml`: the manifest's version, a table of the baked lightmaps (the entity each belongs to, its resolution and intensity) and a table of the probe fields (each field's resolution per axis and probe count). A container nothing has been baked into says it has no lightmaps and no probe fields.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# procGraph (asset type) A `.procGraph` asset is a **procedural graph**: a description of how to make something, written as code, that can be evaluated over and over with different numbers. Its `init.luau` returns `proc.define(...)` — that source IS the asset, the way a `.procNode`'s `init.luau` is. ## Shape A `<name>.procGraph/` folder containing: - `init.luau`: the graph's definition. Returns `proc.define(function(g) … end)`, the graph named by its asset folder. - `graph.json` — the compiled form (`proc.graph.v1`), written by this type from `init.luau`. Generated, never hand-edited. - `README.md`, `.metadata` — the universal asset files. The type writes the graph's description and kind into `.metadata` on every compile. - `layout.json` (optional) — where the Inspector's node editor draws each node. - `preview.png` (optional) — the graph's rendered still, which search shows. `asset.create("procGraph", name)` scaffolds `init.luau` (a box with a `size` input, shown through `g.io.output` and returned as `mesh`), `README.md` and `.metadata`, and the first compile writes `graph.json`. ## Authoring Edit `init.luau`. The type recompiles on the write, rewrites `graph.json`, and every live `Generator` bound to the asset re-cooks from it — there is no build step between saving and seeing the result. A graph is built from more than its `init.luau`: a module the source requires while it builds (`onDependencyChange`), a file it reads with `vfs.read`, and a file a module it calls reads with `proc.read` are part of it, and so is every node it calls. When one of them changes, every `Generator` standing on the graph builds it again and cooks it on its next frame; nothing is written to the world for it. A recompile is cheap however large the graph: node results are keyed by content, so recompiling an unchanged node reuses its cooked output, and an edit invalidates only that node and the ones downstream of it. Changing the last step of a landscape does not re-run the erosion above it. Two words worth keeping apart, because both happen here: - **compile** — `init.luau` → `graph.json`. Produces the graph. - **cook** — each node performing its operation to produce a value. Runs the graph. Driven by a `Generator`, reported by `procgen.cooks`. ## Using one Through the ref rather than a path string: `ref:eval("mesh")` evaluates an output (`"output:mesh"` and `"node:<id>"` are targets too, and `ref:eval("mesh", { inputs = { size = 3 } })` overrides inputs for the call), `ref:inputs()` lists the knobs a Generator can override by name (`{ [name] = { type, default, min?, max?, ... } }`), `ref:outputs()` the sorted output names, `ref:validate()` type-checks it (an empty list when it is well-typed), and `ref:asOp()` wraps it so another graph can composite it as a node. `ref:graph()` builds the graph from `init.luau`; `ref:compile()` compiles it now and answers `{ id?, nodes, out }`; `ref:instantiate(target?, { params?, output?, ... })` puts it in the scene on a `Generator`; `ref:promote(opts?)` makes it a `.procNode`; `ref:preview(opts?)` renders its still and `ref:stillTime()` names the moment that still shows. Generated outputs (meshes, materials, textures, bundles) are persisted through their own asset types. ## Related - `@builtin::systems.procgen.proc` — the authoring + evaluation model. - `procgen.toolbox` — `preview`, `spawn`, `bake`, `validate`, `searchNodes`, `describeNode` and the wider tool family. ## In the Inspector The Inspector shows the graph as nodes and wires, and edits it there. Every graph input, op, graph used as a node and output is a node; each input port that nothing is wired into carries the value that drives it, and a click on a value edits it where it stands (typing, dragging a number, flipping a switch, choosing from a list). Drag a node to move it, drag from a port to another port to connect, drag a connected input away to take its wire off, Delete removes the selection. A node is added from the op search under the graph, or from the procGraph assets, which stand as nodes that open their own asset on a double click. The graph's inputs and outputs are nodes too: their name, type, default and range, and an output's domain, are values on them, and the Inputs and outputs section declares new ones. Describes is the sentence search finds the graph by. The Graph section also carries **Compile**, which compiles the graph now, and a link that opens `init.luau`. Every edit is written into `init.luau` with `proc.saveSource` and compiled by the type, so a live Generator re-cooks on it; the node positions are kept beside the graph in `layout.json`. The Result section scrubs the timeline of a graph that has one and shows what the selected node makes (`procgen.preview` with the target `node:<id>`), and the Preview section above it shows what the graph makes, live. The Node section describes the selected node.
▲ 0↑ born
·
assettype · born here
❒asset
# Post effect (asset type) A post effect is a post-process shader on the screen, as an asset: one post-process shader with its values, its order and its layer in the post chain, described in `postEffect.yaml`. It implements `applicable`: applying it puts that shader in the chain for the applier. ## Making one A post effect names a post-process shader and states the values it runs with: a shader of the world's own, or any post-process shader a world can reach. A holder (a setup, a sky, a `PostProcess` entry) names the post effect and may state values of its own for it, which are that holder's alone: ```yaml # <setup>.sceneSetup / sceneSetup.yaml members: - id: grade source: "./grade.postEffect" values: { saturation: 0.82 } ``` `asset.list({ type = "postEffect" })` lists the post effects a world holds, and `ref:inputs()` names the values each takes. ## Where it lives - Source: `<name>.postEffect/` - Identity: `<name>` (the `.postEffect` suffix strips from the identity) - Folder shape: - `postEffect.yaml`: the effect. **Required.** - `README.md`: what it does to the picture. **Required.** - `.metadata`: `description` and `tags`. **Required.** ```yaml # <name>.postEffect / postEffect.yaml shader: "<post-process shader>" # any post-process shader layer: scene # scene | all | "" (the shader's own space) order: 120 values: { intensity: 0.3 } ``` ## Writing its shader The shader a post effect names is a `post-process` shader: one `fn fragment(in: PostInput) -> vec4<f32>` over the rendered frame, its properties in `properties.yaml`. Besides `in.uv` and `in.frag_coord`, it reads: - `zero_sample_scene(uv)`: the rendered scene colour at `uv`; - `zero_scene_depth(uv)`: the scene depth at `uv` (reversed: 1 is the near plane, 0 the far plane and empty sky), and `zero_linear_depth(d, near, far)` for it in metres; `zero_scene_motion(uv)`, the per-pixel motion; - `engine.time`: `x` the elapsed seconds, `y` the frame's `dt`, `z` the frame index: an effect that moves (a scan line, a pulse, drifting grain) animates by it; - `engine.resolution`: `x` and `y` the target's width and height, `z` and `w` their reciprocals; - `engine.view_proj`, `engine.prev_view_proj`, `engine.inv_view_proj`: the camera the frame was drawn from, this frame and the last. The `shader` type's README, "Post-process & screen shaders", has the whole surface: every helper, multi-pass shaders and the space an effect declares. ## Parameters Its parameters are its shader's properties, each with the Field descriptor of its kind, defaulting to what `values` states (else the property's own default): | Property kind | Field | |---|---| | `float` with a `min` or `max`, `range` | `Field.range` | | `float` | `Field.number` | | `float2` / `float3` | `Field.vec2` / `Field.vec3` | | `float4` | a four-number `Field.struct` (`x`, `y`, `z`, `w`) | | `color` | `Field.color` | | `bool` | `Field.bool` | | `texture` | `Field.resource("texture")` | and the chain's two inputs every post effect has: `order` (where it runs in the post chain, lower first) and `layer` (`scene`, `all`, or empty for the shader's own space). A shader property of a kind a post effect does not take (`texture_array`, `buffer`), or one named `order` or `layer`, is refused by name (`postEffect.definition` from `asset.validate`, and an error from `ref:inputs()` and `apply`). ## Applying it Each application puts the shader in the post chain under the name `"<asset guid>/<owner>"` (`ref:effectName(owner)` answers it), at its effective `order` and `layer`, with the effective values written to its properties: the asset's saved values, its live values (`appliedSystem.setLive`), then what the owner states. Applying it again for the same owner changes the values of that running application: `ref:as("applicable"):apply(owner, { intensity = 0.5 })` writes the new value to the standing entry, and a change of `order` or `layer` registers it again. Turning the application off disables the entry; dropping it removes it. Post effects combine in chain order, so every application of every post effect draws at once. The entry is registered under the component origin, so a scene freeze never turns an applied post effect into scene content: what puts it in force (a setup, a `PostProcess` entry, code) is what the scene keeps. ## In a `PostProcess` region An `effects` entry of `PostProcess` names either a `shader` (registered as a plain chain entry) or a post effect in `effect`, exactly one. An `effect` entry is an application of the post effect, owned by `"<entity id>/effects/<index>"`, with the entry's `values` and `textures` as its stated values, its `layer` stated when not empty, and the region's `priority` added to the effect's `order`. A post effect applied by a setup and the same one named in a `PostProcess` entry draw the same, and a live change reaches both.
▲ 0↑ born
·
assettype · born here
❒asset
# Scene light (asset type) A scene light is one light that reaches the whole scene alike, as an asset. It is one position-independent `Light` (`directional`, `ambient` or `distant`, the kinds `lighting.isPositionIndependent` answers for) described in `sceneLight.yaml`, and it implements `applicable`: applying it puts that light in force for the applier. ## Where it lives - Source: `<name>.sceneLight/` - Identity: `<name>` (the `.sceneLight` suffix strips from the identity) - Folder shape: - `sceneLight.yaml`: the light. **Required.** - `README.md`: what light it puts on a scene. **Required.** - `.metadata`: `description` and `tags`. **Required.** ```yaml # moonFill.sceneLight / sceneLight.yaml kind: distant direction: [0.3, -0.5, 0.4] color: [0.6, 0.7, 1.0] intensity: 0.3 ``` ## Parameters Its parameters are the `Light` component's own fields for the light, with their descriptors (`intensity`, `colorR`/`colorG`/`colorB`, `directionX`/`Y`/`Z`, `castsShadows`, `lightChannels`, `mobility`), defaulting to what `sceneLight.yaml` states, and three of its own: - `followSky`: whether the sky orients this light (a `directional` or `distant` one). A sky that drives the sun (a procedural backdrop) then writes the light's direction from its hour, and its colour and intensity as the stated ones multiplied by the curve of the sun's elevation: the stated `intensity` is the noon peak, reached from 30° up; toward the horizon the light dims and warms (about 0.3 of the peak at 7°), and below it the intensity is 0. A sun that should follow the sky states `followSky: true` and no direction. - `skyOffset`: where a following light stands from the sun, `[yaw, pitch]` in degrees. Yaw turns it about the vertical, so `[180, 0]` is a fill from the side opposite the sun at the sun's elevation; pitch raises it above the sun. The curve is the sun's, so a fill dims with the sun and is out at night. - `followSkyIntensity` (default `true`): whether a following light takes its intensity from the sky as well as its direction and colour. `true` puts the sun's curve on the stated intensity, as above. `false` keeps the stated intensity while the light stands above the horizon (its own elevation, after `skyOffset`) and 0 below it; the direction and the colour still come from the sky. A sun follows with it `true`; a fill or a rim that should hold its strength through dusk states it `false`. After dark a following light stands at the moon the sky draws, opposite the sun: with `true` it is out, with `false` it is moonlight at the intensity it states. A cool fill for a dusk scene: it stands opposite the sun, a little higher, takes the sky's direction and its warm-to-cool colour, and lands at the 0.9 it states at 17:42, where with `followSkyIntensity` true it would land near 0.18. ```yaml # harbourFill.sceneLight / sceneLight.yaml kind: distant color: [0.5, 0.6, 1.0] intensity: 0.9 castsShadows: false followSky: true followSkyIntensity: false skyOffset: [180, 12] ``` What a following light lands at is not what it states. A placed setup's `SceneSetup:members()` reports, for such a member, `landed` (its intensity, colour and direction now) beside `stated`, and `SceneSetup:get(path)` carries `landed` beside `value` for each of those parameters; `SceneSetup:set(path, value)` returns that read, so setting `fill/intensity` answers what it lands at straight away, and the setup's card shows it on the row (`0.9 → lands at 0.18 at 17:42`). `ref:landed(owner)` is the same answer for one application. ## Applying it Each application spawns a temporary entity of its own (`ref:entityOf(owner)`) and puts a `Light` of the asset's kind on it; it publishes itself as the sun or the ambient term the way every `Light` does, and the last to publish holds it. Dropping the application removes the `Light` and the entity. The `ApplyState` reports `held` while another light holds its kind (`heldBy` names that application's owner, or the holding entity), and a notice when an ambient term is as bright as half the sun or more, which flattens the scene's shading. A write the lighting API makes to the light (`lighting.setSun`, `lighting.setAmbient`, `sky.setSunDirection`) lands on the application, through its owner's writer when it handed one. A kind that lights from where its entity stands (`point`, `spot`) is refused by name (`sceneLight.kind`).
▲ 0↑ born
·
assettype · born here
❒asset
# 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.
▲ 0↑ born
·
assettype · born here
❒asset
# Bundle (asset type) A bundle is a composable, spawnable entity assembly— a saved entity hierarchy plus its components, sub-assets (meshes, textures, animations, materials, sub-bundles), and any nested data, packaged into a single addressable identity. Bundles are the engine's "prefab" primitive. There are **two ways** to bring a bundle into a scene — and the difference matters enormously for scene saving and live editing. See "How to spawn" below before you write anything. If you want one snapshot of a whole world / level, use a `.scene`. ## Where it lives - Source: `/zero/source/.../<Name>.bundle/` - Identity: `<Name>` (the `.bundle` suffix strips for use in identities, but the on-disk folder keeps the suffix). - Folder shape (container type — open child set): - `entity_template` — JSON of the entity hierarchy + components. **Required.** - `.metadata`: optional. - Anything else: meshes / textures / materials / animations / sub-bundles. Validator allows arbitrary additional files (`allow_unlisted: true`). ## How to create one Two paths, depending on whether you have an in-scene hierarchy or are authoring from scratch: ```luau -- From an existing in-scene entity: composes the given entity tree into a bundle. local bundle = asset.create("bundle", "<Name>", { entity = entityRef }) -- Or scaffold an empty bundle, then update it from an entity: local bundleRef = asset.create("bundle", "<Name>") bundleRef:update(entityId) ``` ## How to spawn ### 1. `Asset` component — live-linked (the canonical way) **This is the primary way to put a bundle into a scene that survives saving as an asset reference.** Spawn an empty entity, attach the `Asset` component, point it at the bundle: ```luau local car = entity.spawn("car_1") car.component.add("Asset", { source = "<bundleIdentity>" }) ``` What you get: - The bundle's hierarchy spawns as **temporary** children under the owning entity. They're real, addressable runtime entities, but they are NOT serialized into `scene.json` on save, only the Asset component and its entity is saved. - **Live editing of the bundle is supported.** When you edit anything inside the `.bundle/` (entity_template, meshes, materials, sub-bundles, components), every entity in the world carrying that `Asset` component automatically tears down its spawned children and rebuilds them from the new template — same frame, no restart, no manual reload. The `onAssetReload` hook in `Asset.component/init.luau` drives this. - **Per-instance overrides survive across reloads.** Move a spawned child, rename it, add/remove components on it, edit a component's public state — the changes land in the Asset's `public.diff` (a sparse delta keyed by the child's `original_id`) at save time and are replayed by `bundleRef:instantiate()` on next load. The bundle stays a single source of truth; per-spot tweaks ride on top. - **Stable child ids across reloads.** `public.idMap` records the `original_id → runtimeId` assignment on first spawn; on every subsequent spawn the same mapping is reused so cross-entity references (e.g. `SkinnedModel.skeletonRoot = "ent_xxx"`) stay valid. ### 2. `bundleRef:instantiate` — baked, no live link Resolve the bundle and instantiate it onto an entity — this spawns the children **without** the live-link plumbing the `Asset` component provides: ```luau local car = entity.spawn("car_1") asset.resolve("<Name>", "bundle"):instantiate(car) ``` What you get — and the trade-offs: - The children spawn as **regular** (non-temporary) entities. On the next `layers.active:save()`, the entire spawned hierarchy is serialized into `scene.json` verbatim. - **No live link to the bundle.** Editing the `.bundle/` after the fact has no effect on already-spawned hierarchies. The bundle was effectively consumed at spawn time. - Scene-save / restore round-trip works the same as for any other hand-authored entity tree. Use this path when you want a one-shot expansion of the bundle into permanent scene state (e.g. you're populating a scene's static layout from a parametric bundle and don't want a live link). You can convert a live-linked instance into a baked one explicitly via `Asset:bakeIntoScene()` — this drops the `Asset` component and promotes the temporary children to permanent scene entities. ## How it operates 1. **Registration.** Writing into a `.bundle/` folder indexes the asset with the container-category restore plumbing. 2. **Inner refs.** Component fields that reference assets inside the bundle use the `__ref` shape (`{ "__ref": "<guid>", "name": "...", "type": "..." }`). The asset registry resolves them at spawn time. 3. **Identity.** The `.bundle` suffix is stripped, so a bundle resolves as `<Name>` (`asset.resolve("<Name>", "bundle")`); the type argument tells it apart from any `<Name>` of another type. 4. **Hot reload.** Saving `entity_template` (or any file in the bundle directory) fires the engine's per-asset content-changed hook, which calls `onAssetReload("source")` on every entity whose `Asset` component points at the bundle. Each carrier despawns its children and re-instantiates against the new template — typically next frame. ## Discovery - `asset.list("bundle")` — every registered bundle. - `asset.inspect("<name>")` — sub-asset catalog, source, this type README. - `ls /zero/source/<Name>.bundle` lists the files the folder holds. ## Parts and slots A bundle can be an object assembled from parts, and a part that fills one. A child carrying a `Slot` component is a named place another part fills (its `kind`, the `tags` a part must carry, a `default` part, and where the part attaches: that child's transform). A bundle whose root carries a `Part` component is a part, and its `fits` names the slot kinds it fits. An `Assembly` on the root holds what fills each slot by path (`wheel_fl`, `engine/turbo`, a part's own slots nesting under the slot it fills), and resolves, swaps and explains them at runtime: ```luau local car = entity.spawn("car") car.component.add("Asset", { source = "Buggy" }) -- a bundle with slots and an Assembly at its root local asm = car.component.get("Assembly") asm:configure({ wheel_fl = "SportWheel", engine = { part = "V8", turbo = "Turbo" } }) asm:fill("wheel_fl", "OffroadWheel") -- rebuilds that wheel alone print(asm:fits("wheel_fl", "V8")) -- false, and why ``` The configuration is saved with the scene and synced; the parts are runtime children rebuilt from it. `guides { path: "topics/assemblies" }` covers the whole family. ## Authoring conventions - Prefer `bundle:update()` or `asset.create("bundle", "<name>", { entity = ref })` over hand-authoring `entity_template`. The in-scene composer wires `__ref` shapes correctly and pulls in every transitively-needed asset. - Keep bundles focused — one prefab per bundle. If you have a "vehicle + driver + sound" assembly, split into three bundles and reference them from a scene rather than packing all three into one bundle. - Name child entities meaningfully — bundle interiors are inspectable, and stable IDs let other tooling (`entity_template` edits, animation hooks) find them. - Sub-bundles compose: a bundle's `entity_template` can `__ref` a child `.bundle/`. The asset registry resolves them transitively. ## Common pitfalls - **Confusing the two spawn paths.** `Asset` component = live link, reference-only scene save. `bundleRef:instantiate()` directly = baked, full hierarchy in `scene.json`. - **Copying JSON between bundles.** A copied `entity_template` does not bring the assets it references along with it; re-compose from a live scene rather than copy-pasting JSON. - **Live editing only fires for live-linked carriers.** Already-baked entities don't update when you edit the source bundle. ## Related types - `Asset.component` — the canonical mount point for a live-linked bundle. See its README for the `idMap` / `diff` machinery in detail. - `.scene` — owns a whole world's worth of entities; spawns bundles into itself via `Asset` components on per-spot entities. ## In the Inspector Selecting a bundle opens its **Contents** section, from the bundle's inspect detail: the template's node count, its root, the component types attached across it, a table of each renderable node's mesh and material, and a link to each of those meshes and materials.
▲ 0↑ born
◐
material · born here
❒asset
# Chrome A polished chrome surface built on the `pbr` shader — fully metallic (`metallic: 1.0`) with a bright near-white base colour (`0.95, 0.95, 0.97`) and very low roughness (`0.05`) for mirror-sharp reflections. Opaque, back-face culled, instanced, with the `_METALLICSPECGLOSSMAP` keyword enabled. ## Inputs - `colors.base_color` (`0.95, 0.95, 0.97, 1.0`) — bright, faintly cool chrome tint. - `floats.metallic` (`1.0`) — fully metallic. - `floats.roughness` (`0.05`) — near-mirror sharpness. - `textures.base_color_texture` (`default:white`): the white base texture the colour multiplies against, so the surface renders `base_color` alone.
▲ 0↑ born
·
assettype · born here
❒asset
# guide A guide is a single-file documentation asset: a `<name>.guide/` folder whose body is `guide.md`, surfaced through the `guides` MCP tool, the `man` shell builtin and the Docs panel. Drop one anywhere under `/zero/source/`, a `.package` included, and it shows beside the built-in guides. ## Linking guides together A markdown link in a guide is followed when it is clicked in the Docs panel: `[Bindings](controls-guide)` opens another guide by any name `guides read` takes, `[Slots](#save-slots)` a heading of the same guide (its text in lower case, punctuation removed, spaces turned into `-`), `[Slots](save-kit#save-slots)` a heading of another, and `[the module](../saveKit.module)` a file or asset, relative to the guide's own folder. A link the panel cannot follow says why above the guide. ## In the Inspector Guide: the guide's word count, its headings, and **Open in Docs**, which opens it in the Docs panel.
▲ 0↑ born
·
assettype · born here
❒asset
# 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 } }, } }) ```
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# dataType (asset type) A dataType is a user-authored typed-data contract: it declares a set of fields — names, types, constraints, defaults — that any bound `.data` instance must satisfy. A contract can carry an optional `behavior.luau` of methods its instances expose. Think of it as a ScriptableObject schema: the contract defines structure and behavior, `.data` instances supply the values. ## When to use one - You want a typed, validated configuration shape (a weapon's damage / fire mode / recoil profile, a quest's objectives, a loot table's entries) that many `.data` instances can be authored against. - You want field-level validation (required, numeric ranges, enums, references to other assets or data instances) enforced the same way everywhere the contract is used. - You want shared structure across related contracts without duplicating field declarations — `extends` factors common fields into a parent contract. If you only need a named set of values for settings something already declares, use a `.preset` instead. If you need executable shared logic rather than typed configuration, use a `.module`. ## Where it lives - Source: `/zero/source/.../<Name>.dataType/` - Identity: `<Name>` (the `.dataType` suffix strips). - Folder shape: - `schema.yaml` — the field declaration (`fields:`, optional `extends:`). **Required.** - `README.md` — instance documentation: what the contract models, what each field means. **Required.** - `.metadata` — description + tags for search. **Required.** - `behavior.luau` — optional ref methods this contract's `.data` instances expose beyond the built-in `:contract` / `:satisfies` / `:validate` surface. ## How to create one ```luau asset.create("dataType", "<Name>") -- Creates: /zero/source/<Name>.dataType/ -- schema.yaml (`fields: {}`, a valid contract with no fields yet) -- README.md (instance README template) -- .metadata (empty description/tags — fill both to publish) ``` Then edit `schema.yaml` to declare the contract's fields. ## `schema.yaml` field-spec vocabulary ```yaml extends: "item" # optional: parent contract identity fields: damage: type: number required: true min: 0 max: 100 fireMode: type: string enum: ["semi", "burst", "auto"] default: "semi" muzzle: type: vec3 default: [0, 0, 0] tint: type: color # "#rrggbb"/"#rrggbbaa" or {r,g,b[,a]} fireSound: type: assetRef assetType: soundClip # required for assetRef fields recoil: type: dataRef contract: recoilProfile # required for dataRef fields required: true falloff: type: array items: type: struct fields: distance: { type: number } multiplier: { type: number } ``` Field types: `number`, `string`, `boolean`, `vec3`, `color`, `assetRef`, `dataRef`, `array`, `struct`. - `required` — a boolean; a field with a `default` is never "missing" even when `required` is set. - `default` — must itself satisfy the field's own constraints (checked at declaration time). - `min` / `max` — apply only to `number` fields. - `enum` — apply only to scalar fields (`number` / `string` / `boolean`); the value must equal one of the listed entries. - `assetRef` — needs an `assetType`; validated against `asset.resolve(identity, assetType)`. - `dataRef` — needs a `contract`; validated against whether the referenced `.data` instance's contract chain includes it (`:satisfies`). - `array` — needs an `items` field spec every element must satisfy. - `struct` — needs a `fields` map of nested field specs; struct values reject unknown keys the same way top-level values do. ## `extends` A contract may declare `extends: "<parentContract>"` to inherit the parent's fields. The child adds new fields — it never redeclares a field the parent (or any ancestor) already declared; doing so is a schema error. Behavior is optional at every level: a contract may carry `behavior.luau` or not regardless of whether its parent does. Chains are single-inheritance and acyclic — a cycle raises loudly the moment the chain is resolved (`:schema`, `:validate`, `:defaults`, `:chain` all resolve the chain). Editing a parent's schema does not re-warn its child contracts at edit time; validation stays loud where the chain is used — `:schema` / `:validate` calls and the publish gate. ## Ref surface (`AssetRef<dataType>`) - `ref:schema()` — the merged field map (own fields + every field inherited through `extends`). - `ref:validate(values)` — `(ok, violations)` against the merged schema. `violations` is an array of `{ path, message }`. - `ref:defaults()` — the default value table the merged schema declares (a fresh, mutable table). - `ref:parent()` — the parent contract ref (`extends`), or nil for a root contract. - `ref:chain()` — the full extends chain as refs, root parent first, this contract last. - `ref:instances()` — every `.data` instance bound to this contract or to a contract that extends it, as `AssetRef`s. A full scan over the world's data assets — a discovery surface for authoring and tooling, not a per-frame call. ## Discovery - `asset.list("dataType")` — every registered contract, as `AssetRef`s. - `asset.inspect("<name>")` — the contract's files, declared schema body, instance README, and this type README. - `ls /zero/source/<Name>.dataType` lists the files the folder holds. ## Authoring conventions - Name contracts for the concept they type (`weapon`, `questObjective`, `lootTable`), not for a specific instance. - Factor genuinely shared fields into a parent contract via `extends`; don't duplicate a field declaration across sibling contracts. - Document every field's meaning and units in `README.md` — the schema only carries types and constraints, not intent. ## Common pitfalls - **Redeclaring an inherited field.** `extends` merges parent fields in; a child that re-declares a field name the parent already declared is a merge error, not a silent override. - **Cyclic `extends`.** Contract A extending B extending A raises loudly the first time the chain is resolved — fix the chain, there is no partial result to fall back to. - **assetRef/dataRef without existence checks.** `assetType` and `contract` on ref fields are declaration-time requirements; the referenced asset or data instance is checked at validation time, not declaration time. ## Related types - `.data` — a configured value instance bound to a dataType contract. - `.preset` — a named set of values for one declarer's settings schema (an assetType, an importer, a component), not a contract of its own. - `.component` — executable entity behavior, versus this type's typed configuration data. ## In the Inspector Contract: the contract it extends (a link), every field across the extends chain with its type, whether it is required, its default and its bounds or allowed values, and **Count instances**, which scans every data asset for the ones that satisfy it (a count taken before a data asset was made or removed says so).
▲ 0↑ born
◐
material · born here
❒asset
# Snow Particle A soft, cold-white flake surface for falling-snow particle effects — a near-white base colour (`0.95, 0.97, 1.0`) with a cool blue-grey emissive glow (`0.25, 0.3, 0.4`) so flakes stay faintly visible in shadow. Transparent, double-sided (`cull: none`), and drawn in the transparent queue (`3000`). Built on `@builtin::shaders.snow_material`. ## Inputs - `colors.base_color` — the cold-white flake tint. - `colors.emissive` (`0.25, 0.3, 0.4`) — cool self-illumination that keeps flakes readable in dark scenes. - `floats.roughness` (`0.8`) — matte, non-glossy flakes. - `floats.metallic` (`0.0`) — fully dielectric.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Gold Polished gold — a fully metallic PBR surface with a warm yellow base colour (`1.0, 0.84, 0.0`) and low roughness (`0.25`) for bright, sharp reflections. Built on `@builtin::shaders.pbr`. ## Inputs - `colors.base_color` — the gold tint. - `floats.metallic` (`1.0`) — fully metallic. - `floats.roughness` (`0.25`) — sharpness of the reflection; raise for a brushed look.
▲ 0↑ born
·
assettype · born here
❒asset
# procRecord: a kind of record a graph makes and saves A `.procRecord` defines a kind of value a procedural graph moves that becomes an asset when it is saved: a material, a mesh, a texture, or a kind a world defines for its own asset type. Its `init.luau` returns `proc.record({ ... })`: ``` Glow.procRecord/ init.luau -- returns proc.record({ ... }) README.md -- what a record holds and the asset it saves as .metadata -- description and tags ``` ## What a kind states - **`name`**: the kind's display name. A kind is identified by its guid, so two kinds may share a name. - **`asset`**: the asset type a record saves as (`"material"`). - **`applies`**: `{ component, field }`, the component a record stands in live and the field it feeds (`{ component = "Material", field = "material" }`). - **`fields`**: the record's own fields by name, each with a short description. - **`live(record, key)`**: the runtime value the applied field takes, filed under `key`. - **`release(value, key)`**: lets go of what a runtime value `live` answered holds. Left out, the kind holds nothing to let go of. - **`save(record, name, place)`**: writes the record as its asset and answers the reference. Left out, the asset type's own `graph.write` writes it. - **`load(ref, options)`**: the record an asset of the kind holds. Left out, the asset type's own `graph.read` reads it. `name` and `asset` are required; a key outside these is refused, naming the keys a kind states. ## How records travel A record carries its kind's guid as `kind`. The node that writes a record holds it on an element, in the attribute named after the component the kind applies to (`Material = { material = <record> }`), and states the kind on the geometry's detail attribute `records`: `{ [<kind guid>] = <reference to the .procRecord> }`. `io.output` stands the element with the runtime value the kind's `live` answers, `io.export` saves the record through the kind, and `io.import` reads an asset back as the same element: an asset type names the kind its assets load as in its `graph` conversion (`graph.record`). A node references a kind by a literal reference, `asset.resolve("<identity>", "procRecord")`, and `proc.records.stamp(ref)` gives the `records` map that names it. `io.import` of a `.procRecord` answers the kind itself, `{ kind, name, asset, applies }`: the guid a record of it carries and what it saves as and applies to.
▲ 0↑ born
◐
material · born here
❒asset
# Checkerboard A procedural checkerboard pattern rendered by `@builtin::shaders.checkerboard`, alternating a red base colour (`1.0, 0.2, 0.2`) with a blue emissive colour (`0.2, 0.2, 1.0`). Opaque and non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — useful as a UV / scale test surface. ## Inputs - `colors.base_color` — the red square colour. - `colors.dark_color` — the blue square colour. - `floats.roughness` (`0.5`) — diffuse spread on the lit squares. - `floats.metallic` (`0.0`) — dielectric surface.
▲ 0↑ born
◐
material · born here
❒asset
# Custom Textured A textured opaque surface built on `@builtin::shaders.custom_material`, sampling the `array_texture` builtin over a warm peach base colour (`1.0, 0.8, 0.6`). Non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — a worked example of pairing a custom shader with an array texture. ## Inputs - `textures.base_color_texture` (`@builtin/textures/array_texture`) — the sampled array texture. - `colors.base_color`: the warm peach colour the texture is multiplied by. - `floats.roughness` (`0.5`) — diffuse spread. - `floats.metallic` (`0.0`) — dielectric surface.
▲ 0↑ born
◐
material · born here
❒asset
# Sky Procedural A fully procedural atmospheric sky with a day/night cycle, built on `@builtin::shaders.procedural_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), computing gradient, sun, moon and stars analytically from its parameters — no texture required. ## Inputs - `properties.zenith_color` / `horizon_color` / `ground_color` — the atmospheric gradient from overhead (`0.1, 0.3, 0.6`) through the horizon (`0.5, 0.7, 1.0`) to the ground (`0.3, 0.25, 0.2`). - `properties.sun_intensity` (`20`) / `sun_size` (`0.02`) — brightness and disc size of the sun. - `properties.turbidity` (`4`) — atmospheric haze / scattering density. - `properties.stars_intensity` (`1`) / `moon_size` (`0.03`) — night-sky star brightness and moon disc size.
▲ 0↑ born
◐
material · born here
❒asset
# Sky Cubemap A cubemap sky/environment background built on `@builtin::shaders.cubemap_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` with adjustable rotation and exposure. ## Inputs - `textures.sky_texture` — the cubemap sampled as the sky (`Ryfjallet_cubemap`). - `floats.rotation` (`0.0`) — yaw rotation of the sky around the vertical axis. - `floats.exposure` (`1.0`) — brightness multiplier applied to the sampled colour.
▲ 0↑ born
·
assettype · born here
❒asset
# tool (asset type) A tool is one named operation: a single luau `typed function` inside a toolboxe's `<name>.tool` asset, callable as `<toolbox>.<tool>`. The function's signature is the tool's interface, so anyone can call it correctly without reading its code. A tool is also a shell command, `zero <toolbox> <tool> <args>`; `guides core/tools`, "A tool's command line", covers its flags, paths, `render.luau` and exit status. Each tool has a declared input shape and return shape; the engine wraps each call's result in an envelope. ## Why use a tool? Tools are typed operations with a known serialized output format, made to enable efficient operation in the engine and provide an easily callable interface for operations around a topic. They are also useful in that they can be called from a multitude of surfaces, from `execute`, to `bash` to `tool_exec` to users Tools portion in the edui. Compared to say a `module.assetType`, that might contain multiple functions with varying shapes, experct references or specific formats of tables as input and could return potentially anyting including flat tables. that has multiple callable functionm in that they might return anything a tool is meant to be called with a serialized value, and return a serialized value. A tool is meant to perform an self contained operation and return results/info/relevant data in a readable format, including eg. image data. Whenever you identify an operation that requires specific orchestration and or is something that could be a repeated operation and makes it easier to manage the project/task or when you want to expose logic written in `luau` to the other call surfaces like `bash` under its `zero` command, it propably should be a `<name>.tool` asset. ## How tools are written In its simplicity, a tool is a single Typed luau function that returns a value. written plainly, in its basic form it could look like this. ```luau -- probe.toolbox/onCall.tool -- -- Fire when a named function runs, seeing its arguments and what it returned. --- A toolbox offered shared module, that in this case,contains a type shared by the tools in their toolbox. local shared = require(".shared") local M = {} export type OnCallResult = { ok: boolean, id: string?, result: string?, error: string?, } --!desc example tool --!arg path target path for the operation --!arg opts `{ notice, when?, run?, capture?, label?, limit?, cooldown?, freeze?, silent? }`. -- `capture` is Luau, compiled against the hit's context the way `run` -- is, that returns a picture for the hit — a capture tool you aim: -- `return tools.use("capture", "fromEntity", { entity = entity })`. It -- runs once the hit is recorded, and the hit's notice then carries the -- picture under `shot`, delivered as a picture. --!return `{ ok, id, result }`. --!example "arg1", arg2 typed function M.gatherResults(path: string, opts: shared.ArmOpts): OnCallResult local modulePath, key = splitPath(path) --- the tool code implementation local results = myCodeResults --- the tool call returns a table with keys, that is then wrapped in a return envelope. return { ok = true, id = results.id, result = results.gathered } end return M ``` Now when called, the tool runs and returns the envelope with the inspectable results. ## Why return plainly, and fail by raising Every caller gets a tool's outcome in the same form, success or failure, so return the value itself and raise an error when the tool can't do its job. A tool that returns its own `{ ok = false }` reads as a success that happened to return that table. Make the error say what to do instead: the caller reads it and acts on it. ## What the shell prints `zero <toolbox> <tool>` prints the text the tool's `render.luau` states: a module in the tool's folder returning one function `(result) -> string | { out, err?, exit? }`. A returned string is the output, and `{ out, err?, exit? }` sets the output, the standard error text and the exit status. A call that raises exits 1, and a command line the shell cannot bind to the tool's parameters exits 2. ## When to answer later instead of blocking A caller waits for the tool to return, and might be calling multiple tools at the same time. Should your call run past the waiting threshold in order to return, even if it yields it comes back as a handle to a background task that will then complete on its own, but require the caller to separately read the task results. For a call that is small, answering inline with the result is better. When a tool can tell that this particular call will be long (a big bake, a large batch, a slow fetch), it hands itself to the background with `task.background()` early, so the caller gets the handle at once and carries on with other work. ## When to post a notice The return value is the answer to what was asked. A notice is for what the caller needs to know besides that: a side effect it didn't ask for, a return to one that has no caller, notices should be treated as a way to make sure your tool can return quickly, when you arent sure how long it takes for the results to be ready. It allows the agent to continue working, and then react when the notice fires. `notices.post` delivers it to the caller, and an agent that is idle is woken by it, so the caller learns it without polling. Name in it what to do about it. A notice for something the return value already says is noise. ## Returning more than text Tools also support returning images, that the agent can then directly read from the tool response, regardles of what surface they used to call the tool. Images also work on notices, so you can eg attach visual results to the eventual outcomes of your tool results and the agent will see them the second the notice fires. ## What a tool may do that other code may not A tool, and code only tools call, may act on whatever an input names, resolving an asset by a name that only arrives with the call. That is what makes a tool the place for operations that depend on what they are given. Tools are for working on a world rather than running in the game: a component may not call one unless it declares `declare { componentSafe = true }`, and a tool doesn't call another tool, so logic several tools need goes in the toolbox's shared module or exist elsewhere. For information how to group tools and organize them, and how they are called read `toolbox.assetType` readme. ## In the Inspector Tool: how the tool is called (its signature), what it does, each argument, what it returns, and its examples, with **Open** for its source.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Default Unlit A flat, unlit surface that renders its base colour directly with no lighting response, built on the `unlit` shader. Uses a white base colour (`1.0, 1.0, 1.0`) over the `default:white` texture with `emissive` (`1.0`) for full brightness — the go-to default for UI, gizmos, and debug geometry that must stay legible regardless of scene lighting. ## Inputs - `colors.base_color` — the flat colour shown directly. - `textures.base_color_texture` (`default:white`) — the white base texture the colour multiplies against. - `floats.emissive` (`1.0`) — full, lighting-independent brightness.
▲ 0↑ born
·
assettype · born here
❒asset
# Style (asset type) A style is a UI design-token bundle: colour palette, spacing scale, typography pairs, and the widget classes built from them. Registered with the UI theme system, its classes cascade to every widget that names them. Authoring a style is the way to express a brand / theme; consumers register it once and every widget carrying its classes picks up the tokens. ## When to use one - You're branding a UI surface (game theme, editor theme, dialog theme) and want a named token set widgets pick up automatically. - You want a swappable theme — light vs dark, normal vs accessibility contrast. - You want designers to edit tokens (`color.primary`, `spacing.md`) without touching widget code. If you need per-widget overrides, those go inline on the widget, not in a style. If you need shader-driven looks, that's a `.shader` + `.material`. ## Where it lives - Source: `/zero/source/.../<name>.style/` - Identity: `<name>` (the `.style` suffix strips). - Folder shape: - `init.luau` (or `init.lua`) — returns the module carrying the token table. **Required.** - `README.md` — instance documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** ## How to create one ```luau asset.create("style", "<name>") -- Creates: /zero/source/<name>.style/ -- init.luau (token scaffold: color / spacing / font) -- README.md (instance README template) -- `folder` places it in a subfolder of /source instead of the root: asset.create("style", "<name>", { folder = "themes" }) ``` ## How it operates 1. **Registration.** Writing `init.luau` into a `.style/` folder registers the asset — it is listable, inspectable, and referencable by identity. 2. **Token shape.** `init.luau` returns a module exposing `M.tokens`, one nested table per token category: - `color.<name>` / `spacing.<name>` / `font.<name>` are the conventional three; a style may declare any category it wants. - A value is a literal (a `"#rrggbb"` colour string, a number, an array) or a `"$otherToken"` reference resolved during the cascade. An optional `M.styles` maps a selector — `<widgetType>`, `<widgetType>.<className>`, or a bare `.<className>` — to a block of style properties, each value a literal or a `$token` reference. 3. **Cascade.** The stylesheet resolves a widget's look in the order `type` → `type.class` → `.class` → inline props. Widgets select classes with their `classes` (or `class`) prop. 4. **Application.** `styleRef:loadTheme()` returns the table the style exports. The UI takes it through `ui.registerTheme(name, { tokens, styles })`, with every `$token` already resolved to its value. From there `ui.setTheme(name)` makes it the active theme, and `ui.useStyles(name)` applies a registered theme's classes additively without changing the active one. `ui.defineStyle` / `ui.defineStyles` define individual classes directly. 5. **Hot reload.** Editing `init.luau` reloads the asset; re-register the style for the change to reach the live stylesheet. ## Discovery - `asset.list("style")` — every registered style. - `asset.inspect("<name>")` — `tokenCategories` (the top-level keys of the style's `M.tokens` literal, read from its source text), source, and this type README. - `ls /zero/source/<name>.style` lists the files the folder holds. - `styleRef:getInitScript()` — the entry script's raw text. ## Authoring conventions - Write colours the way the theme system reads them — `"#rrggbb"` / `"#rrggbbaa"` hex or `rgba(r,g,b,a)` strings. - Name tokens semantically (`color.primary`, `color.danger`, `spacing.gutter`), not by visual value (`color.blue`, `spacing.eight`). Semantic names survive theme swaps. - Keep token names stable. Widgets reference tokens by name — renaming a token forces every consumer to update. - Document `light` / `dark` variants under separate `.style/` folders with paired names (`game.style`, `gameDark.style`) rather than switching values within one style. ## Common pitfalls - **Unknown `$token` reference.** A `"$name"` with no matching token fails the cascade with `token 'a': unknown token: $name` and the style never reaches the stylesheet. Read the error rather than the render. - **Token reference cycles.** `$a` → `$b` → `$a` is reported as `token 'a': cycle detected: a → b → a` when the theme is resolved. - **Missing tokens.** A widget asking for `color.warn` when the style doesn't define it falls back to the active theme. Inspect the style to confirm the token surface. ## Related types - `.component` — `UiPanel` and other widget components consume styles. - `.material` / `.shader` — for 3D surface looks (different cascade system). - `.package` — to ship styles + components together as a theme package. ## In the Inspector Selecting a style opens its **Tokens** section, from the theme `styleRef:loadTheme()` returns: a swatch per colour token, its spacing values, and a table of its font tokens (family and size). A style written as YAML style classes (a `styles:` map of class name to properties, applied with `ui.useStyles`) shows how many classes it declares and, for each class, its colour properties as swatches and its other properties as values. A style whose `init.luau` does not load a `tokens` table says why.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Instance Color A lit white surface that every instance wearing it colours from its own shader-data lane 2, built on `@builtin::shaders.pbr` with `instance_color_lane = 2`. One material draws hundreds of members in hundreds of colours, and a colour that changes every frame costs one `renderer.instanceData.set` per member: a stress map over a bridge, a heat map, a damage flash, team colours, a selection highlight, a gauge. ```luau local LANE = 2 for i, id in members do local load = loads[i] -- 0 relaxed .. 1 at its limit renderer.instanceData.set(id, LANE, load, 1 - load, 0, 1) -- green to red, fully covered end ``` The lane's `rgb` is the colour and its `a` is how much of it covers the base colour and the emission, 0 none through 1 all; an instance whose lane was never written reads zero and draws plain white. The colour replaces the base colour before lighting, so the member still shades, casts its highlights and shows the lane colour in the `albedo` capture pass. Set `instance_emission` above 0 for a colour that glows where it covers. `renderer.mesh.drawInstanced` reads the same lane from its `instanceDataBuffer`, so a GPU-filled population colours each copy the same way. The writes are local to the engine that makes them and replicate nothing; `Model.tint` is the synced form of a tint, for a colour every participant must see. ## Inputs - `floats.instance_color_lane` (`2`): the lane read; lanes 0 and 1 carry a baked lightmap's rect and layer. - `floats.instance_emission` (`0`): how brightly the lane colour glows. - `colors.base_color` (white), `floats.roughness` (`0.5`), `floats.metallic` (`0`): the surface under the lane colour.
▲ 0↑ born
·
assettype · born here
❒asset
# soundClip An **audio asset** — a managed container holding a sound effect or music track, addressed by the `.soundClip` suffix. `soundClip` is a first-class assetType (not a bare plural-dir category) so that: - a soundClip has a stable asset **identity** and an explicit `asset_type` link, and - a component that plays a soundClip records a real `.refs` edge to it. ## Internal layout A `.soundClip/` is permissive (`allow_unlisted: true`) — the conversion step decides its shape. A managed container holds: ``` <name>.soundClip/ source.<ext> the retained source audio (.ogg / .mp3 / .wav / .flac): `asset.create` keeps a copy of the bytes it was given under this name, and the importer moves the uploaded file in under its own name instead. Absent for a PCM-baked clip. settings.yaml compression settings — see below data.zaud engine-native ZAUD payload the runtime decodes + plays, under the codec its own header names README.md what the sound is and what it is for ``` `data.zaud` is the **preferred primary**: when present the runtime resolves and decodes it directly. When absent the primary falls through to the source audio file, so imported-only containers keep working. ## Settings A soundClip's settings are declared in `settings.luau` and live in `settings.yaml`. Editing any of the encode-relevant ones re-runs encoding — against the retained source audio when the container has one, or against the decoded `data.zaud` for a PCM-baked clip — and rewrites `data.zaud`. Rewriting the retained source audio re-encodes it the same way: | key | values | meaning | |-----|--------|---------| | `codec` | `opus` (default) / `pcm` | output codec. `opus` compresses; `pcm` stores uncompressed samples. | | `bitrateKbps` | integer, default `96` | Opus target bitrate (ignored for `pcm`). | | `vbr` | `true` (default) / `false` | Opus variable bitrate. | | `sampleRate` | integer, `0` = keep source | resample target in Hz. | | `forceMono` | `false` (default) / `true` | downmix to a single channel. | | `loadType` | `auto` (default) / `decompressOnLoad` / `streaming` | how the runtime loads the clip. | | `loopStart` | integer frames, `0` = none | loop-point start. | | `loopEnd` | integer frames, `0` = none | loop-point end. | `loadType` alone never re-runs encoding — it decides how the runtime holds the clip, not what `data.zaud` holds. It acts on an already-playing `Audio` component instead: the next source that component builds reads the new value fresh and rebuilds under it. The `data.zaud` payload is produced by the engine's audio codec, exposed to Luau as `audio.encode` / `audio.encodePcm` / `audio.decode` / `audio.info` / `audio.loopSeam` and consumed by this assetType. Every sample the codec is handed must be a finite number, so `asset.create` raises when the `pcm` or `bytes` it is given carries a NaN or an infinity, and the error names how many samples fail and where the first one sits. ## Does it loop without a click Whole-clip repeat is the loop the runtime plays, so the join between a clip's last frame and its first is heard once a lap. `clipRef:loopSeam()` reads what the samples do there: the step the wrap makes (`|x[1] - x[frames]|`) against the step the signal ordinarily makes between neighbouring samples, as `ratio = step / meanStep`. The figure is in the units the signal itself moves in, so a generated ambience travelling a thousandth of a unit per sample and a synth drone travelling a hundredth are read the same way. | field | meaning | |-------|---------| | `ratio` | `step / meanStep` on the worst channel — one channel clicking is the clip clicking. | | `step` | `\|x[1] - x[frames]\|`, the step the wrap makes. | | `meanStep` | the mean `\|x[i + 1] - x[i]\|`, the distance the signal ordinarily travels in one sample. | | `maxStep` | the largest `\|x[i + 1] - x[i]\|` the channel already carries. | | `channel` | which channel the four figures above came from, counted from 1. | | `seamless` | `ratio <= threshold`. | | `threshold` | the ratio the engine warns past — `8`. | | `channels` | every channel's own `{ ratio, step, meanStep, maxStep }`, in channel order. | A bed whose partials complete a whole number of cycles across the buffer reads near 1; one carrying a percussive strike at its head and silence at its tail reads in the tens. ```lua local seam = clipRef:loopSeam() if not seam.seamless then print(seam.ratio, seam.step, seam.meanStep) -- e.g. 41.0 0.5993 0.0146 end ``` `asset.create("soundClip", ...)` takes the same reading of the payload it just encoded and logs a warning naming the ratio when it is past `threshold`, so a bed that ticks is reported at the call that bakes it. The re-encodes a source edit and a settings change trigger report it the same way. The reading is taken on the DECODED payload, so it answers for what the codec left behind rather than for the buffer that was handed to the encoder — and for a clip that arrived already encoded, from an import or from ZeroMind, whose source buffer nobody holds. ## Creating a soundClip `asset.create("soundClip", name, opts)` reads seven keys of its own out of `opts`, and the settings table above is one of them. `asset.create`'s framework keys — `folder`, `into`, `dest` and `overwrite` — apply to a soundClip the way they apply to every type. | parameter | type | meaning | |-----------|------|---------| | `bytes` | `string?` | encoded source audio (OGG / MP3 / WAV / FLAC), stored verbatim as `source.<ext>` by default. | | `ext` | `"ogg"` (default) / `"mp3"` / `"wav"` / `"flac"` | which container `bytes` is in. | | `writeSource` | `boolean?`, default `true` | keep the source audio in the container as `source.<ext>`. `false` skips the copy — the caller supplies the source itself (the importer moves the uploaded file in under its own name instead). | | `pcm` | `buffer \| string \| { number }?` | interleaved f32 samples — a `buffer`, the shape `microphone.samples` hands back; a binary string of little-endian f32, the shape `audio.decode` returns; or a flat number array. | | `sampleRate` | `number?` | the rate the `pcm` samples are at, in Hz. Required with `pcm`. To resample a clip, set `settings = { sampleRate = ... }`. | | `channels` | `number?` | how many channels they interleave. Required with `pcm`. | | `settings` | `table?` | the full settings table from the section above, baked in the same pass; wins over the defaults. | `ext` and `writeSource` belong with `bytes`, and `channels` with `pcm`: a create that passes one of them without the opt it belongs with is refused, naming both. ```lua -- from encoded audio bytes (kept as source.<ext>, encoded to data.zaud) asset.create("soundClip", "music", { bytes = oggBytes, ext = "ogg" }) -- the caller supplies the source itself (moved in under its own name after -- create, preserving its identity) — the importer's own promote path asset.create("soundClip", "music", { bytes = oggBytes, ext = "ogg", writeSource = false }) -- from raw PCM samples (no source file; encoded straight to data.zaud) local samples = buffer.create(960 * 4) for i = 0, 959 do buffer.writef32(samples, i * 4, math.sin(i * 0.05) * 0.5) end asset.create("soundClip", "beep", { pcm = samples, sampleRate = 48000, channels = 1 }) -- the same samples kept exactly as handed in, under a codec and a load -- strategy chosen in the one pass that bakes them asset.create("soundClip", "bed", { pcm = samples, sampleRate = 48000, channels = 1, settings = { codec = "pcm", loadType = "decompressOnLoad" }, }) ``` A `buffer` is the cheap container for a long clip: a 1.5 s mono 48 kHz clip is 72 000 samples, which is a 288 KB buffer against a 72 000-entry Luau table. **Choose the codec at create time.** Encoding runs once per bake, and a later settings change re-encodes from what is already stored — the retained source audio when the container has one, and otherwise the decoded `data.zaud`. So a clip baked with the default `opus` and then given `setSettings({ codec = "pcm" })` stores the Opus signal losslessly rather than the samples that were handed in: the frame count, the duration and the settings table all read as asked for, and only the samples differ. Passing `settings` to `asset.create` bakes the samples once, under the codec they are meant to keep. Read a clip's settings with `clipRef:settings()`, patch them with `clipRef:setSettings({ bitrateKbps = 64 })`, read its stored payload's header with `clipRef:info()`, decode its samples with `clipRef:pcm()`, and read its loop point with `clipRef:loopSeam()`. `clipRef:info()` is the length, rate, channel count, codec and loop points of the payload the container stores, read off its header: ```lua local info = clipRef:info() print(info.durationMs, info.sampleRate, info.channels) ``` It is the reading to time something against a clip, such as a caption held for as long as its line is spoken, because it costs a header read where `pcm()` decodes every sample to arrive at the same figures. The `sampleRate` it reports is the rate the payload holds; the `sampleRate` in the settings table above is the resample target the encode was asked for, and `0` there means the source's own rate was kept. `clipRef:pcm()` hands back `(pcm, sampleRate, channels)` — the same triple `audio.decode` returns. The samples come back packed rather than as a Luau array: a binary string of interleaved little-endian f32, four bytes per sample, so `#pcm // 4` is the sample count and one sample reads as `string.unpack("<f", pcm, i * 4 + 1)` or through `buffer.fromstring(pcm)`. ```lua local pcm, sampleRate, channels = clipRef:pcm() local frames = #pcm // 4 // channels print(frames / sampleRate, "seconds") -- e.g. 1.5 seconds local peak = 0 for i = 0, #pcm // 4 - 1 do peak = math.max(peak, math.abs(string.unpack("<f", pcm, i * 4 + 1))) end ``` The second and third returns are the clip's own rate and channel count, so a duration is arithmetic on what `pcm()` alone hands back. `audio.info` reads the same figures off the stored payload without decoding it, and the `topics/audio` guide lists every field it returns. The `topics/audio` guide covers synthesis end to end: computing a buffer, baking it into a clip, playing it from an `Audio` component, and reading it back. ## How a source holds the clip `clipRef:streams(bytes?)` answers whether a source playing this clip holds it streaming: `loadType = "streaming"` does, `"decompressOnLoad"` does not, and `"auto"` streams a clip longer than 5 seconds. Pass the `data.zaud` bytes when you already hold them, to skip reading the payload again. Every source the `Audio` component builds asks it, so the policy lives with the clip. ## Auditioning `clipRef:audition()` plays the clip once through the mixer, unpositioned, on the `sfx` channel. It plays on a temporary host entity that the scene never saves and the entity listings leave out, and it replaces any clip already auditioning. It returns the host's entity id, or nil when the payload is unreadable. The host goes when the mixer reports the voice ended. `clipRef:stopAudition()` ends the audition at once and its host goes on the next frame; it returns whether this clip was the one auditioning. A later audition ends the earlier one the same way. `clipRef:lastAuditionEnd()` says how this clip's most recent audition ended once its host is gone, as `{ host, reason }`: `"ended"` (the mixer reported it played through), `"stopped"`, `"replaced"`, `"unvoiced"` (no output, or the mixer turned it away), `"timeout"` (on the mixer past the clip's length with no end reported), `"neverArrived"` or `"hostGone"`. The Playback section shows it under "Not playing.". `clipRef:auditionVoice()` is the audition in progress for this clip: `{ host, voice }`, where `voice` is `audio.voice(host)` (the mixer's view of the voice, nil until the mixer has it), or nil when this clip is not auditioning. ## In the Inspector Selecting a clip shows, after its identity: - **Clip**: the payload header (duration, sample rate, channels, frames, codec, packets and the loop points when set) and whether a source holds the clip streaming or decoded on load. - **Playback**: Play auditions the clip and Stop ends the audition. While it plays, the section shows the mixer's state for the voice and, when the voice is silent, why. - **Settings**: the settings above. - **Waveform** (collapsed at first): 96 bars, each the loudest sample of an equal span of the clip across its channels, from `audio.peaks`. The payload is decoded a block at a time, so a long clip costs no more memory than a short one, and it is read again only when `data.zaud` changes.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Emissive White A bright white light-emitting PBR surface built on the `pbr` shader with the `_EMISSION` keyword enabled. A white base colour (`1.0, 1.0, 1.0`) paired with a strong `emissive` (`20.0`) makes it glow and drive bloom — well suited to light fixtures, emitters, and glowing accents. Non-metallic (`metallic 0.0`) at mid roughness (`0.5`). ## Inputs - `floats.emissive` (`20.0`) — high emission strength that produces the glow. - `keywords: _EMISSION` — enables the emissive path in the PBR shader. - `colors.base_color` — the white surface and emission colour. - `floats.roughness` (`0.5`) — diffuse spread on the lit surface.
▲ 0↑ born
▣
module · born here
❒asset
# 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 ```
▲ 0↑ born
◐
material · born here
❒asset
# Water An animated water surface with a deep blue base colour (`0.1, 0.3, 0.8`) and low roughness (`0.2`) for glossy, reflective highlights, driven by a scrolling normal map for wave detail. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.water_material`, sampling `@builtin/textures/water_normals`. ## Inputs - `colors.base_color` (`0.1, 0.3, 0.8`) — the water body colour. - `floats.roughness` (`0.2`) — low roughness for sharp specular reflections. - `floats.metallic` (`0.0`) — dielectric surface. - `textures.normal_texture` — the wave normal map (`@builtin/textures/water_normals`).
▲ 0↑ born
·
assettype · born here
❒asset
# 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.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_chrome A polished metal: its highlight of a bright light is a sub-pixel specular, the firefly a bloom and a temporal resolve are read on in the post-verification reference scenes.
▲ 0↑ born
·
assettype · born here
❒asset
# `animation` asset type A single animation clip, as a composite asset. The folder `<name>.animation/` carries: - **`data.zanim`** — the engine-native binary clip payload (bincode `AnimAsset`): bone-named tracks, duration, channels. This is the asset's *primary*; consumers reference the `.animation` asset's guid, never this inner file. Parallel to how `.mesh` carries `data.zmsh`. - **`source_rig.json`** (optional) — a reference to the `.rig` the clip was authored on. A clip whose source rig qualifies as humanoid retargets onto any humanoid rig, through the roles each rig's `qualify()` reads from its structure. Clips are produced by the model importers (`model`, `model_animation`), which decode embedded animation tracks and call `asset.create("animation", name, { bytes })`. ## In the Inspector Selecting an animation opens its **Clip** section, decoded from `data.zanim` once per payload version. It reports the clip's name, duration in seconds, channel and bone counts, and, when the clip is tagged, whether it is humanoid. It links the rig named in `source_rig.json` and lists the clip's bones. An animation with no `data.zanim` says so.
▲ 0↑ born
◐
material · born here
❒asset
# Grass blades Swaying grass for a blade mesh, built on `@builtin::shaders.grass_material` with the same green as `@builtin::materials.grass` (`0.22, 0.62, 0.16`) and `sway` at `1.0`. The shader bends each vertex along its blade in proportion to `uv.y²`, so this material belongs on a mesh whose `uv.y` runs 0 at a blade's root to 1 at its tip — a merged field of blades, each a cross of two tapered quads. It inherits the Rust-side render defaults (opaque, back-face culled, queue `2000`) so its pipeline matches the library variant compiled at startup. ## Inputs - `colors.base_color` (`0.22, 0.62, 0.16, 1.0`) — the grass green tint. - `floats.sway` (`1.0`) — the full blade bend. `@builtin::materials.grass` leaves it at the shader's default of `0` for a ground surface.
▲ 0↑ born
·
assettype · born here
❒asset
# gaussianSplat A photographic capture of a real place, stored as a cloud of oriented 3D Gaussians rather than as triangles. Drop a `.spz` or `.ply` into the world and the importer turns it into one of these. ``` room_01.gaussianSplat/ room-01.spz the capture — the primary the runtime decodes .metadata count, bounds, SH degree, axis convention README.md ``` The capture keeps the name it arrived under, so the file you dropped in is the file you find inside. Reach its bytes through the asset — `captureRef:getBytes()` — rather than by spelling the filename. ## Putting a capture in the scene A capture instantiates under the same name a bundle and an avatar do — the entity drawing the cloud is spawned for you, in the axis convention the container recorded: ```luau local root = asset.resolve("room", "gaussianSplat"):instantiate() local child = captureRef:instantiate(entity.spawn("mount")) -- as an owner's child ``` It is scene-compatible (`ref:canInstantiate()` is true), so every consumer of the scene contract takes one: `zero entityOps fromAsset <capture>` is the same spawn as one packaged call, and an `Asset` component pointed at a capture spawns and tears down the cloud with its owner. To place the cloud by hand instead, point a `GaussianSplat` component at it: ```luau local id = entity.spawn("scan").id entity(id).component.add("GaussianSplat", { source = "captures/room.gaussianSplat" }) ``` ## Reading a cloud without decoding it `.metadata` carries what a tool needs to reason about a capture — how many splats it holds, the world-space box it occupies, whether it stores view-dependent colour — so framing a camera on a cloud or reporting its cost does not pay for a decode of the whole thing. ```json { "count": 1920000, "boundsMin": [-24.48, -0.92, -22.19], "boundsMax": [27.52, 33.40, 16.81], "shDegree": 0, "convention": "rightDownFront", "recordBytes": 24 } ``` `boundsMin` / `boundsMax` are the full extent, outliers included. A capture of a whole scene usually carries a sparse halo of stray Gaussians far outside the part anyone looks at, so framing a camera on these bounds puts it outside the scene looking at the halo. For a scene capture, place the camera **inside** it. ## Why the capture stays the primary The engine's packed record pool is 24 bytes per splat — larger than the `.spz` the capture arrived in, whose quantized encoding is what makes the format worth using. Baking the pool into the container would spend storage to save a decode that costs a few hundred milliseconds once per load. ## Guide `guides { path = "gaussian-splats" }` covers capturing, placing, and tuning a cloud. ## In the Inspector Selecting a splat capture opens its **Capture** section: the facts the importer stamped in the capture's `.metadata` (splat count, SH degree, record size, format, axis convention, antialiasing and bounds), and the capture file the asset holds: its primary, the `.spz` or `.ply` under the name it was imported with. A capture folder with no capture file says so.
▲ 0↑ born
◐
material · born here
❒asset
# Text Default The default surface for Text3D — a white base colour (`1.0, 1.0, 1.0`) drawn with alpha blending and no depth write so glyphs composite cleanly over the scene. Transparent, double-sided (`cull: none`), `depth_write: false`, in the transparent queue (`3000`). Built on the `pbr` shader. ## Inputs - `colors.base_color` (`1.0, 1.0, 1.0`) — the glyph colour. - `render.depth_write` (`false`) — glyphs blend without occluding each other. - `render.cull` (`none`) — text is visible from both sides. - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric defaults.
▲ 0↑ born
◐
material · born here
❒asset
# Grid Background A procedural background/reference-grid surface built on `@builtin::shaders.grid_bg`. It draws grid lines over a black base colour (`0.0, 0.0, 0.0`) with full roughness (`1.0`) and no metallic response, rendered opaque with culling disabled (`cull: none`) and instancing enabled so it can back many objects at once. ## Inputs - `colors.base_color` (`0.0, 0.0, 0.0, 1.0`) — black backdrop behind the grid lines. - `floats.roughness` (`1.0`) — fully diffuse, no highlights. - `render.cull` (`none`) — visible from both faces. - `render.instancing` (`true`) — supports instanced draws.
▲ 0↑ born
◐
material · born here
❒asset
# Standard Default The baseline PBR surface — a neutral white base colour (`1.0, 1.0, 1.0`), half roughness (`0.5`), non-metallic (`0.0`), wired with the full standard texture set (base colour, normal, roughness-metallic, emissive, occlusion) and the `_NORMALMAP` / `_OCCLUSIONMAP` keywords enabled. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.pbr`. This is the starting point most materials copy and retint. ## Inputs - `colors.base_color` (`1.0, 1.0, 1.0`) — the albedo tint over the base colour texture. - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric, mid-gloss default. - `floats.normal_strength` (`1.0`) / `floats.ao_strength` (`1.0`) — normal-map and occlusion intensity. - `textures.normal_texture` / `textures.roughness_metallic_texture` / `textures.occlusion_texture` — the PBR map slots, seeded with neutral defaults.
▲ 0↑ born
·
assettype · born here
❒asset
# procPack — a family of procedural ops as content A `.procPack` is a FAMILY of procedural operations authored as content: a folder whose `init.luau` returns a **pack table**. When the asset registers, every def in its `ops` map joins the proc op registry under the stable string id the pack names it with, so a graph calls it by that id (`g.op.<id>`). Discover the available packs with `asset.list("procPack")`, and the ops any of them contributed with `procgen.searchNodes("", { pack = "<name>" })`. This is the one path an op family reaches the registry through. Procgen's own families are packs — `procPacks/` in this package holds one per family, `abi.procPack` beside it holds the ops every node is built from, and terrain's `terrain.procPack` sits in its own package the same way — so the packs shipped here are worked examples of exactly what you are writing, not a separate mechanism the built-ins are exempt from. ``` MyPack.procPack/ init.luau -- returns the pack table README.md .metadata ``` ## The pack table ```lua local proc = require("@builtin::systems.procgen.proc") local function transformed(ctx: any, geometry: any, params: { [string]: any }): any return proc.registry.get("geometry.transform").eval(ctx, { geometry = geometry }, params) end return { name = "myPack", -- the asset's own name when omitted description = "Moves and turns whole geometries.", ops = { ["myPack.lift"] = { description = "Lift a Geometry by a height.", inputs = { geometry = { type = "Geometry" } }, params = { height = { type = "Float", default = 1.0 } }, outputs = { geometry = { type = "Geometry", default = true } }, eval = function(ctx, inputs, params) return transformed(ctx, inputs.geometry, { translate = { x = 0, y = params.height, z = 0 } }) end, }, ["myPack.spin"] = { description = "Turn a Geometry about the up axis.", inputs = { geometry = { type = "Geometry" } }, params = { degrees = { type = "Float", default = 45 } }, outputs = { geometry = { type = "Geometry", default = true } }, eval = function(ctx, inputs, params) return transformed(ctx, inputs.geometry, { rotate = { x = 0, y = params.degrees, z = 0 } }) end, }, }, } ``` Each def is the same table every op in the registry is described by — typed input sockets, params, typed output sockets, and an `eval(ctx, inputs, params)` returning the outputs. `ctx` carries seed / nodeId / compositePath / hash / checkpoint. Validation is the same for every pack, so a malformed socket or an undeclared param type is refused here exactly as it is for the ones shipped in this package. Beside `name`, `description` and `ops`, the pack table takes: - `context`: the context every op of the family works in (`"geometry"`, `"field"`, `"sim"`, ...), for each def that states none of its own. A name that is no registered context is refused. - `aliases`: former op ids mapped onto current ones (`{ ["myPack.raise"] = "myPack.lift" }`). A graph naming a former id cooks the current op, while listings and schemas carry the current id. An alias onto an id that is no registered op is refused, and so is an alias whose former id is itself a registered op. A graph calls a pack's op as `g.op.<id>`, with one table naming its inputs and params: ```lua return proc.define(function(g) local box = g.mesh.box({}) local lifted = g.op.myPack.lift({ geometry = box, height = 2 }) return { mesh = g.op.myPack.spin({ geometry = lifted }) } end) ``` ## procPack or procNode Both contribute nodes that a graph calls. They differ in how a node is written and addressed: | | `.procNode` | `.procPack` | |---|---|---| | contributes | one node, written as a graph (`proc.define(function(g) ... end)`) | a family of ops, each a def table | | addressed by | the asset's identity (`g.points.disc`, a path, a guid or a short name), recorded in the graph by guid | the string id the pack names it with | | a graph writes | `g.<family>.<name>({ ... })` | `g.op.myPack.lift({ ... })` | Reach for a `.procPack` when the ops belong together and you want to read the family's name at every call site; reach for a `.procNode` when one operation stands on its own. ## Finding a pack's ops Search embeds a pack's `README.md` and `init.luau` (the `indexing` block of `type.yaml`), so the README is where a search by what an op does reaches it: list every op of the pack as a line of its own, the op's id and what it does, and keep the line true when the op changes. ``` - `myPack.lift` — Lift a Geometry by a height. - `myPack.spin` — Turn a Geometry about the up axis. ``` `procgen.searchNodes` asks for `.procNode` and `.procPack` assets together. A hit that is a pack is listed as the ops of that pack that answer the query's words (`op.myPack.lift`, with `matched.pack` naming the pack), or as the pack itself when none of them does. ## Registration lifecycle `init.luau` is compiled from its own source on every registration rather than `require`d, so an edit lands immediately. Another module is reached by its absolute name (`@builtin::systems.procgen.proc`), and a file of the pack's own by a relative require (`require(".helpers")`). Every op's `version` is derived from the pack's source, unless its def declares a `version` of its own, so editing the file re-keys the node caches of every graph that reaches any op in the family — those graphs recook. Editing the pack to REMOVE an op unregisters it. A graph built before the edit that still names the op errors loudly at eval, naming the op that is not registered, and a graph source that calls it fails to build, naming the ops the pack still holds. Deleting the `.procPack` folder unregisters the whole family the same way. ## In the Inspector Operations: how many ops the pack registers, and each op's id, kind and what it does.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# data (asset type) A `.data` instance is a configured value binding to a `dataType` contract: `values.yaml` names the contract and supplies the field values the contract's schema declares. Instances carry values only — structure (field types, constraints, defaults) and behavior live on the bound contract, never on the instance. Think of it as the ScriptableObject *asset* to `dataType`'s ScriptableObject *class*. ## When to use one - You have a `dataType` contract (e.g. `weapon`, `questObjective`) and need one or more concrete, named configurations of it (`smg`, `rifle`, `sniper`). - You want the configuration to persist as authored content, discovered by `asset.list("data")` / `contractType:instances()`, and validated against the contract on every edit. - Mutable *runtime* state (ammo remaining, cooldown timers) belongs on a component, not here — a `.data` instance is configuration, not simulation state. If you don't have a contract yet, author one first (`asset.create("dataType", ...)`). ## Where it lives - Source: `/zero/source/.../<Name>.data/` - Identity: `<Name>` (the `.data` suffix strips). - Folder shape: - `values.yaml` — `contract: <dataTypeName>` plus a `values:` map of the contract's fields. **Required.** - `.metadata` — description + tags for search. **Required.** Play-mode edits fork a runtime copy (`runtime_copy: true`) — tweaking values while gameplay runs never writes back to the source instance. ## How to create one ```luau asset.create("data", "<Name>", { contract = "<dataTypeName>" }) -- Creates: /zero/source/<Name>.data/ -- values.yaml (contract binding + the contract's declared defaults) -- .metadata (empty description/tags — fill both to publish) ``` `opts.contract` is required. Creating without `opts` or without `contract` fails on the missing value; the error that names the problem (`no dataType contract named "<x>"`, saying to author the contract first) is the one for a contract name that isn't a registered `dataType`. Either way nothing is written. The seeded `values.yaml` fills every field the contract declares a default for, so a fresh instance is immediately valid wherever every required field has a default. ## Ref surface (`AssetRef<data>`) - `ref:contract()` — the bound `AssetRef<dataType>`. - `ref:satisfies(wanted)` — `(ok, reason?)`: whether this instance's contract chain includes `wanted` (the bound contract itself, or any contract it extends). `reason` is a string explaining a `false` result (unrelated contract, unresolvable binding, invalid values). - `ref:validate()` — `(ok, violations)` against the bound contract's merged schema. `violations` is an array of `{ path, message }`. - `ref:data(wanted?)` — the resolved, read-only value object: this instance's `values.yaml` with the bound contract's schema defaults filled in, `assetRef` / `dataRef` fields materialized (`assetRef` → `AssetRef`, `dataRef` → a nested value object resolved the same way), and the bound contract chain's `behavior.luau` methods reachable by field-style call — `v:someMethod()` alongside `v.someField`. Method resolution is **child-first**: the bound contract's own methods win over an inherited one of the same name, and either loses to an explicit instance value of that name (values always shadow methods). A contract with no `behavior.luau` simply contributes no methods — it still inherits its ancestors' via the chain. Pass `wanted` to assert the instance's bound contract satisfies that contract before resolving (same semantics as `:satisfies`) — it's an assertion of intent, not a filter: the returned object still carries the full bound schema and full method chain, not a view scoped to `wanted`. Raises when the instance's values violate its contract (same violations `:validate()` reports), when `wanted` doesn't appear in the bound contract's chain, and when `dataRef` fields form a circular chain (instance A referencing B referencing A). The object is read-only at the top level — assigning a field raises; change configuration by editing `values.yaml` instead. Nested plain tables (struct and array values) are private copies of the resolved snapshot: mutating them changes only your snapshot, never the source instance or any other caller's resolve. Generalized iteration (`for k, v in w do`) walks the resolved value fields (explicit values + filled defaults); methods are reachable by name but never appear in iteration. ```luau local w = smg:data() -- resolved value object print(w.damage, w.fireMode) -- schema values (with defaults) print(w:dps()) -- a behavior.luau method, if the contract ships one local weapon = smg:data("weapon") -- asserts smg's contract chain includes "weapon" ``` ## Discovery - `asset.list("data")` — every registered instance, as `AssetRef`s. - `<contractRef>:instances()` — every `.data` instance bound to that contract or to a contract that extends it (see `dataType`'s ref surface). - `asset.inspect("<name>")` — the instance's files, bound contract, values, and this type README. - `ls /zero/source/<Name>.data` lists the files the folder holds. ## Authoring conventions - Name instances for the specific thing they configure (`smg`, `rifle`), not for the contract they bind (that's `values.yaml::contract`). - Keep `values.yaml` limited to configuration; anything that changes during gameplay belongs on a component instead. - Say what this specific configuration is tuned for in the `description` of its `.metadata` — the contract's own README documents field meaning. ## Common pitfalls - **Missing or unknown contract at creation.** `opts.contract` must name an existing `dataType`; a missing `opts`, a missing `contract` and an unknown contract name each error before any file is written. - **Values drifting from the contract.** Editing `values.yaml` re-runs validation immediately; a violation warns rather than silently passing through. - **Confusing configuration with runtime state.** A `.data` instance never mutates during play — components own live state. ## Related types - `.dataType` — the contract this instance is bound to; owns structure, validation, and (optional) behavior. - `.preset` — a named set of values for one declarer's settings schema (an assetType, an importer, a component), not a contract of its own. ## In the Inspector Values: a link to the contract this instance is bound to, every contract field as a typed control (`data_schema`'s `toFields`), and the values that break the contract. An edit is checked against the contract and written through `dataRef:setValues`, one undoable step. `setValues` re-encodes values.yaml with `Yaml.encode`, so comments in the file are not kept; a values.yaml that carries comments is therefore shown read-only, with **Open** for the file. `dataRef:setValues(patch)` replaces the named top-level fields and checks the result against the contract. A change is refused (one error naming each violation, nothing written) when it introduces a violation or leaves one standing at or under a value it set. A list item is known by what it holds rather than where it sits, so removing or reordering items sets none of the rest. A violation the file already held anywhere else stays listed and does not stop the change, so an instance that does not yet satisfy its contract fills in one field at a time, and a value beside a key the contract does not declare stays editable. It writes values.yaml, recorded into the open undo operation when there is one. An Inspector edit writes only the leaves it changed: every other value keeps its stored value and form, including a colour held as numbers, a map-form vector, and keys the contract does not declare.
▲ 0↑ born
·
assettype · born here
❒asset
# mesh A mesh is renderable geometry — vertices and triangle indices, and, for a skinned mesh, the per-vertex skinning data that binds it to a skeleton. A component that draws geometry references a mesh, and the renderer binds the mesh's GPU resource for that entity. A static mesh draws at a continuous level of detail (cluster LOD), with no authored LOD meshes. A static mesh's triangles are split into clusters, a bake builds coarser levels of them into a hierarchy, and the GPU draws the coarsest clusters that still look the same at each one's distance, per view and per instanced copy. A mesh asset bakes its hierarchy when it materialises, at the depth its `clusterLod` setting (below) asks for; `renderer.mesh.clusters(mesh).kind` reads `dag` once it draws it. `guides { path = "topics/world-detail" }` covers cluster LOD and the meshes built from geometry. > New to how a mesh exists as an asset, as CPU-side vertex data, and as a live > GPU resource (and how `renderer.mesh.*` moves between them)? Read > `core/resource-model` first. Geometry is stored in `data.zmsh`; the GPU resource is keyed by the asset's guid. ## Create `asset.create("mesh", name, opts)` writes the geometry and registers the mesh. `opts` is raw geometry — flat arrays; `positions` and `indices` are required, `normals` and `uvs` optional: ```luau asset.create("mesh", "tri", { positions = { 0,0,0, 1,0,0, 0,1,0 }, -- [x,y,z, ...] (required) indices = { 0, 1, 2 }, -- [i0,i1,i2, ...] (required, 0-based) normals = { 0,0,1, 0,0,1, 0,0,1 }, -- [x,y,z, ...] (optional) uvs = { 0,0, 1,0, 0,1 }, -- [u,v, ...] (optional) }) ``` The full authorable geometry, all flat arrays unless noted: | Field | Shape | Notes | |---|---|---| | `positions` | `[x,y,z, ...]` | required | | `indices` | `[i0,i1,i2, ...]` | required; 0-based, counter-clockwise for the front face (see Conventions) | | `normals` | `[x,y,z, ...]` | optional; the surface's outward direction | | `uvs` | `[u,v, ...]` | texture UVs, optional; `(0,0)` is the image's top-left | | `colors` | `[r,g,b,a, ...]` | optional | | `tangents` | `[x,y,z,w, ...]` | optional (`w` = handedness) | | `uvs1` | `[u,v, ...]` | the lightmap UV set, optional | | `unwrapUvs` | boolean | generate `uvs1` when it is absent | | `skinning` | `{ joints, weights }` | per-vertex skin binding (four each per vertex) | | `skins` | array of skin tables | the skeleton (see `renderer.mesh.decode` for the shape) | | `morphTargets` | array of `{ name?, positions, normals? }` | the shapes the mesh blends towards, each a per-vertex displacement | `encode` / `decode` round-trip every one of these, so a **skinned** mesh can be built in engine, not only imported. Pass `unwrapUvs = true` to generate a lightmap UV set at creation time. ## Conventions Geometry is read against these whether it arrived through `asset.create`, `renderer.mesh.create`, or an importer. | Convention | How the engine reads the geometry | |---|---| | Index base | `indices` count vertices from **0** — index `0` is the first `positions` triple. The Luau array carrying them is 1-based like any other, so `indices[1]` is the first triangle's first index, and vertex `v` has its x at `positions[v * 3 + 1]`. | | Triangle winding | A triangle's **front** face is the one whose three vertices turn **counter-clockwise** as the viewer sees them. Put another way, `cross(v1 - v0, v2 - v0)` points out of the front face. | | Back faces | A material culls its back faces by default, so a triangle turned away from the camera draws nothing where it stands and whatever is behind it shows through. | | Normals | `normals` give the surface its outward direction and shade the face. Which side of a triangle draws comes from the index order alone, so a normal pointing away from the side the winding draws leaves that face standing and shades it as if the light were behind it. | | UVs | `(0, 0)` samples the first texel of an image — its top-left corner — and `v` grows downward through it. | | Axes | Model space carries the world's basis: `+X` right, `+Y` up, and `-Z` the direction an entity's `transform.forward` points. | Winding is what the author states: the inward faces of a room and a sky shell seen from inside are geometry meant to be wound the other way, and `asset.create` writes the index order it is handed. Two levers turn a face around: ```luau indices = { 0, 2, 1 } -- the same three vertices, reversed asset.create("material", "two_sided", { -- or keep the order and draw both sides shader = "@builtin::shaders.pbr", render = { cull = "none" }, }) ``` `cull = "front"` draws the far side by itself, which is what an inverted-hull outline is built on, and `"back"` is the default. `.shader` documents the whole `render` block a material's `mat.yaml` carries. A mesh states which way its own triangles face, so the question is answerable off the geometry — every triangle whose cross product agrees with the normal it carries is wound to draw the side that normal points at: ```luau local cpu = meshRef:load() local g = cpu:geometry() local function facesOutward(t: number): boolean -- t counts triangles from 0 local i = { g.indices[t * 3 + 1], g.indices[t * 3 + 2], g.indices[t * 3 + 3] } local function p(k: number, c: number): number return g.positions[i[k] * 3 + c] end local ax, ay, az = p(2,1) - p(1,1), p(2,2) - p(1,2), p(2,3) - p(1,3) local bx, by, bz = p(3,1) - p(1,1), p(3,2) - p(1,2), p(3,3) - p(1,3) local cx, cy, cz = ay*bz - az*by, az*bx - ax*bz, ax*by - ay*bx local n = i[1] * 3 return cx * g.normals[n+1] + cy * g.normals[n+2] + cz * g.normals[n+3] > 0 end local inward = 0 for t = 0, #g.indices // 3 - 1 do if not facesOutward(t) then inward += 1 end end cpu:unload() ``` ## Built-in primitive meshes The engine ships blockout geometry every world references by bare name (`{ model = "cube" }`). Each one is centred on its local origin, so an entity's `scale` reads directly as the size the mesh covers in the world: | Mesh | Extent (x, y, z) | Local AABB | |---|---|---| | `cube` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` | | `sphere` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` | | `cylinder` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` | | `cone` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` | | `octahedron` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` | | `rounded_box` | 1 x 1 x 1 | `-0.5, -0.5, -0.5` .. `0.5, 0.5, 0.5` | | `capsule` | 0.5 x 1 x 0.5 | `-0.25, -0.5, -0.25` .. `0.25, 0.5, 0.25` | | `torus` | 1 x 0.3 x 1 | `-0.5, -0.15, -0.5` .. `0.5, 0.15, 0.5` | | `plane` | 1 x 0 x 1 | `-0.5, 0, -0.5` .. `0.5, 0, 0.5` | | `ground_quad` | 1 x 0.1 x 1 | `-0.5, -0.05, -0.5` .. `0.5, 0.05, 0.5` | | `ground_hex` | 1.732 x 0.1 x 2 | `-0.866, -0.05, -1` .. `0.866, 0.05, 1` | | `shader_ball` | 0.933 x 1 x 0.933 | `-0.467, -0.5, -0.467` .. `0.467, 0.5, 0.467` | `plane` is a flat quad in the XZ plane, so it has no vertical extent at all and scaling it on Y moves nothing. `meshRef:load():getBounds()` reads the same numbers back off any mesh, built-in or authored. ## Put a mesh on an entity A component draws a mesh through a `resource("mesh")` field, which accepts the mesh **by name, by ref, or as a `MeshHandle`** — the component resolves whatever you give it. The builtin `Model` and `SkinnedModel` both expose a `model` field: ```luau entity.find("box").component.add("Model", { model = "tri" }) -- by name entity.find("box").component.add("Model", { model = asset.ref("tri") }) -- by ref entity.find("box").component.add("Model", { model = meshHandle }) -- a MeshHandle (below) ``` ## Runtime mesh — no asset Build geometry straight onto the GPU and render it without creating an asset. The `resource("mesh")` field takes the returned `MeshHandle` directly: ```luau local h = renderer.mesh.create({ positions = {0,0,0, 1,0,0, 0,1,0}, indices = {0,1,2} }) entity.find("box").component.add("Model", { model = h }) ``` Its geometry reads back off the handle. `renderer.mesh.geometry(mesh)` returns the same flat-array `MeshGeometry` `create` takes, carrying every stream the mesh has — so a runtime mesh can be inspected, edited, and rebuilt without ever becoming an asset: ```luau local geom = renderer.mesh.geometry(h) -- { positions, indices, tangents?, ... } geom.positions[1] = 0.5 local h2 = renderer.mesh.create(geom) ``` An optional stream is present only when the mesh carries one, so `geom.tangents` answers whether the mesh has a tangent basis and `geom.uvs1` whether it has a second UV set. ## Read geometry — `meshRef:load()` `:load()` decodes `data.zmsh` into the CPU store and returns a CPU handle carrying `vertexCount` / `indexCount`: | Method | Returns | |---|---| | `cpu:getVertices()` | array of `{ pos = {x,y,z}, normal = {x,y,z}, uv = {u,v} }`, one per vertex | | `cpu:getTriangles()` | array of `{ v1, v2, v3 }`, each a full vertex (the shape above) | | `cpu:getBounds()` | `{ min = {x,y,z}, max = {x,y,z} }` — the local-space AABB | | `cpu:geometry()` | the complete `MeshGeometry` — flat arrays, every stream the mesh carries | | `cpu:encode()` | the `data.zmsh` bytes | | `cpu:unload()` | drop this guid's CPU copy | ```luau local cpu = meshRef:load() local v = cpu:getVertices()[1] -- { pos = {x,y,z}, normal = {x,y,z}, uv = {u,v} } local aabb = cpu:getBounds() cpu:unload() ``` By default the CPU copy is transient (decode → read → `unload`). Set `keepCpu` to keep it resident — see Settings. ## Write geometry back — `meshRef.primary` The inverse of reading: encode a `MeshGeometry` and write it to the asset's primary content file. The assetType picks the write up and re-uploads the live GPU mesh, so the change shows without a reload: ```luau local geom = renderer.mesh.geometry(meshRef) geom.tangents = computeTangents(geom) -- add a stream it did not carry vfs.write(meshRef.primary, renderer.mesh.encode(geom), { overwrite = true }) ``` `meshRef.primary` is the asset's `data.zmsh` path. This is the route for a stream with no setting of its own; `keepCpu` + `meshRef:setVertices` moves positions in place, and `lightmapUvs` regenerates the second UV set (both below). ## GPU handle — `meshRef:handle()` `:handle()` uploads the geometry (Disk → CPU → GPU) and returns a `MeshHandle`, cached on the asset so every consumer shares ONE GPU entry. A component does this for you when you pass it the mesh; call it directly only for the runtime/low-level path. ## Settings — `meshRef:settings()` / `meshRef:setSettings(patch)` A mesh's settings are declared in `settings.luau` and live in `settings.yaml`. `:settings()` returns them with every declared default filled in. `:setSettings(patch)` writes any subset — sibling settings are preserved, and a patch that fails the schema is refused, naming the field and why. | Setting | Type | Default | Meaning | |---|---|---|---| | `keepCpu` | boolean | `false` | Keep the CPU geometry copy resident — for an in-use mesh — so geometry can be read repeatedly without re-loading. | | `lightmapUvs` | string | `"keep"` | The mesh's second (lightmap) UV set. `"keep"` leaves the stored geometry's set as-is; `"generate"` unwraps a fresh non-overlapping set; `"none"` strips it. See below. | | `clusterLod` | boolean | `true` | How deep the cluster set is built. Every static mesh draws through clusters, from the frame it materialises (its `lod0` set) until its bake lands. `true` (default) builds the LOD hierarchy; `false` builds one level, drawn at full detail. | ```luau local s = meshRef:settings() -- { keepCpu = false } meshRef:setSettings({ keepCpu = true }) ``` `keepCpu` is an active lifecycle control, and only ever holds geometry for a mesh that is **in use** (GPU-resident): - Setting it **on** while the mesh is in use loads the CPU copy immediately. - Setting it **on** for a mesh that is **not** in use loads nothing — the copy is retained the next time the mesh is materialised, so an unused mesh is never pinned in memory. - Setting it **off** drops a resident CPU copy (the renderer keeps drawing from the GPU). `clusterLod` is the same kind of lifecycle control, for the depth of the cluster set rather than the CPU copy: - Setting it **off** on a mesh in use rebakes it as one level of clusters (`single`), drawn at full detail. - Setting it **on** on a mesh in use rebakes the LOD hierarchy (`dag`). - A mesh that is not in use bakes at the depth the setting asks for when it next materialises. Acting on either setting for a mesh in use can read the mesh's stored geometry, and where the geometry is fetched on first read that read spans frames. `meshRef:settingsPending()` answers whether one is still in flight; once it answers `false`, every settings change made so far has reached the mesh. ### Second UV set (`lightmapUvs`) A mesh can carry a **second**, independent UV set (`uv1`) alongside its texture UVs (`uv`) — a distinct per-vertex channel, non-overlapping where the texture UVs tile and reuse charts. `lightmapUvs` controls whether the stored geometry keeps one, generates one, or drops it: | Value | Effect | |---|---| | `"keep"` | Leave the stored geometry's `uv1` as-is (the default). | | `"generate"` | Unwrap a fresh non-overlapping `uv1` (near-planar charts packed into `[0,1]` with gutters). | | `"none"` | Strip the `uv1` set. | ```luau meshRef:setSettings({ lightmapUvs = "generate" }) ``` Changing the setting reprocesses the asset's geometry in **edit** mode; a change in play mode never rewrites the source. The reprocess round-trips the geometry through the codec, so positions, normals, tangents, skinning, and the skeleton are preserved — only the `uv1` set changes. A runtime mesh carries `uv1` the same way: pass `uvs1` (or `unwrapUvs = true`) to `renderer.mesh.create`. ## Read vertices — `meshRef:getVertices()` With `keepCpu` on for an in-use mesh, read its vertices straight from the resident CPU copy: ```luau meshRef:setSettings({ keepCpu = true }) -- on an in-use mesh local verts = meshRef:getVertices() -- { { pos = {x,y,z}, normal = {x,y,z}, uv = {u,v} }, ... } ``` If the CPU copy isn't resident — `keepCpu` is off, or the mesh isn't in use — it errors loudly, naming the reason and the remedy, rather than silently loading a throwaway copy: ``` mesh:getVertices: cannot read vertices — keepCpu is off, so no CPU copy is kept. Turn on CPU retention for an in-use mesh first: meshRef:setSettings({ keepCpu = true }). ``` ## Morph targets — `meshRef:morphTargets()` A mesh can carry morph targets: shapes it blends towards, each a per-vertex displacement from the base geometry. Every target carries the name it was authored under, and an imported model keeps the one its source file gave its blend shapes, so content addresses a shape as the thing it means rather than as the ordinal it happened to import at. ```luau for i, name in meshRef:morphTargets() do print(i, name) end -- 1 Eyes_Blink ``` An entity blends them with `ecs.MorphWeights`, weight `i` driving target `i`. `renderer.mesh.morphWeights(mesh, { Eyes_Blink = 1 })` builds that ordered array from weights named by shape — shapes left out sit at 0, and an unknown name errors listing the ones the mesh carries. ## Discovery | Call | Shows | |---|---| | `asset.list("mesh")` | every registered mesh | | `asset.inspect("<name>")` | a text report about the mesh (metadata, source, status) | | `meshRef:settings()` | the resolved settings | | `meshRef:settingsPending()` | whether a settings change is still reading the stored geometry | | `meshRef:morphTargets()` | the shapes it blends towards, named, in target order | For the on-disk shape of a mesh asset, run `asset.inspect("<name>")` or read the type's `type.yaml` — those are the live source of truth. ## Related - `renderer.mesh.*` — the GPU/CPU resource layer (`create` a runtime GPU mesh, `encode`/`decode` the `ZMSH` payload, `readback` GPU → CPU). `:load`/`:handle` wrap it; see `man renderer`. - `.material` + `.shader` — what shades the geometry. - `.bundle` — container assets that carry `.mesh` interiors. ## In the Inspector Selecting a mesh opens its **Geometry** section, after the asset's identity and before its Settings. It reports what `data.zmsh` holds, decoded once per payload version: vertices, triangles, the bounds and their size, the vertex streams beyond positions (normals, uvs, uvs1, colors, tangents, skinning), and, when the mesh has them, its skin joints and morph targets. While the renderer holds the mesh's cluster hierarchy, the section also reports its cluster and level counts. A payload is one index stream, so the section names no submeshes. A mesh folder with no `data.zmsh` says so.
▲ 0↑ born
·
assettype · born here
❒asset
# Nodebox (asset type) A nodebox is a namespace folder that groups related `.procNode/` children, the way a toolbox groups `.tool/` children. A node's name is its folder name inside its box: `points.nodebox/disc.procNode` is called `points.disc`, and nothing inside the node states that name. Moving or renaming a node is a VFS move that keeps its guid. ## Where it lives - Source: `<anywhere>/<family>.nodebox/`, usually inside a `.package`, an effect or a world's content. - Identity: the folders above it and `<family>` (`fx.points` for `fx/points.nodebox`; the `.nodebox` suffix strips). A graph calls its nodes by `<family>.<node>` alone. - Folder shape (open child set): - `README.md`: what the family is for. Required. - `.metadata`: description and tags. Required. It also states where the box's nodes work: `context` (one of `proc.registry.contexts()`: `geometry`, `field`, `value`, `sim`, `raster`, `material`, `prefab`) and, when every node of the box reads the scene or assets beside its inputs or writes them beside its outputs, `pulls` / `pushes` (`scene` or `asset`). A node that works elsewhere states its own in its `.metadata`. `procgen` `describeNode` and the `context`, `pulls` and `pushes` filters of `searchNodes` read them. - `<node>.procNode/`: any number of nodes. ## How a graph reaches a node `g.<family>.<node>(args)` resolves the node by its asset identity: the box and the folder name together (`g.points.disc`), a path (`g["/zero/source/fx/ring.procNode"]`), `~` (the nearest enclosing package, effect or world root: `g["~/ring"]`) or a short name the asset system resolves (`g.disc`). A name that matches two nodes is an error naming both; a name that matches none is an error naming the closest nodes. Each call is recorded in the graph's reference table by the node's guid. ## How to create one ```luau asset.create("nodebox", "points", { folder = "fx" }) local box = asset.resolve("points.nodebox") asset.create("procNode", "disc", { into = box }) ``` ## Discovery - `asset.list("nodebox")`: every box. - `asset.inspect("points")`: the nodes in it and what each does. - `asset.list("procNode")`: every node, in or out of a box. ## In the Inspector Nodes: how many nodes the box holds, each node's full name and what it does, and a link to each.
▲ 0↑ born
▣
module · born here
❒asset
# entity_records Walks a live entity hierarchy into the flat record array the engine's entity templates use — `{ name, original_id, parent_id, position, rotation, scale, hidden, components }` per entity, root first, parents before children. `bundle` composes its `entity_template` through this module; scene builds compose their baked output through it. One record shape, one implementation. `compose(rootId)` walks one hierarchy. `composeMany(rootIds)` walks several, which is what a build needs — a builder may leave more than one unparented root. Temporary descendants are pruned; an explicitly-named temporary root is kept. `compose(rootId, nil, nil, true)` keeps the temporary descendants too, so the records hold every entity under the root.
▲ 0↑ born
❒
package · born here
❒asset
# edui The editor UI framework, on the CSS-parity `ui.*` surface. An editor-only toolkit: panels author closures instead of callback ids, a dock shell over `ui.*` native docking, and typed editor-chrome primitives. Gameplay and normal world UI author raw `ui.*` trees and need none of this. **`edui.guide` beside this file is how to use it** — creating a panel, the spec it returns, how a panel is drawn and redrawn, the whole widget vocabulary, and how a panel reaches the selection and the dock. ## What installs - **`framework`** — everything under one table. From outside the package, `require("@builtin::~edui.framework")`; inside it, `require("~.framework")`. It carries `app`, `widgets`, `shell`, `topbar`, `query`, `fileDialog`, `worldDialog`, `stats`, and the chrome primitives flat (`panel`, `tree`, `field`, `section`, `text`, `button`, `menu`, …). - **`app`** — maps a panel's closures to `ui.*` callback ids, dispatches to them, and coalesces redraws. - **`widgets`** — the primitives, plus the typed inspector layer (`widgets.tree`, `widgets.fields`, `widgets.controls`). - **`inspector`** — the Inspector as an ordered list of sections: the generic asset sections, the Settings section and its actions, and the merge with the sections a type's `inspector.luau` declares (`inspector.assetSections`, `inspector.settingsSection`), and the building blocks those sections compose (`inspector.parts`, reached as `ctx.parts`). - **`shell`** — the dock: one `ui.*` `dockArea` holding a `dockPanel` per registered panel, and the panel registry behind it. ## Referencing - Inside this package, modules reference siblings with `~.` — e.g. `require("~.app")`, `require("~.widgets.fields")`. - Editor content built on the framework references it by package identity — `require("~edui.framework")`, `require("~edui.shell")`.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_grey18 A lit 18% grey (middle grey) surface, rough and dielectric: what a light of known intensity is read off in the post-verification reference scenes.
▲ 0↑ born
·
assettype · born here
❒asset
# avatar A playable character, composed from three **independent** parts: - **body** (optional): a `.bundle` (a skinned `.mesh` + bone entities, a character imported from a GLB/FBX) or a plain `.mesh`. The look. An avatar with no body is a controller or first-person camera with no visible mesh. - **controller** — the movement system. Default: the standard humanoid kit (`CharacterController` + `MovementState` + `Humanoid`). - **animation** — the system that animates the body. Default: the shared `Locomotion` blend space (reads the controller's velocity, plays retargeted clips). Or `ClipPlayer`. Or your own component. Movement and animation are **not** tied together — attaching the controller never pulls in `Locomotion`, and choosing your own `animation` keeps the standard controller. Authoring your own locomotion is a one-field swap (`animation = ...`). Because the standard clip set retargets onto **any** humanoid rig, the default locomotion drives any humanoid body with no per-body setup and no editing of any built-in content. ## Make an imported character playable ```luau -- After importing a rigged humanoid GLB, the importer leaves a `.bundle` -- (skinned mesh + bones). Survey for it, then wrap it in an avatar: local body = asset.resolve("my_character", "bundle") local hero = asset.create("avatar", "my_hero", { body = body }) ``` To make `hero` the body every connecting player spawns with, point the scene's `PlayerPrototype.body` at a body entity whose `Asset` source is `hero` (authored in the scene tree — see `man scene`). To drive the **local** player with it right now, instantiate it and bind the entity: ```luau local root = hero:instantiate() -- spawns the body + movement kit layers.active.players.localPlayer.avatar = root -- bind the live body ``` Only the avatar bound as the local player's body answers the player's controls. Every other avatar you instantiate (an NPC, a mannequin, a preview) stands where it is until something drives it: with the standard controller, write its `CharacterController` input bus (`inputX` / `inputZ` / `inputJump`) from a component of your own, the way an AI brain does (`man CharacterController`). ```luau local npc = hero:instantiate() -- stands still npc.component.get("CharacterController").inputZ = -2 -- walks while this is written each frame ``` An avatar is **not** humanoid-only. The body can be anything — a humanoid, a vehicle, an unrigged plane with a custom controller and shader. The defaults adapt to the body: a **humanoid** body defaults to the shared humanoid Locomotion (the `synty` clip preset); a **non-humanoid / unrigged** body gets **no auto-animation** (you supply your own `controller` and `animation`). This is the non-humanoid detection — an arbitrary animated model is never auto-driven by humanoid locomotion — and it never blocks creating the avatar. ```luau -- Non-humanoid avatar (e.g. a custom-controlled body), fully generic: asset.create("avatar", "ship", { body = shipBundle, controller = { system = "ShipController" }, animation = false }) ``` ## A VRM is an avatar A `.vrm` (VRM 1.0 or 0.x) written into the world imports as `<name>.bundle` and an avatar `<name>.avatar` beside it (`modules.vrm`). Its `avatar.json` carries the VRM's `expressions` (each preset's `binds` and override rules), a face (`parameters`, `animator`, `menu`: blinking, the emotions the Expressions menu sets, the mouth from `Viseme`), the `secondaryMotion` the `SpringBones` component swings on the body (springs, colliders, constraints), `firstPerson`, `lookAt` (whose offset is the descriptor's `viewpoint`) and `licence`. Its rig keeps the VRM's humanoid map as the roles set by hand, and its MToon materials draw with `@builtin::shaders.mtoon` and a `ToonOutline`. ```luau local me = asset.resolve("me", "avatar") print(me:licence().name, table.concat(me:licence().authors, ", ")) print(me:permits("wear").ok, me:permits("redistribute").reason) ``` ## Options `asset.create("avatar", name, opts)`: | opt | meaning | |-----|---------| | `body` (optional) | the body `.bundle` or `.mesh` ref; omit for a body-less avatar | | `controller` | movement: `true`/nil = standard kit, `false` = none, or a component name / `{ system, data }` | | `animation` | a component name or `{ system, ... }` — **author your own locomotion here**; defaults to Locomotion | | `locomotion` | clip preset for the default Locomotion (default `"synty"`) | | `clip` | a single `.animation` ref — selects a one-clip `ClipPlayer` | | `looping` / `speed` / `sourceRig` | `ClipPlayer` tuning (with `clip`) | | `expressions` | the blend shape each standard expression preset plays, where the body's shapes are not named after the presets: `{ aa = "Mouth_A", blink = { shape = "Eyes_Closed", overrideMouth = "block" } }` | | `parameters` / `animator` / `menu` / `parts` | the avatar's parameters, its animator, its expression menu and its own parts seated on its body (below) | | `type` | the avatar type its body is mapped onto (an `avatarType` ref or identity); the builtin humanoid when omitted | | `secondaryMotion` | the body's spring chains, colliders and bone constraints by bone name (the `SpringBones` component) | | `licence` | the avatar's licence and credits in the VRM 1.0 meta's fields; `:licence()` reads it, `:permits(use)` answers from it | | `firstPerson` / `lookAt` | which meshes a first-person view draws, and where the eyes are and how they look | Author your own locomotion (keeps the standard movement): ```luau asset.create("avatar", "my_hero", { body = body, animation = { system = "MyLocomotion" } }) ``` `avatar.json`: ```json { "body": { "__ref": "<bundle guid>" }, "controller": true, "animation": { "system": "Locomotion", "preset": "synty" } } ``` A composed body faces the avatar's -Z, the forward every entity states, whatever way its file authored it. The composition measures the way the body faces from its skeleton (the hip line crossed with up, carried through the nodes that stand it upright, so a Z-up Blender or Khronos skeleton is measured as it is drawn) and stands the bundle under the body entity's child `front`, turned so that front is the body entity's -Z. So `transform.forward`, `entity:lookAt`, a `PlayerSpawn`'s heading and `capture`'s local `front` all name the way the character visibly faces, and Locomotion turns the body entity to lead its walk with that front. No per-avatar facing knob. ``` avatar root (placed, turned by lookAt / a spawn) body (Locomotion turns this one about up) front (turns the bundle so its front is -Z) <bundle nodes> ``` ## Use ```luau local root = avatarRef:instantiate() -- spawn body + movement kit avatarRef:setCharacter(root, asset.resolve("knight", "bundle")) -- swap the body, keep the behaviour ``` `:instantiate()` spawns the body and attaches the movement system bound to it. `:setCharacter(root, body)` despawns the current body and spawns a new one in its place; the Locomotion kit on the avatar root re-resolves the new body's rig, so the look swaps while the behaviour is kept. Items seated with `Humanoid:attach` are kept: each moves to the new body's socket for the same point, with the transform it was seated with. An item whose point the new body lacks stays on the avatar root and is seated by the next swap to a body that has it. The new body takes the old body's id and is composed with the options the avatar was instantiated with, and the avatar's `Asset` id map names it. ## The avatar standard A humanoid avatar is built around one standard (the `avatarStandard` module): the VRM 1.0 bones, 19 attachment points, the viewpoint, the face expressions and a height band. A game relies on it to seat its own items on any visitor's body (`Humanoid:attach("rightGrip", sword.id)`) and to read where the eyes are. ```luau local d = avatarRef:descriptor() -- bones, points, viewpoint, expressions, height print(d.height, d.points.hat.position.y, d.viewpoint.source) local v = avatarRef:validate() -- { ok, problems } for _, p in v.problems do print(p.rule, p.name, p.message) end ``` `:validate()` names every rule the body breaks, one problem per missing item: a required bone (`rightHand`), an attachment point the body cannot carry (`rightGrip`), a face expression no blend shape answers (`aa`), a height outside the band, or a body that is not a humanoid at all. A game holds bodies to the rules it relies on: `avatarRef:validate({ rules = { "type", "bone", "point", "height" } })` leaves out the face expressions. A live avatar answers the same through its `Humanoid` (`:descriptor()`, `:validate(opts)`). ## Parameters, an animator and an expression menu An avatar declares its own state as data: `parameters` (named bools, ints and floats, synced or local, saved or not, the synced ones 256 bits in all), an `animator` (layers of state machines over the parameters, whose states pose blend shapes and bones, show and hide parts, set shader data and play `.animation` clips on the body under the layer's mask, a wave on the right arm or a dance over the locomotion), a `menu` (buttons, toggles, sub-menus, radial and two-axis puppets) the person uses from the app menu's **Expressions** tab, and `parts` (meshes seated on its body's attachment points on every peer). No script is involved, and every peer draws the same avatar from the parameters it receives. ```luau local hero = asset.create("avatar", "my_hero", { body = body, parts = { { name = "Hat", mesh = "@builtin::meshes.cone", point = "hat", scale = 0.25 } }, parameters = { { name = "Hat", type = "bool", default = true, saved = true } }, animator = { layers = { { name = "Hat", states = { { name = "On" }, { name = "Off", motion = { hide = { "Hat" } } } }, transitions = { { from = "On", to = "Off", when = "!Hat", duration = 0 }, { from = "Off", to = "On", when = "Hat", duration = 0 } }, } } }, menu = { { type = "toggle", label = "Hat", parameter = "Hat" } }, }) local check = hero:animator() -- { ok, problems, summary, syncedBits, cost } ``` `hide = { "Hat" }` names the part the avatar declares; any entity under the avatar is named the same way, and an attachment point's name (`hat`) names every item seated there. An avatar whose synced parameters pass 256 bits is refused when it is created, with the overrun stated. The `avatarAnimator` module's README has the whole data form, and the `AvatarAnimator` component runs it. ## In the Inspector Selecting an avatar opens its **Avatar** section, read from `avatar.json`: its label when it has one, how it moves (`controller`: the standard mover, none, or the system it names), what animates it, and whether it is humanoid. It links the body the avatar wears, or says the avatar spawns no visible body, and offers to open `avatar.json` in the Code panel. ## The body's skeleton `avatarRef:rig()` is the `.rig` of the body's skinned mesh (nil for a body-less avatar or a plain mesh), and `avatarRef:avatarType()` the avatar type its body is mapped onto. The `avatar` toolbox reads and corrects that mapping (`avatar.inspect`, `avatar.map`), and makes, dresses and saves avatars; `guides { path: "core/avatars" }` walks through it.
▲ 0↑ born
◐
material · born here
❒asset
# Parallax Cube (Flat) A brick surface built on `@builtin::shaders.pbr_parallax_occlusion` with `parallax_depth_scale = 0`, so the ray-march is bypassed and the shared brick textures render as plain textured PBR (rough `0.7`, non-metallic, white base colour). Opaque, back-face culled, queue `2000`. Pair it with `parallax_cube` to A/B the parallax effect from a fixed viewpoint. ## Inputs - `floats.parallax_depth_scale` (`0.0`) — disables the occlusion ray-march, flattening the surface. - `floats.roughness` (`0.7`) — matte brick finish. - `floats.normal_scale` (`1.0`) — strength of the normal map. - `textures.height_texture` — the brick height map (unused while depth scale is `0`).
▲ 0↑ born
·
assettype · born here
❒asset
# avatarType An avatar type describes a kind of body: a humanoid, a quadruped, a vehicle. It names the roles and chains a rig of that kind maps onto, and it finds them in a skeleton. The builtin library ships one, `@builtin::avatarTypes.humanoid`. A world adds its own the same way, as a `<name>.avatarType/` folder. A rig can be mapped for more than one type; its author's corrections are stored on the rig, keyed by the type's guid, so mapping a skeleton for one type never overwrites another. ## The module `init.luau` returns: | Field | What it is | |---|---| | `name` | The type's name, e.g. `"humanoid"`. | | `vocabulary.roles` | Every role the type can assign (`hips`, `lefthand`, ...). | | `vocabulary.chains` | Every chain the type can assign (`spine`, `leftArm`, ...). | | `vocabulary.required` | The roles and chains a rig must have for the type to claim it. | | `qualify(structure)` | Maps a skeleton. `structure` comes from `modules.rigStructure`. | `qualify` returns: ```luau { qualifies = true, -- the rig is this kind of body confidence = 0.94, -- 0..1 reason = nil, -- one line, when qualifies is false mapping = { roles = { hips = "Hips", ... }, -- role -> bone name chains = { leftArm = { "Clavicle_L", ... } }, secondary = { { root = "Hair_01", tip = nil, class = "hair", bones = { ... } } }, }, report = { chains = { leftArm = { confidence = 0.97, bones = { ... } } }, missing = { "rightArm" }, ambiguities = { { role = "hips", candidates = { { bone = "Hips", score = 0.9 } } } }, contradictions = { "..." }, stale = { { role = "leftforearm", bone = "Elbow_L" } }, verdict = "humanoid: every required chain found", rolesMapped = 52, -- how many roles the mapping fills reasonCode = nil, -- when qualifies is false: the code of the reason reasonValues = nil, -- the values that reason is written from }, } ``` ## Using one ```luau local humanoid = asset.resolve("@builtin::avatarTypes.humanoid", "avatarType") local rig = asset.resolve("PolygonSyntyCharacter", "rig") local q = rig:qualify(humanoid) -- the rig's effective mapping for this type print(q.qualifies, q.mapping.roles.hips) ```
▲ 0↑ born
◐
material · born here
❒asset
# postReference_siemensStar A Siemens star of 36 spokes, 0.9 on 0.02: the spokes narrow below a pixel toward the centre, where a temporal resolve aliases. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
◐
material · born here
❒asset
# Skybox An unlit cubemap skybox rendered from the inside of the mesh, built on `@builtin::shaders.cubemap_unlit`. Uses front-face culling and no depth write so it draws behind all scene geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` environment. ## Inputs - `textures.base_color_texture` — the cubemap sampled as the background (`Ryfjallet_cubemap`). - `floats.reflect_mode` (`0.0`) — samples the cube directly as a background rather than as a reflection. - `colors.base_color` (`1.0, 1.0, 1.0`) — tint applied to the sampled cubemap.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_greyWedge The grey wedge: one column per whole stop from -10 to +10, each middle grey (0.18) at that exposure. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Checkerboard White A static white/grey checkerboard rendered by `@builtin::shaders.checkerboard`, alternating a white base colour (`1.0, 1.0, 1.0`) with a dark grey check colour (`0.3, 0.3, 0.3`). Animation is disabled (`animation_speed 0.0`), giving a fixed, neutral grid — ideal as a level-design blockout or scale-reference floor. Opaque, non-metallic (`metallic 0.0`) at mid roughness (`0.5`). ## Inputs - `colors.base_color` — the white square colour. - `colors.check_color` — the dark grey square colour. - `floats.animation_speed` (`0.0`) — held at zero for a static pattern. - `floats.roughness` (`0.5`) — diffuse spread on the squares.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_white A flat unlit white of 0.8 light: the thin geometry of the temporal reference scene (wires, a fence, a fan's blades) drawn against the dark, so every pixel it touches stands out from its neighbours. Drawn by `@builtin::shaders.referenceChart`. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# parallax_cube Brick wall material using `@builtin::shaders.pbr_parallax_occlusion` with the parallax march enabled (`parallax_depth_scale = 0.08`, 48 ray-march layers). Pair with `parallax_cube_flat` for a same-textures, no-POM A/B comparison. ## Shader `@builtin::shaders.pbr_parallax_occlusion` — see that shader's README for the full parameter list. ## Textures All from `@builtin::textures.parallax_bricks` (height/normal derived from three.js's MIT-licensed `brick_bump` + `brick_diffuse`): - `base_color_texture` → `bricks_albedo` - `normal_texture` → `bricks_normal` - `roughness_metallic_texture` → `bricks_roughness` - `occlusion_texture` → `bricks_ao` - `height_texture` → `bricks_height` ## Usage ```luau Material.Apply(entityId, "parallax_cube") -- Override at runtime: Material.SetProperty("parallax_cube", "parallax_depth_scale", 0.12) ``` Pair it with `parallax_cube_flat` (same textures, `parallax_depth_scale = 0`) to compare the ray-marched surface against a flat-mapped baseline. ## Notes - `Material.SetProperty` mutations are global — every entity using `parallax_cube` sees the change. If you need per-entity variation, derive a new material name and override the property there. - Use under any standard camera (forward path). The deferred path is not yet POM-aware; materials applied to a deferred camera will render as plain textured PBR.
▲ 0↑ born
·
assettype · born here
❒asset
# workflow A job whose shape is a program. Some jobs are one thing an agent does. Others have a shape: a decision, then several pieces built at once because they do not touch each other, then somebody looking at the result and saying whether it holds. Written as instructions, that shape becomes a list an agent has to carry in its head, and by the last step the first is gone. Written as a workflow, the shape is code — it runs in the engine, it decides its own phases and branches and fan-out, and nothing that answers it is told what comes next. ## The shape on disk <name>.workflow/ workflow.js the program — the primary file, and where all the decisions live workflow.yaml what it is, when to reach for it, the phases it moves through README.md .metadata ## The program `workflow.js` is JavaScript, run in the engine. Six things are given to it: phase(name) name the stage the run is in log(text) say something as it goes agent(prompt, opts) ask for one agent's whole job; parks until answered parallel(thunks) several asks that do not depend on each other pipeline(items, ...) each item through every stage, independently args whatever the run was started with `agent()` is the only call that leaves the engine. It parks the run, puts the request where whoever holds credentials can see it, and resumes with the answer. Everything else — the loop that built those prompts, the branch on what came back, the decision to fan out — is the program's, and stays in the engine. `opts.schema` states the shape the answer must have: 'string' 'number' 'boolean' 'any' a value of that type 'string[]' or [ shape ] a list, every item of that shape { field: shape, 'note?': shape } a table with those fields; a name ending in ? may be left out `workflow.next` hands the schema over with the prompt. `workflow.answer` refuses a value of any other shape, naming the field and the shape expected there, and the request stays open to be answered again. `workflow.correct` replaces an answer the program has not read yet, held to the same schema; the program reads an answer within a moment of it arriving, and a correction after that is refused as already consumed. Every list the schema names reaches the program as an array, an empty one included. A schema written outside this notation fails the run at the `agent()` call that carries it. ## Running one local run = asset.resolve("<name>", "workflow"):start({ ... }) or through the `workflow` toolbox, which is what an agent uses: `workflow.start`, then `workflow.next` / `workflow.answer` until it is finished. Each request a run asks is announced on tool responses once, when it can be taken, and once more if a claim on it runs out; `workflow.status` lists every request still waiting. From the engine shell, the same run is driven with `zero workflow`: zero workflow start --name [name] zero workflow status zero workflow next --runner <who you are> (claim the request it is waiting on) zero workflow renew --request <id> (keep the claim while its work goes on) zero workflow answer --request <id> --value <result> zero workflow fail --request <id> --reason "<why>" `next` names who is taking the request, and `answer`, `renew` and `fail` name the request they act on by the id `next` returned. ## What a run is A run lives in the engine, not in a session. Whoever started it can close the tab, lose the connection or hand over to somebody else; the run stays parked exactly where it was, and the next agent to ask gets the request that was waiting. Each request is one subagent's whole job — the point is that no single context has to hold the entire run. ## In the Inspector Workflow: what the workflow is for and when to reach for it, the args it takes, its phases, its step budget when it declares one, and the size of workflow.js, with **Open** for workflow.yaml and workflow.js. Nothing here runs it.
▲ 0↑ born
·
assettype · born here
❒asset
# renderFeature A **render feature** inserts custom GPU passes into the frame pipeline. The engine provides one generic capability — a per-frame render-pass queue and a set of pipeline-phase insertion points — and a feature is the authored Luau that decides what passes to enqueue, and where, every frame. ## Authoring contract A `.renderFeature` folder holds an `init.luau` that returns a feature module: ```luau return { setup = function(ctx) -- optional; runs once when the feature goes live -- A "fragment" pass's `shader` names a POST EFFECT, not a `.shader` -- guid directly — postprocess.add compiles the shader asset under -- that name once, here. Enqueueing a name never passed to -- postprocess.add runs the pass as a no-op every frame (the log -- reads "effect '<name>' not compiled — pass skipped"). postprocess.add("my_effect", asset.resolve("my.shader.guid", "shader"), { enabled = false }) end, render = function(ctx) -- required; runs every frame -- enqueue one or more passes. The spec shape depends on `kind` (see -- "Pass kinds" below): this is a "fragment" pass (full-screen shader over -- input textures); a mesh effect (outline, x-ray) is a "geometry" pass -- with `material` + `select` (see "Geometry passes"). ctx.enqueue { phase = "afterTransparent", shader = "my_effect", inputs = { src = "@scene.color" }, output = myRenderTargetGuid, } end, teardown = function(ctx) end, -- optional; runs once when the feature is destroyed } ``` Optional `materials/` and `shaders/` subfolders hold shader source the feature constructs GPU programs from. A feature constructs its GPU programs (it does not reference `.material` surface assets). ## `ctx` Built fresh each frame and passed to `setup` / `render` / `teardown`: | Field | Meaning | |-------|---------| | `ctx.enqueue(spec)` | Queue one render pass for the current frame. | | `ctx.viewport` | `{ w, h }`: the size the **main viewport's** scene rasterized at, in pixels (`renderer.rasterSize()`: the viewport taken down by the render scale). | | `ctx.time` | The instant this frame's per-frame fields are drawn at, in seconds: the running clock, or the instant a `renderer.temporal.hold` pins. | | `ctx.frame` | The frame index beside that instant: it counts every frame of the loop, drawn or not, and reads 0 while a hold stands. | | `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. | | `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". | | `ctx.authored` | The same knobs as authored: a setting declared with `Field.scaled` reads its authored value here and the value of the quality level in force in `ctx.settings`; every other setting reads the same in both. | ### Per-frame values and a still picture A buffer a feature's passes read is part of the picture: written with new words between two frames, it is a change of the picture, and a renderer draws for as long as such changes arrive. A field that animates with time (film grain, a moving noise) seeds from `ctx.time` and draws while the clock runs. The jitter an accumulation averages over (a ray offset, a rotated sample pattern) turns with the renders of the view instead, so the feature's parameters hold the same words on every frame of a still scene and the renderer stops drawing once the accumulation settles: a history target's `state` buffer (`renderer.texture.create { history = true }`) carries in `y` how many renders in a row the view being drawn has carried, written as each render of the view begins, and a pass that binds it reads its jitter frame there. While `renderer.temporal.held()`, the feature writes a frame taken from `ctx.time` into its parameters and the passes read that one, so two renders under one hold agree. `@builtin::systems.reflections.ssr` works this way. ## Settings A feature declares the knobs it takes as `settings`, each a Field descriptor with a default, the way a component declares its public fields. A feature that declares no `settings` has nothing to tune: its schema is empty, and applying it turns it on or off. ```luau local Fields = require("@builtin::modules.field") local Field, NoSync = Fields.Field, Fields.NoSync return { settings = { intensity = Field.number(1.0, NoSync, "How much of the effect reaches the image."), quality = Field.enum({ "low", "high" }, "high", NoSync, "How many samples the pass spends."), }, render = function(ctx) local s = ctx.settings -- { intensity = 1.0, quality = "high" }, or what a caller set ... end, } ``` The engine holds one settings table per live feature — every declared default, overridden by what it was handed — and passes it as `ctx.settings` on every `setup` / `render` / `teardown`. A feature reads its knobs there and nowhere else, so any caller tunes any feature by name: ```luau local h = renderer.feature.create(ref, { settings = { intensity = 0.5 } }) renderer.feature.configure(h, { quality = "low" }) -- lays over the rest renderer.feature.settings(h) -- { intensity = 0.5, quality = "low" } renderer.feature.find(ref) -- the live handle, or nil renderer.feature.schema(ref) -- the declared knobs, unrun ``` A knob the feature does not declare, or a value of the wrong shape, is refused by name. A scene authors its features on one `RenderFeatures` entity — a list of features, each with its settings — which adopts a feature already live rather than stacking a second, and takes every one down on disable and destroy. Each entry is an application of its asset (`applicable`): the asset holds its one live feature, every application joins it, the settings in force are those of the application that last stated something new, and the last to leave stops it. A feature already running when the first application comes is adopted, and runs on with its own settings once the last leaves. A feature stopped from outside the asset (`renderer.feature.destroy`, a `render` that raised) stays stopped until an application is stated again. `render` runs **once per frame**; the passes it enqueues run **once per render target** drawn that frame — the live viewport, every offscreen capture, every RTT camera — each at its own resolution. So `ctx.viewport` is the main viewport's size, not the size of the target a pass ends up drawing into. Size a full-screen scratch RT with `screen = true` and let the engine track the drawn target (see "Screen-sized targets") rather than deriving it from `ctx.viewport`. ## Screen-sized targets `renderer.texture.create { screen = true }` marks a feature RT as full-screen: before each render target's feature passes, the engine resizes it to that target's resolution. Create it once — the engine owns its size from then on: ```luau myRt = renderer.texture.create { width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only screen = true, format = "rgba16f", name = "my_effect", } ``` A target that holds a picture of the scene is `rgba16f`, which is what the scene target itself carries: linear light with headroom above the display's white and no 256-step floor under a dark gradient. Omitting `format` on a screen-sized target asks for the same thing. `format = "rgba8"` is for a mask, a weight or an occlusion term, where 0..1 is the whole range — hand one of those back over `@scene.color` and the frame loses every highlight and bands every gradient, and the engine says so in the log. `screenScale` (default `1.0`) takes a fraction of the drawn target's resolution, for a scratch that runs below composite resolution (a half-res blur passes `0.5`). A screen-sized RT is what makes a full-screen effect composite correctly at any resolution. Deriving the size from `ctx.viewport` instead pins the RT to the main viewport, and every differently-sized render target then composites a mismatched scratch — the scene scaled into a corner with the rest black. `screenSpace` names WHICH image a screen-sized RT follows: | value | what it tracks | |---|---| | `"scene"` (default) | the scene render target, at whatever resolution the render scale asked for. Resized before EVERY render target's feature phases — the main frame and each offscreen one — and cleared to transparent before an offscreen render, so one sink never reads what another left behind | | `"composite"` | the image the post-scene phases draw into. The presented frame's allocation is resized and drawn by the presented frame alone; an offscreen render that runs a post-scene phase (a capture, a render-to-texture camera whose picture goes through the `display` stage) draws in an allocation of its own at its own size, cleared to transparent before it draws | The two carry the same size until the render scale drops below 1. From there, while the renderer presents the viewport itself, the scene reaches the display's resolution through an upscale that runs before `afterScenePost` — so a composite-space RT is the display's size while a scene-space one is the smaller rasterized frame. Under a UI viewport panel the panel draws the scene target at its own rect, nothing upscales beforehand, and both spaces carry the scene's size. A scene-space target is scratch: whatever a pass does not rewrite this render is transparent black. The presented frame's allocation of a composite-space target survives every offscreen render untouched. ## History targets An accumulation across frames (temporal antialiasing, a temporal denoiser, any pass that reads what it wrote last time) lives in a history target: ```luau history = renderer.texture.create { width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only history = true, format = "rgba16f", name = "my_accum", } -- in render(ctx): ctx.enqueue { kind = "compute", program = myResolve, inputs = { scene_color = "@scene.color", accum_previous = history.previous.guid }, buffers = { accum_state = history.state }, storage = { accum_out = history.guid }, phase = "afterLighting", } ``` The passes a feature enqueues run once for every view the frame draws (the viewport, each render-to-texture camera, each capture), so an accumulation has to be one per view. A history target keeps one pair of images per view, sized to that view: for the length of a view's render `history.guid` names the image the render writes and `history.previous.guid` the image the same view's previous render wrote. Another view never resizes, clears or overwrites them, and a view's images are freed when it stops drawing. It follows `screenSpace` and `screenScale` like any screen-sized target; a composite-space one is kept for every view that runs the post-scene phases: the viewport, a capture, and a render-to-texture camera whose picture goes through the `display` stage. Before each render of a view the engine writes `history.state`, one `vec4<f32>` a pass binds through `buffers`: | field | holds | |---|---| | `x` | 1 when `previous` holds this view's previous image; 0 on the view's first render, its first after a camera cut or a change of size, or after a render of the view that ran without the target, and `previous` then reads transparent black | | `y` | how many renders in a row have carried the history | | `zw` | this render's sub-pixel projection offset, in pixels (`renderer.setProjectionJitter`) | `renderer.setProjectionJitter` is the matching per-view sample sequence: every view walks it by its own count of renders, so the sequence a temporal pass expects is the one each view's renders sampled. ## Post stages A post effect belongs to one of the frame's named **post stages**, in frame order, each stating what the picture holds there: the space an effect there reads and writes (`light`, the scene's own light ahead of the display transform's exposure and tone curve, `display`, code values, or `encoded`, the presented surface's own values) and the size the picture is held at (`raster`, the size the scene rasterized; `output`, the size the frame is composed and shown at): | Stage | Space | Resolution | Runs | |-------|-------|------------|------| | `lighting` | light | raster | screen-space lighting terms and what draws into the lit scene: occlusion, reflections, indirect light, contact shadows, decals, splats, outlines, diagnostic views. It spans every phase up to `afterLighting`, so a pass of a feature declaring it may name one of those phases | | `medium` | light | raster | participating media: aerial perspective, fog, volumetric light | | `preTemporal` | light | raster | effects reading the jittered raster before reconstruction: depth of field | | `temporal` | light | raster | the one temporal reconstruction of the raster (TAA); the stage holds one feature at a time | | `postTemporal` | light | raster | effects reading the reconstructed picture: motion blur | | `meter` | light | reduced | measuring the picture: the exposure histogram, a fraction of the raster | | `optics` | light | raster, then output | lens light: bloom, flare, streaks. Its render features run on the raster; the frame then carries the picture to the output size, and the post-process chain's `scene` layer runs there | | `display` | display | output | the display transform, then on code values the temporal upscale, debanding, edge antialiasing and sharpening; the chain's `display` layer, the film grain last | | `ui` | display | output | the UI, drawn over the finished picture, then what grades the picture with the UI on it: `afterUI` passes, the chain's `all` layer, then `afterPost` passes | | `output` | encoded | output | the renderer's output stage alone: the one write of the presented surface, in the surface's encoding, rounded to its bit depth with a blue-noise dither (`renderer.output`). It takes no render feature and no chain effect | A feature declares the stage it belongs to, and each pass it enqueues with no `phase` runs in that stage, at the stage's phase and its band of orders plus the pass's own local `order` (a whole number from 0 to 99): ```luau return { stage = "postTemporal", render = function(ctx) ctx.enqueue { kind = "fragment", shader = "my_effect", inputs = { src = "@scene.color" }, order = 0 } end, } ``` Passes sharing an order run in the order they were enqueued, so a chain of passes over shared targets can run at one order, in sequence. The `meter` and `optics` stages are the camera's film. A pass placed in one of them, stating neither `postProcessing` nor `presented`, is part of the camera's post-process chain (`postProcessing = true`): a camera running no post-processing, such as a capture asking for the scene ungraded or an environment cube face, skips it. A pass stating `postProcessing = false` runs on every camera. `render` runs once a frame, but each view the frame draws (the viewport, a capture, a render-to-texture camera, an environment cube face) looks at the world from its own camera, so an order that depends on where the camera stands is stated per pass rather than chosen in `render`. A pass that composites something standing in the world states the world point it stands at as `sortPoint`: `{ x = .., y = .., z = .. }`, `{ x, y, z }` or a `vector`, so an entity's `position` is one. Among the passes of one phase sharing one `order` that run together (its fragment, compute and raster passes; its geometry passes, which run ahead of those), the ones stating a point trade the places they were enqueued in so that every view runs the one farthest from its own camera first and the nearest last: composites laid over the frame by each of them leave the nearest in front from wherever the view looks. Depth is taken along the view (the distance in front of a perspective camera, the depth into an orthographic one's box). Passes at the same depth keep the order they were enqueued in, so the passes of one effect stating one point (a march into a target and the composite reading it) stay together, and a pass stating no point keeps its place: ```luau for _, item in ipairs(items) do ctx.enqueue { kind = "compute", program = march, storage = { out = scratch.guid }, order = 2, sortPoint = item.center } ctx.enqueue { kind = "fragment", shader = composite, inputs = { src = scratch.guid }, blend = true, order = 2, sortPoint = item.center } end ``` A draw or splat pass takes no `sortPoint`, and a value that is not three finite numbers is refused by `ctx.enqueue`. A pass may name a `stage` of its own in place of the feature's, placed the same way: a feature whose work spans two stages declares one and names the other on those passes, the way temporal antialiasing declares `temporal` for its resolve and names `display` on its sharpening passes. A pass naming both a `stage` and a `phase` is refused. A stage the frame does not have is refused by `renderer.feature.create`, naming the stages there are, and a second feature declaring the `temporal` stage while one stands in it is refused naming both; the `temporal` stage takes the passes of the feature declaring it alone. A pass that names a `phase` runs at that phase and `order`, as below. `renderer.post.stages()` reports every stage and what stands in it: a feature by the stage its passes' position falls in, marked `declared` where that is the stage the feature declares or a pass names. Every built-in render feature declares its stage; `postStages`'s README lists where each built-in effect runs. ## Pass phases `enqueue` runs a pass at a named pipeline boundary — a real seam between the scene's discrete passes — ordered within a phase by `order`. Each phase is the point where the scene colour holds a specific, nameable state: | Phase | Scene colour there | |-------|--------------------| | `afterDepthPrepass` | the visibility raster written: `@scene.depth` holds this frame's complete opaque depth, and `@scene.motion` its opaque motion, before anything shades. Scene colour is not yet drawn; `@scene.colorHistory` holds the previous frame's lit colour, and the deferred g-buffer the previous frame's surfaces (`readsPrevious`) | | `afterShadows` | shadow maps populated; scene colour not yet drawn. `@scene.depth` and `@scene.motion` hold what the visibility raster laid at `afterDepthPrepass` | | `afterSky` | sky only. `@scene.depth` holds the frame's opaque depth, so a pass here tells the pixels the geometry pass draws over (depth above 0) from the ones that stay sky (depth 0) | | `afterOpaque` | opaque drawn, before transparents. `@scene.depth` (and the deferred G-buffer) are populated. Forward: lit opaque. Deferred: lit opaque too, which the geometry pass shades straight into the scene colour, on a render no pass reads or writes `@scene.shaded` in; on one that does, the opaque surfaces are in the G-buffer's shaded channel, so the colour is still sky only until the composite (use `afterOpaqueLit`). Radiance stamped into `@scene.emissive` reaches the colour at the composite | | `afterOpaqueLit` | the lit opaque scene, still before transparents, on **both** paths — the forward opaque draw, or the deferred geometry pass and composite. The background a refractive or transmissive surface samples: the one phase whose colour holds what is behind such a surface without holding the surface itself | | `afterTransparent` | transparents drawn, before the OIT composite | | `afterLighting` | deferred-lighting + OIT composite done — fully lit, final geometry on **both** paths | | `afterScenePost` | the chain's `scene` layer and the display transform done: display code values, before the chain's `display` layer and the UI | | `afterUI` | scene + UI composited | | `afterPost` | the chain's `all` layer done — the finished picture in display code values, before the output stage writes it to the surface. A pass here reads that picture as `@scene.color` and draws over a copy of it | The last three are the post-scene phases, and they work on the COMPOSITED image: `@scene.color` there is the target the UI lands on, not the scene render target. `@scene.depth` and `@scene.motion` still bind — they are the scene's own buffers for the frame just drawn, which is what lets a pass at these phases reproject the composite it is handed — and on the deferred path so do the G-buffer channels (`@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive`), the surfaces of that same frame, so a look drawn over the finished picture reads what each pixel's surface is without copying the G-buffer at an earlier phase. All of them keep the SCENE's resolution. Whenever the render scale is below 1 on the presented frame, that is smaller than `@scene.color`, so a pass here maps between the two by uv rather than by texel index, and takes its own output size from the target it writes. **A texture is a texture.** A pass's sampled input names any texture the engine holds by the handle that made it: a render target or a texture `renderer.texture.create` returned (its guid), or a storage texture a compute shader created (`ref:createStorageTexture2D`, its `key`). Which one it is decides nothing about whether the pass accepts it. A pass sees the contents a texture holds when the pass runs: a compute shader that wrote the texture in an earlier pass of the same frame, or in a `dispatchEx` recorded at the start of the frame, is read by a pass at any later point of the frame, and a pass that reads a target an earlier phase of the frame draws sees that draw once the phase has run. The `@scene.*` inputs (`@scene.color`, `@scene.depth`, …) bind the live frame buffers; the deferred g-buffer channels (`@scene.normal`, `@scene.shaded`, …) resolve only on the deferred path. Before the pass that shades has drawn — at `afterDepthPrepass` — a g-buffer channel holds the previous frame's surfaces, and a pass reading it there names the slot in `readsPrevious` (`readsPrevious = { "scene_normal" }`); one that does not is held back rather than handed a stale normal. `@scene.colorHistory` is the lit colour the target's previous render ended with, kept by the engine per render target and never cleared by a frame: what a pass tracing at `afterDepthPrepass`, against this frame's depth, takes its light from — reprojected through the previous view-projection `@frame.camera` carries. A capture drawn once, or a camera drawn again after a pause, is drawn lit first when a pass reads the history, so its first frame holds one. Every `@scene.*` channel, what it holds, its format, the phase it is first valid from, and the other names it answers to: | Name | Holds | Format | Valid from | Also named | |---|---|---|---|---| | `@scene.color` | the scene's lit colour; the display composite at a post-scene phase | the scene target's format at a scene phase, the display composite's at a post one | every phase | — | | `@scene.depth` | opaque depth, reversed (1.0 near, 0.0 far/empty sky) | `Depth32Float` — binds through a `texture_depth` compute slot, not `texture2d` | `afterDepthPrepass` on | — | | `@scene.motion` | screen-space NDC velocity since the previous frame | `Rg16Float` | `afterOpaque` on | — | | `@scene.normal` | world-space normal + the per-pixel surface-flag field | `Rgb10a2Unorm` | deferred path, `afterOpaque` through `afterPost` (previous frame's before — declare `readsPrevious`) | — | | `@scene.shaded` | what a surface SENT — its shaded colour, linear and scene-referred | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.albedo` | | `@scene.material` | what a surface IS — base colour (RGB565) + metallic + perceptual roughness | `Rgba8Uint` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.mr` | | `@scene.emissive` | radiance a pass stamped on the surface, added at the composite | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | — | | `@scene.ao` | scene occlusion a feature wrote, read back by shading: occlusion in r, the bent normal laid flat on the octahedron in g and b, and in a whether a bent normal was written | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — | | `@scene.sunOcclusion` | the share of the sun's direct light a feature found taken on the way to each pixel's surface (`.rgb`, 0 none to 1 all), read back by the sun's term alone | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — | | `@scene.reflection` | traced reflection radiance (`.rgb`) + confidence (`.a`) | `Rgba16Float` | every scene phase (cleared at the top of the scene render) | — | | `@scene.indirect` | the indirect diffuse light the surfaces closing each pixel's hemisphere send it (`.rgb`, in the ambient term's units) + the share of the closed hemisphere it answers for (`.a`), read back by the diffuse term through `zero_scene_indirect_here`; the second layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | every scene phase (cleared at the top of every scene render) | — | | `@scene.decal` | the base colour stamped over each pixel's opaque surface, premultiplied by its coverage (`.rgb`), with that coverage (`.a`); written at `afterDepthPrepass` (blend `premultiplied`), and every opaque surface takes it into its own base colour before it is lit (`zero_take_scene_decal`, which `zero_pbr_shade` calls), so the stamp is lit, shadowed and written to `@scene.material` with the surface; the third layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | `afterDepthPrepass` through `afterSky` (cleared at the top of every scene render and again once the opaque surfaces have shaded, so a surface drawn after them takes none) | — | | `@scene.colorHistory` | the lit colour the target's previous render ended with | `Rgba16Float` | every phase | — | | `@scene.lights` | the punctual-light storage buffer: 1024 light entries of eleven vec4s each (the light, then its projection, which names the shadow record it casts through), the light grid, then the virtual shadow map's region: a shadow record per casting light and their page tables. A loop runs over the first `@frame.camera[4].w` entries, the lights in use; the buffer's length counts the regions after the lights too, so `arrayLength` does not size a light loop | storage buffer | every phase | — | | `@scene.shadowPool` | the depth pool every shadow-casting light renders its shadow pages into, read beside `@scene.lights` through `@builtin::shaderModules.light_shadows` (`zero_light_shadow`): the shadow a point, spot or area light casts at any world point, the one the surfaces take. A frame with a pass reading it keeps the coarsest page of every map of each casting light whose reach meets the view | `Depth24Plus` — binds through a `texture_depth` compute slot | scene phases only | — | | `@scene.sunShadow` | the sun's virtual shadow map as the view being drawn reads it: its basis, depth range, clipmap levels and window origins and where its page table starts in `@scene.lights`, read beside `@scene.lights` and `@scene.shadowPool` through `zero::sun_shadow` (`zero_sun_visibility`): how much of the sun reaches any world point, past the occluders that shadow the surfaces. A frame with a pass reading it keeps the sun's pages under the air the view looks through | storage buffer (`ZeroVsmUniform`, a `kind: buffer` slot with `array: false`) | scene phases only | — | | `@scene.environment` | the reflection-probe cube array | texture cube array | scene phases only | — | | `@scene.environmentSampler` | the filtering sampler for `@scene.environment` | sampler | scene phases only | — | | `@scene.reflectionProbes` | the environment buffer: the probe blend data naming which probe reaches a point, then the irradiance light-probe volumes | storage buffer | scene phases only | — | The rendering and ray-tracing guides (`guides { path = "topics/rendering" }`, `guides { path = "topics/raytracing" }`) point here rather than repeating this table. **What a full-frame pass reads, at each stage, on each path.** A full-frame pass is a fragment or compute pass of a render feature, or an effect of the post-process chain (`postprocess.add`). The G-buffer channels above are what the deferred path knows about each pixel's surface, and they are the four the paths differ on: | Channel | Deferred path | Forward path | |---|---|---| | `@scene.color`, `@scene.depth`, `@scene.motion` | every stage (depth and motion from `afterDepthPrepass` and `afterOpaque` on, as the table states) | the same | | `@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive` | `afterOpaque` through `afterPost`: the `lighting`, `medium`, `preTemporal`, `temporal`, `postTemporal`, `meter`, `optics`, `display` and `ui` stages, and every layer of the chain. Before `afterOpaque` a pass naming one in `inputs` reads the previous frame's surfaces (`readsPrevious`), and the surface helpers read their stated substitute with `zero_scene_surfaces_drawn()` false | none: the forward path draws no G-buffer. A pass naming one as an input is skipped, and the log names the channel and the reason. A shader reading one through the surface helpers reads its stated substitute (zero) and `zero_scene_surfaces_drawn()` reads false, so it draws a picture of its own there | Two readers reach them. A pass names a channel in `inputs` (or a compute binding), as above. A fragment pass's shader, or a chain effect's, reads them by screen uv through the post framework's surface helpers (`zero_scene_normal`, `zero_scene_material`, `zero_scene_shaded`, `zero_scene_emissive`; the shader type README's post-process section has the table), which spend none of the pass's input slots. Either way a render keeps a channel only when something reads it: a queued pass naming it, a queued fragment pass whose shader calls its helper, or a running chain effect that does. The channels are at the scene's resolution, so a pass after an upscale reads them by uv. A pass before the `temporal` stage reads each channel as the raster drew it, with this render's sub-pixel offset. With temporal antialiasing running (`@builtin::systems.antiAliasing.temporalAntiAliasing`), a reader after the `temporal` stage reads `@scene.depth`, `@scene.normal` and `@scene.material` restated at each pixel's centre, with no sub-pixel offset, so under a still camera they hold still the way the resolved picture does: the restatements run on a frame where a pass after them names the channel or a shader reads it through its helper, and a chain effect reading the helpers is such a reader. `@scene.shaded` and `@scene.emissive` keep the raster's sub-pixel offset at every stage. `ctx.renderPath` names the path a feature's `render(ctx)` runs on, and `postprocess.status()` lists, for each effect, the channels it `reads` and, after a frame it drew with their substitute, the `substituteReason`. **Two g-buffer channels describe the surface, and they answer different questions.** `@scene.shaded` is what a surface SENT — the colour the geometry pass shaded it to, linear and scene-referred, so a surface lit above the display's peak reads above 1 there. `@scene.material` is what the surface IS: the base colour it reflects, its metallic and its perceptual roughness, each in [0, 1] and each independent of how brightly the surface happens to be lit. A pass that multiplies incoming light by a reflectance — a bounce multiplier, a Fresnel tint, an ambient floor — reads `@scene.material`; a pass that filters the picture reads `@scene.shaded`. `@scene.material` is an `Rgba8Uint` channel packing all three into 32 bits, so its slot declares `sample: uint` and the module unpacks it: ```yaml # bindings.yaml - { name: scene_material, kind: texture2d, sample: uint } ``` ```wgsl #include "@builtin::shaderModules.gbuffer_material" let m = zero_gbuffer_material(scene_material, coord); let bounce = incoming * m.base_color; ``` `@scene.albedo` is another name for `@scene.shaded` (the SHADED lit colour) and `@scene.mr` for `@scene.material` (the material channel). The engine logs the substitution once per name, naming the canonical one to write. `@scene.motion` carries screen-space velocity: the NDC displacement each pixel's surface underwent since the previous frame, so a still surface under a still camera reads `(0, 0)`. Opaque geometry contributes it on both render paths: the visibility raster writes it for every surface it records, and an opaque surface whose depth state the raster cannot express writes its own where it draws. A moving entity, a moving camera and an animated pose all reach it in the viewport; transparents, particles and sky carry none. A surface a material's `vertex()` hook displaces carries the displacement's own velocity. A render target's own camera and a capture keep no view history, so velocity there is the entity's motion with no camera term. `@frame.camera` is a reserved **buffer** input carrying the camera CURRENTLY being drawn: 14×`vec4<f32>` = the inverse view-projection (columns `[0..4)`, column-major) + camera world position (`[4].xyz`, with the number of lights `@scene.lights` holds in `[4].w`) + the previous render's view-projection (columns `[5..9)`), which projects a point into the picture that render left + the view-projection itself (columns `[9..13)`), which projects a world point onto the view being drawn and is the matrix the scene rasterized with + the sub-pixel offset that matrix carries (`[13].xy`, in NDC; zero without a temporal upscale). A compute pass declares a `buffer` binding and binds it via `inputs = { name = "@frame.camera" }`, then reconstructs a pixel's world position from `@scene.depth`: ```wgsl let inv_vp = mat4x4<f32>(cam[0], cam[1], cam[2], cam[3]); // ndc.z is the `@scene.depth` sample itself. Scene depth is reversed — 1.0 is // the near plane, 0.0 the far plane and empty sky — and this matrix inverts // that same range, so a sample goes in unmodified. let wh = inv_vp * vec4<f32>(ndc, 1.0); let world_pos = wh.xyz / wh.w; ``` Like `@scene.*`, the engine resolves it **per render target** — so the same pass reconstructs against the live viewport's camera on screen and against an offscreen capture's / RTT camera off screen. (Pack a camera matrix into your own buffer instead and the offscreen render reconstructs against the wrong camera.) > Render-feature passes run in the main viewport render **and** in offscreen > captures / render-to-texture, each against its own camera. The `capture` tool's > `source = "position"` / `"entity"` therefore run the pass queue too; using > `@frame.camera` is what keeps those captures matching the live viewport. ### The scene's light `@frame.light` is a reserved **buffer** input carrying the scene's sun and ambient term as the camera being drawn is shaded by them, the values the lit passes read in the same frame: 3×`vec4<f32>` = the direction the sun's light travels (unit, world space) with its intensity in `w`, the sun's colour with `w` 1 while it casts shadows, and the ambient colour with its intensity in `w`. A pass that lights a participating medium (clouds, haze, fog) reads its sun here rather than carrying one of its own, so a day cycle, a scripted sun and a sun switched off reach the medium in the frame they reach the surfaces, and a scene with the sun and every light at zero leaves it black. `#include "@builtin::shaderModules.frame_light"` reads it, and states the sun's light either in the units the scene's lights are stated in (`zero_frame_light_sun_irradiance`), for a medium that scatters those lights too, or as the share of a medium's authored brightness the sun lights (its intensity up to a unit sun, `zero_frame_light_sun_tint`): ```yaml # bindings.yaml - { name: scene_light, kind: buffer, access: read, element: vec4<f32> } ``` ```wgsl #include "@builtin::shaderModules.frame_light" let light = zero_frame_light(scene_light[0], scene_light[1], scene_light[2]); let toward_sun = zero_frame_light_toward_sun(light); let sun = zero_frame_light_sun_tint(light) * authored_brightness; ``` ```luau inputs = { scene_light = "@frame.light" } ``` ### The environment A compute pass reads the scene's captured surroundings — the reflection-probe cube array, its sampler and the environment buffer (the probe blend data, then the irradiance light-probe volumes) — through three reserved inputs, bound to bindings of the shapes group(0) binds them in: ```yaml bindings: - { name: environment_map, kind: textureCubeArray } - { name: environment_sampler, kind: sampler } - { name: zero_environment, kind: buffer, access: read, element: ZeroEnvironment, array: false } ``` ```luau inputs = { environment_map = "@scene.environment", environment_sampler = "@scene.environmentSampler", zero_environment = "@scene.reflectionProbes", } ``` Named like that, `#include "zero::environment"` in the shader resolves the environment at a world point along a direction — `zpbr_sample_environment(world_pos, dir, lod)`, the probes whose radius reaches the point blended by rank and proximity, each through its proxy volume, and the sky under them — exactly as a material's environment term does, so a reflection a pass draws and one a material draws agree about the room they are in. A pass that reads several directions at one point selects the probes once, `let probes = zpbr_select_probes(world_pos);`, and gathers each direction with `zpbr_gather_environment_with_probes(probes, world_pos, dir, lod)`, which answers the radiance in `rgb` and the share of it the probes and sky claimed in `a`. The three bind at the scene phases; a post or UI phase carries none. A `textureCubeArray` binding takes `@scene.environment` alone, and a fragment pass has no slot of that shape. ## Pass kinds `enqueue` runs one of six kinds (the `kind` field; default `"fragment"`): - **`"fragment"`** — a full-screen shader over input textures. The program is a GPU **material** (or `shader`) the feature constructed; `inputs` bind live textures (`@scene.*` or RT guids), `output` is the target RT (omit = the phase's default scene target). Post-process, blur, edge effects. **Writing named G-buffer channels (`outputs`).** Instead of the single `output` RT, a fragment pass may declare an `outputs` array — one or more targets, each a named engine channel (`@scene.shaded` / `@scene.normal` / `@scene.emissive` / `@scene.color`) or an RT guid — each with its own blend mode: ```luau ctx.enqueue { kind = "fragment", shader = myShaderKey, outputs = { { target = "@scene.shaded", blend = "under" }, -- premultiplied dst-over-src { target = "@scene.emissive", blend = "additive" }, -- one fullscreen pass, two targets (MRT) }, phase = "afterOpaque", -- deferred: G-buffer filled, before the composite } ``` Blend modes — the keywords every pass's `blend` takes, `src` being what the pass returns and `dst` what the target holds: | Keyword | Result | |---|---| | `"replace"` | `src` — overwrites | | `"alpha"` | `src.rgb * src.a + dst.rgb * (1 - src.a)` — straight-alpha source-over | | `"premultiplied"` | `src + dst * (1 - src.a)` — source-over for a colour already multiplied by its alpha | | `"additive"` | `src + dst` — sums | | `"under"` | `src * (1 - dst.a) + dst` — premultiplied destination-over-source: what the target holds stays in front, which accumulates coverage-weighted contributions | A keyword outside the table raises from `ctx.enqueue`, naming the field. A `@scene.*` channel resolves only where it exists (the deferred G-buffer at a pre-composite phase); a pass whose targets are all unavailable at its phase is skipped (logged). `output` + `blend = true` remains the shorthand for a single alpha-blended target. The shader's returned colour is written to every target in the set. A fragment shader returns `vec4<f32>`, so the channels it can target are the float ones. `@scene.material` (also named `@scene.mr`) is `Rgba8Uint`, which binds as `uint` — naming it as an output is refused by name, with the channel's format and class in the log, and the rest of the frame draws. A fragment pass's `inputs` reads through the same fixed float slot, so naming `@scene.material` there is refused the same way; a compute pass reads that channel through a `sample: uint` slot instead. **What a pass with no `inputs` samples.** A fragment pass that declares no `inputs` reads `@scene.color` — the shape of an effect that filters the scene image. A pass that names `@scene.color` among its own `outputs` samples a 1x1 transparent texel instead, because the scene colour is that pass's render target and one texture is a colour attachment or a sampled resource in a render pass, never both. Declare `inputs = { src = "@scene.color" }` and write an RT to read the scene image and write somewhere else in one pass. - **`"compute"`** — a workgroup dispatch (`shader`, `storage`, `buffers`, `dispatch`; see "Compute passes"). - **`"geometry"`** — draw scene geometry with a constructed pipeline. The program is a **material** the feature built (`renderer.material.create`); the engine draws the scene's render-objects with that material's pipeline + uniforms. - **`"draw"`** — rasterize the feature's OWN geometry: `geometry` names a buffer created with `usage = { "vertex" }`, `storage.index` one created with `usage = { "index" }`, and `select` the one entity whose transform and material the draw lands through. `params[0]` is how many indices to submit — or name a buffer under `storage.indirect` (created with `usage = { "indirect" }`, holding a `DrawIndexedIndirectArgs` block: index count, instance count, first index, base vertex, first instance) and the count comes from the GPU instead, so a compute pass that compacts geometry pays only for what it kept and nothing waits on a read-back. `first_instance` must be 0; the engine resolves the entity's per-instance data another way, because a non-zero one needs a device feature WebGPU does not guarantee. - **`"splat"`** — rasterize a compute buffer of particle records as instanced camera-facing billboards into feature RTs (see "Splat passes"). - **`"raster"`** — draw geometry the feature makes itself with a `.rasterShader` of its own: `vertexCount` vertices for each of `instanceCount` instances, pulled from the buffers the pass binds, into the scene or the feature's targets, depth-tested against the scene (see "Raster passes"). ### Geometry passes A geometry pass re-draws the scene's meshes with a material you supply — the generic primitive for mesh-space effects (the engine names none of them): ```luau ctx.enqueue { kind = "geometry", material = myMaterial, -- the HANDLE renderer.material.create -- returned (or its registry-key string) geometry = "@geometry.opaque", -- which drawables: "@geometry.opaque" | -- "@geometry.transparent" | "@geometry.all" select = { entityA, entityC }, -- OPTIONAL: restrict to these entities -- (entity refs); omit = every matching mesh phase = "afterLighting", -- afterLighting = lit scene + valid depth } ``` `select` restricts the draw to the given entities — the per-instance signal that turns a whole-scene pass into a chosen-meshes effect. A pass with no `select` also draws the instanced populations (`renderer.mesh.drawInstanced`) its `geometry` set takes, every copy at its own slot, so a whole-scene pass sees an instanced forest as it sees the entities around it. The **material** decides how those meshes are drawn; you control three things: - **Pipeline render-state.** `renderer.material.create` takes a `render` block — `cull` (`back`/`front`/`none`), `depthWrite` (bool), `blend` (`opaque`/`alpha`/`additive`) — so the pass can rasterize differently from the surface pass: ```luau local myMaterial = renderer.material.create({ shader = myShaderKey, -- a .shader you authored (identity, not guid) render = { cull = "none", depthWrite = false }, properties = { outline_color = { 1, 0.4, 0, 1 } }, -- seed the shader's uniforms }, "my_pass_mat") -- pass `myMaterial` (or "my_pass_mat") as the pass `material` ``` - **The shader.** A geometry `.shader` is a surface shader: author `fn vertex(v: VertexData) -> VertexData` to move vertices (object-local `v.position` / `v.normal`) and `fn fragment(input: FragmentData) -> vec4<f32>` for the colour. - **Its properties.** A shader reads ONLY the uniforms IT declares in `properties.yaml`, via `material.<yourProp>`. Referencing a field it didn't declare (e.g. a StandardMaterial `material.base_color`) fails to compile and the mesh renders **magenta** — declare the property or use a constant. What effect those three produce (outline, x-ray, wireframe, highlight, …) is yours to design — the engine just draws the selected geometry with your pipeline. #### What a pass starts its target from (`load`) A geometry or draw pass with no `output` draws over the phase's own scene target, which holds the frame as it stands. A pass naming an `output` render target begins by setting that target's colour and depth to a starting state, and `load` says which: | `load` | the target starts as | |---|---| | `"clear"` (default) | empty: transparent colour and the far depth, so the target holds only what this pass draws | | `"keep"` | what it holds: colour and depth as the last pass to draw into it left them, so this pass draws over that, depth-tested against it | Two geometry passes naming one `output` therefore leave only the second one's draw by default, since the second pass starts from an empty target. State `keep` on the second to draw both, the way one camera draws many entities into one target: ```luau ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid, select = groupA, phase = "afterLighting", order = 0 } -- starts from empty ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid, select = groupB, phase = "afterLighting", order = 1, load = "keep" } -- draws over groupA's ``` `keep` loads what the target holds when the pass begins: the draws of the passes before it this frame, and the previous frame's picture where none drew it first (and where a screen-sized target is made again, an empty one). The first pass to draw a target each frame says `"clear"` so the target starts the frame empty; an accumulation across frames is the one that says `"keep"` there too. `load` is refused, naming the field, on a pass that is not a geometry or draw pass or that has no `output`. A splat pass loads its targets with `blend = true`, and a raster pass clears them with `clear = true`. **How much of each mesh it draws.** A pass drawing into a small map (a top-down cover or height map, a coarse occlusion mask) holds none of the detail finer than a texel, and two fields keep it from paying for that detail: - `detail = 1.0` states the world-space size of the finest detail its target holds. Each static mesh then draws at the coarsest cut of its cluster hierarchy whose error, placed at the object's scale, stays within that size, the cut the scene's own draw takes for a distant object: a building keeps its walls and roof and a tree its crown, in far fewer triangles than their full detail. A mesh drawing from its own vertex streams (a skinned or morphing mesh, one with no cluster set yet) and an instanced population draw in full. - `rigid = true` leaves out every mesh a skeleton poses or morph targets blend, so a crowd of characters costs the pass nothing. `renderer.feature.drawn()` reads what each geometry pass drew on the last drawn frame, as `{ objects, triangles }` keyed by its material, so the difference either makes is a number. ### Compute passes A compute pass dispatches a `.computeShader` program over a workgroup grid: ```luau ctx.enqueue { kind = "compute", program = myComputeShader, storage = { outTex = myStorageRtGuid }, -- slot -> storage-texture RT guid buffers = { particles = "my_particle_buf" },-- slot -> named compute buffer inputs = { camera = "@frame.camera" }, -- slot -> @frame.*/@scene.* buffer dispatch = { x = 64, y = 1, z = 1 }, } ``` **`dispatch` is optional.** Omit it and the pass is dispatched over what it WRITES: a grid covering its first `storage` texture, at the `@workgroup_size` the shader's entry point declares. With a screen-sized storage target that grid tracks the render target being drawn, so a screen-space effect covers the live viewport, an offscreen capture and an RTT camera without the feature knowing any of their resolutions: ```luau ctx.enqueue { kind = "compute", program = myComputeShader, inputs = { scene_color = "@scene.color", cam = "@frame.camera" }, storage = { outTex = myScreenSizedRt.guid }, -- screen = true phase = "afterLighting", } ``` State an explicit `dispatch` for a grid that is not one thread per output texel (a reduction, a particle sim), or when the shader's `@workgroup_size` is an override/const expression the engine cannot read. Each WGSL storage-buffer binding in the shader resolves its bound slot in this order: an explicit `buffers` mapping (the handle a buffer's owner holds, or a name), then `inputs` (`@frame.camera` / `@frame.light` / `@scene.lights` / `@scene.reflectionProbes`), then — when a slot has neither — a buffer whose engine-side name equals the slot's own name. `buffers` is the seam a pass binds through: the buffers a shader works over are the ones handed to it, whatever each is called. `storage` binds storage TEXTURES (RT guids) the same way, one map per resource kind. **A table built from a few settings.** A compute pass whose targets follow from inputs that rarely change (a lookup table, a baked noise volume) states the version of those inputs as `version`, a string or a number. The pass runs in a view only while some render target it writes holds no picture this program recorded at this version, so the table is built in the first view after the version moves and skipped in every later view and frame: ```luau ctx.enqueue { kind = "compute", program = bakeLut, buffers = { settings = settingsBuf }, storage = { lut_out = lutRt.guid }, phase = "afterSky", version = string.format("%.17g,%.17g", density, falloff), } ``` A pass reading the table later in the frame reads the picture it holds. The table is built again when the version changes, when the pass's own `params`, `dispatch`, `buffers` or `storage` change, when the program's pipeline is rebuilt (an edit to its source), when a render target it reads through its `inputs` holds a new picture (so a table built from another table is built again whenever that one is, and one built from a camera's target or a video target whenever that target draws), when another texture it reads there holds new texels, when a pass of any other version or none writes the target, when the target is reallocated or cleared, and when the device reports an error after the build was recorded. What the build reads from a buffer's contents or from a value its program holds (`ref:setParam`) belongs in the version. A pass reading a texture a GPU producer outside the texture cache writes, a 3D texture, or the scene's acceleration structure and hit tables is built in every view. **A table built from the view being drawn.** A table that follows the camera too (a sky seen from the camera's altitude) binds `@frame.camera`, and names what its program reads of the view in `viewReads`: `"@frame.camera.position"` (the camera's world position, `@frame.camera[4].xyz`) and `"@frame.light"` (the whole light buffer). The engine names the build by those values as each view holds them, so the table is built in a view drawn from where it was not built and stands in every view and frame drawn from where it was. `render` runs once a frame and states what follows from the frame alone in `version`; the engine adds what each view holds: ```luau ctx.enqueue { kind = "compute", program = skyTable, inputs = { cam = "@frame.camera", lut = transmittanceRt.guid }, buffers = { settings = settingsBuf }, storage = { sky_out = skyRt.guid }, phase = "afterSky", version = string.format("%.17g,%.17g,%.17g", sun.x, sun.y, sun.z), viewReads = { "@frame.camera.position" }, -- built again when the camera moves } ``` Every view of a frame shares the target, so a capture or a render-to-texture camera standing elsewhere builds the table for its own camera, and the next view drawn from the viewport builds it again for the viewport's. The program reads nothing else of the camera buffer: its orientation, its projection and a temporal upscale's sub-pixel offset move from frame to frame and name no build. A geometry pass drawing a map of the scene into a render target of its own (`output`) takes a `version` too. Its build is its material (the shader's install, the row it draws with: its property values, textures, render state and the buffers it binds, and the picture each render target it samples holds), its version, its `geometry`, `select`, `detail` and `rigid`, the render layers of the camera drawing it, and the meshes its selection takes as they stand: each one's mesh, geometry, world transform and node pose (or the place a substrate binding gives it on the device), the cluster sets the meshes draw, and each instanced population's transforms. So a map of a scene where nothing moved is drawn once, a mesh that moved, arrived, left or changed draws it again in the next view, and an edit to some other material leaves it standing. A selection taking a mesh a skeleton poses or morph targets blend draws in every view (`rigid = true` leaves those out), and so does a material whose properties follow each object's named values. The material makes the same picture from every view the build stands for: it places what it draws without the camera's view (a map seen from above, placed by a `vertex_clip` hook), and reads the camera being drawn only through `viewStep`: its position rounded to whole steps of that size (`floor(position / step + 0.5)`), and the build stands for every view whose camera stands in the same step. What else it reads that changes (the frame clock, the sun, a texture's texels) belongs in the version. A power of two rounds alike in Luau, the engine and WGSL (multiply by its reciprocal there): ```luau ctx.enqueue { kind = "geometry", material = coverMaterial, geometry = "@geometry.opaque", output = coverMap.guid, phase = "afterLighting", rigid = true, detail = 1, -- the meshes nothing deforms, at 1-unit detail version = 1, viewStep = 32, -- drawn again when a mesh moves or the camera steps } ``` A pass of any other kind stating a `version` is refused when it is enqueued, and so is a geometry pass drawing into the frame, a `viewStep` without a `version` or on another kind, `viewReads` without a `version`, on another kind or naming a buffer no input binds, and a versioned compute pass binding what each view draws for itself: an `@scene.*` input, an `@scene.*` storage target, or a `@frame.*` input its `viewReads` names nothing of. ### Raster passes A raster pass draws geometry the feature makes itself: a `.rasterShader`'s `vs_main` runs `vertexCount` times for each of `instanceCount` instances, and pulls whatever it places from the buffers the pass binds. No mesh and no vertex buffer stand behind it — the shape of an instanced field of grass, kelp, leaves or debris, one record per instance. This one draws a field of leaves from a storage buffer, hidden behind the scene's opaque geometry: ```luau local leafShader = asset.resolve("leaves", "rasterShader") local leaves -- a buffer of vec4 records, one per leaf: xyz position, w size return { setup = function(ctx) leaves = substrate.createBuffer({ name = "leaf_field", type = "vec4", len = 256, kind = "gpu" }) local records = {} for i = 0, 255 do local x, z = (i % 16) - 7.5, (i // 16) - 7.5 table.insert(records, x); table.insert(records, 0); table.insert(records, z); table.insert(records, 0.6) end leaves:write(records) end, render = function(ctx) ctx.enqueue { kind = "raster", shader = leafShader, phase = "afterLighting", vertexCount = 4, -- one quad per leaf instanceCount = 256, -- one leaf per record topology = "triangle-strip", cull = "none", buffers = { quads = leaves }, -- slot -> buffer, as a compute pass binds them inputs = { cam = "@frame.camera" }, -- the drawn camera, for vs_main depth = { target = "@scene.depth", test = true, write = true, compare = "less" }, } end, } ``` The fields a raster pass reads: | Field | Default | Holds | |---|---|---| | `shader` | — (required) | the `.rasterShader` (its reference or guid) whose `vs_main` and `fs_main` the pass draws with | | `vertexCount` | — (required without `indirect`) | vertices per instance, `@builtin(vertex_index)` 0 .. n-1 | | `instanceCount` | `1` | instances, `@builtin(instance_index)` 0 .. n-1 | | `indirect` | none | a buffer created with `usage = { "indirect" }` holding vertex count, instance count, first vertex and first instance as four `u32`; the counts then come from the GPU, so a compute pass that culls or spawns instances draws exactly what it kept | | `topology` | `"triangle-list"` | `"triangle-list"` or `"triangle-strip"` | | `cull` | `"none"` | `"none"`, `"back"` or `"front"`; a triangle wound counter-clockwise on screen faces the camera, as in WebGPU | | `depth` | none | `{ target, test, write, compare }`, `true` for `{ target = "@scene.depth", test = true, write = true, compare = "less" }`, or `false` for no depth buffer | | `outputs` / `output` / `blend` | `@scene.color`, replaced | where `fs_main`'s colours land and how they blend: `@scene.color`, `@scene.motion` or render targets the feature created, each `"replace"`, `"alpha"`, `"premultiplied"`, `"additive"` or `"under"` (the blend table under "Pass kinds") | | `generateMips` | none | render targets (made with `mips`) whose mip chain the pass fills once it has drawn | | `params` | the shader's own | values for the shader's `params:` fields, by name, for this pass | | `phase` | — (required) | any pass phase (see "When it runs") | | `clear` | `false` | clear the render targets the pass draws into (colour and depth) before it draws; the scene's own targets are never cleared | | `buffers` / `inputs` / `storage` | — | the shader's bindings, resolved exactly as a compute pass resolves its own | **Depth.** `depth.target` is `"@scene.depth"` (the opaque depth the frame laid down) or a render target the feature created, whose own depth buffer the pass draws and tests against. `compare` states the visible order a fragment is kept in — `"less"` keeps the fragment nearer to the camera than what the target holds, `"greater"` the farther one, and `"lessEqual"`, `"greaterEqual"`, `"equal"`, `"always"`, `"never"` likewise — the keywords a material's depth test takes. Every depth buffer a raster pass draws into is reversed, the scene's and a render target's alike: 1.0 is the near plane and 0.0 the far plane, and the engine maps each keyword onto the comparison that order takes, so `"less"` is the hardware's `greater`. `clear = true` clears a render target's depth to 0.0, the far plane, so the first fragment `"less"` meets is always kept. The matrix in `@frame.camera` already writes reversed depth. A pass placing vertices with a projection of its own that maps the near plane to 0 and the far plane to 1 (a light's orthographic shadow matrix built the conventional way) writes `clip.z = clip.w - clip.z` in `vs_main` to store the reversed value, and states its compare keywords in visible order as above. `test = false` keeps every fragment; `write = false` leaves the depth as it stood, and lets the same pass sample `@scene.depth` through its `inputs`. **A render target's depth as a texture.** `inputs = { shadow = "@depth.<guid>" }` binds the depth buffer of the render target `<guid>` (built with the target the first time a pass draws into it or reads its depth) to a `kind: texture_depth` binding, so a later raster or compute pass reads what a raster pass drew there: a shadow map, a depth pre-pass of the feature's own. Sample it with `textureLoad`, or with `textureSampleCompare` through a comparison sampler (below). **Winding.** A triangle whose vertices run counter-clockwise on screen faces the camera, as in WebGPU: `cull = "back"` drops the clockwise ones and `cull = "front"` the counter-clockwise ones. A projection that mirrors the picture (a negative determinant, such as one whose x or y axis is flipped) mirrors every triangle's winding with it; depth does not enter into it. **Colour targets.** `outputs` (or `output`) names `@scene.color`, `@scene.motion` or render targets the feature created, each with its blend: `"replace"`, `"alpha"`, `"premultiplied"`, `"additive"` or `"under"`, as the blend table under "Pass kinds" defines them. `blend` beside a single `output` takes the same keywords (`true` is `"alpha"`), so `output = rt, blend = "additive"` sums into `rt`. A keyword the pass does not know raises from `ctx.enqueue`, naming `blend`. **Motion vectors.** A pass whose geometry moves writes its velocity into `@scene.motion` as a second target, `outputs = { { target = "@scene.color" }, { target = "@scene.motion" } }`, with `fs_main` returning it at `@location(1)` as a `vec2` NDC displacement since the previous frame: the current clip position divided by its `w`, less the sub-pixel offset this render's matrix carries (`cam[13].xy`), less the previous clip position divided by its `w`. `vs_main` projects the previous position through the previous render's view-projection, `cam[5..9)`. `@scene.motion` is drawn from `afterDepthPrepass` to `afterLighting`; temporal reconstruction and motion blur read what the pass wrote there. **Samplers.** A `sampler` binding takes how it samples from `bindings.yaml`: `filter` (`linear` | `nearest`), `mipmap` (`linear` | `nearest`), `address` for every axis or `addressU` / `addressV` / `addressW` (`clamp` | `repeat` | `mirror`), and `anisotropy` (1 to 16, with `filter` and `mipmap` linear). A binding that also states `compare` (`never`, `less`, `less-equal`, `equal`, `greater`, `greater-equal`, `not-equal`, `always`, compared as WebGPU states them, reference against stored texel) is a `sampler_comparison`, for `textureSampleCompare` on a `texture_depth` binding. A binding stating none of these is the engine's linear, clamped sampler. A compute shader declares its samplers the same way. ```yaml bindings: - { name: albedo, kind: texture2d } - { name: smp, kind: sampler, filter: linear, mipmap: linear, address: repeat, anisotropy: 8 } - { name: shadow, kind: texture_depth } - { name: shadow_smp, kind: sampler, compare: greater-equal } ``` **Textures the feature made.** A texture `renderer.texture.create` made from pixels (`rgba = ...`) binds by its handle (or its guid) in `inputs`, the way a render target does. It holds its whole mip chain, each level made from the pixels it was given, so a sampler declaring `mipmap` reads it at any level. **Mip chains.** `renderer.texture.create({ width, height, mips = true })` makes a render target holding its whole mip chain (`mips = <n>` holds `n` levels). A pass draws into the first level; naming the target in `generateMips = { target }` fills every level below it, each the 2x2 average of the level above, once that pass has drawn — a raster, fragment or compute pass alike. Bound in `inputs`, the target binds its whole chain, so a sampler declaring `mipmap: linear` (and `anisotropy`) reads it the way it reads a texture asset's. A `screen` or `history` target is resized to each view it follows and holds one level. ```luau local water = renderer.texture.create({ width = 512, height = 512, format = "rgba16f", mips = true }) ctx.enqueue({ kind = "raster", shader = waterShader, phase = "afterOpaque", vertexCount = 3, output = water, clear = true, generateMips = { water } }) ctx.enqueue({ kind = "raster", shader = seabedShader, phase = "afterOpaque", vertexCount = 6, inputs = { water = water }, depth = true }) ``` **Per-pass values.** `params = { exposure = 1.5, layer = 2 }` gives the shader's `params:` fields values for this one pass, laid over the values the shader holds; a field the shader does not declare skips the pass, with the field named in the log. A compute pass takes the same table, and so does a compu
▲ 0↑ born
◐
material · born here
❒asset
# Neon A glowing cyan neon surface built on `@builtin::shaders.pbr` with emission enabled. It pairs a bright cyan-blue base colour (`0.2, 0.8, 1.0`) with a matching emissive colour driven hard by `emissive: 5.0`, so it reads as a self-lit light source. Low roughness (`0.2`), non-metallic, opaque, instanced, with the `_EMISSION` keyword enabled. ## Inputs - `colors.emissive` (`0.2, 0.8, 1.0, 1.0`) — cyan glow colour. - `floats.emissive_intensity` (`5.0`) — strong emissive intensity (feeds bloom). - `colors.base_color` (`0.2, 0.8, 1.0, 1.0`) — matching cyan base tint. - `floats.roughness` (`0.2`) — glossy surface under direct light.
▲ 0↑ born
·
assettype · born here
❒asset
# Material (asset type) A material is a named, configured instance of a `.shader`. The shader defines the surface look (lighting model, available property fields, texture slots); the material picks values for those fields and a shader to bind to. Renderable entities reference materials, not shaders, so the same geometry can wear different materials and the same material can be reused across many entities. Entities sharing one material can still differ in a value: every drawn object carries four `vec4` lanes of its own that a surface shader reads as `input.shader_data[lane]` and `renderer.instanceData.set` writes. Use that for a dissolve at its own progress per subject, a hit flash at its own age, a fill level per instance — a material per entity is for when the LOOK differs, not when a number does. > New to how a material relates to its shader, its textures, and the live GPU > material behind it? Read `core/resource-model` first. It also covers the > difference between an authored `.material` asset (this type) and a runtime GPU > material made with `renderer.material.create`. ## When to use one - You want a named surface configuration an entity wears by referencing it from its `Model` component (`material = "@.../<Name>"`). - You want runtime property tweaks (`asset.resolve(ref):setProperty(...)`) to affect every entity using the material at once. - You want to publish a curated look (`Gold`, `RedGlow`, `BrickWall`) other authors can reuse without re-typing shader bindings. If you need a brand-new lighting model or a custom visual effect, you need a `.shader` first; the material wraps it. ## Where it lives - Source: `/zero/source/.../<Name>.material/` - Identity: `<Name>` (the `.material` suffix strips). - Folder shape: - `mat.yaml` — canonical material spec (shader + property values). **Required.** - `README.md` / `.metadata` — optional prose + tags, indexed when an author writes real ones. - `textures/` — optional folder for embedded textures. Validator allows the folder; its interior is unrestricted. - `shaders/` — optional folder for a co-located custom shader. Same rule. ## How to create one ```luau asset.create("material", "<Name>") -- Creates: /zero/source/<Name>.material/ -- mat.yaml (shader binding + property scaffold) -- `folder` places it in a subfolder of /source instead of the root: asset.create("material", "<Name>", { folder = "materials" }) ``` Pass the shader and initial values through `asset.create`, then tune with `setProperty` and keep what you tuned with `saveDefinition`: ```luau local mat = asset.create("material", "<Name>", { shader = "@builtin::shaders.pbr" }) mat:setProperty("base_color", { 0.8, 0.6, 0.1, 1 }) mat:setProperty("roughness", 0.3) mat:saveDefinition() -- writes the tuned values into mat.yaml ``` This mints the `.material` asset and returns a handle you tune with `setProperty`. A set is a runtime change: it reaches the GPU material and every entity wearing it, and `saveDefinition` is the call that writes it into `mat.yaml`, so a property driven every frame costs no file write and leaves the authored file as its author wrote it. A purely runtime `asset.create` lives only for the session. For an ephemeral, runtime-only GPU material that is not an asset at all, use `renderer.material.create` instead (see `core/resource-model`). ## How it operates 1. **Property reflection.** The bound shader's uniform struct fields become the material's configurable properties — no manual property declarations needed. 2. **Property values.** `mat.yaml` groups values by type, each block keyed by the shader's field names: `properties:` holds scalars and colors/vectors, `ints:` holds integer-typed fields, `bools:` holds boolean-typed fields, and `textures:` holds texture slots. Omitted fields take the shader's default. A scalar is a bare number (`roughness: 0.5`); a color or vector is an array (`base_color: [1, 1, 1, 1]`). `shader:` is the shader's identity string. This is the shape every material the engine writes uses. A `saveDefinition` writes the changed values into the file where they already stand and leaves the rest of it — its comments, the order of its keys and blocks, the spelling of its literals, untouched. 3. **Render state.** `render:` holds how the mesh is drawn rather than what the shader reads: `blend` (the equation the fragment composites with, also spelled `type`), `cull`, `depth_write`, `depth_compare`, `topology` and `queue` (the draw order, a whole number: `2000` opaque, `3000` transparent, `4000` overlay). The `.shader` type README's "The render block" section lists every value each key takes, and `asset.create`'s `render` argument takes the same keys and values. 4. **Application.** An entity wears a material by referencing it from its `Model` component (`material = "@.../<Name>"`). Materials affect every entity that references them; runtime `asset.resolve(ref):setProperty(...)` changes propagate to all of them immediately, and last until the next mode change unless `saveDefinition` writes them into `mat.yaml`. 5. **Texture binding.** Texture slots accept `color:r,g,b,a` for solid colors, `default:white` / `default:black` / `default:normal` for the engine's own fallback texels, `@builtin::textures.<name>` for builtins, `path/to/image.png` for file textures, or a render-target handle for camera renders. The GPU texture cache reads the `color:` and `default:` forms from the string itself, so a slot written in one names no asset and carries nothing with the material when it travels; every other form names a texture asset the slot depends on. A texture in `base_color_texture` is multiplied by `base_color`: every built-in surface shader declaring both draws the texture's colour times `base_color`, channel by channel. Under the default white `base_color` the texture shows as itself, and a coloured `base_color` tints it. The two read a colour differently: `base_color` is linear, and the slot reads its texels as sRGB-encoded, a `color:` value's included, the way it reads an image. A colour stated in both places is therefore multiplied by a darker copy of itself: `color:0.62,0.14,0.05,1` in the slot decodes to `0.34, 0.017, 0.0039`, so beside `base_color` `0.62, 0.14, 0.05` the surface draws `0.21, 0.0024, 0.0002`, far darker than either. State a solid colour once, as `base_color`, and leave the slot at its default white. 6. **Hot reload.** Editing `mat.yaml` repacks the GPU uniform buffer on the next frame; visible immediately. **Properties that follow a named value.** `values:` binds a property to a named value of the entity wearing the material (`values.set(entity, name, v)`, the `topics/values` guide): `property: valueName`, or `property: { value: "name", scale: s, offset: o }`, and the property draws `value * scale + offset` on each entity holding the value, read on the draw. A boolean reads as 1 or 0, and a number fills every channel of a colour or vector property. The wearer's own value is read, else its nearest ancestor's, so a lamp mesh under a car lights from the car's `brake`; a wearer holding none draws the material's own value. A scalar, vector, colour or bool property binds (at most 32 per material); a texture slot does not. `asset.create("material", name, { values = { ... } })` and `renderer.material.create({ ..., values = { ... } }, key)` take the same map. ```yaml values: emissive_intensity: { value: "brake", scale: 3 } ``` 7. **Inspector.** `type.yaml` names `inspector: { type: "inspector.luau" }`, and `inspector.luau` declares the material's sections beside the generic ones: `shader` (the bound shader, swappable), `properties` (each shader field as its typed control) and `textures` (each texture slot as an asset chip). They read the material through `mat:getShaderRef()` (the bound shader's ref, `~` expanded) and `mat:getTextures()` (slot name → `{ ref, name }`: the bound texture's guid and the id the material names it by). An edit there is an authoring write: `mat:writeProperty(name, value)` and `mat:writeTexture(slot, texture)` write the value into `mat.yaml` (and drop the session's own value for it, so the material reads what the file holds), and `setShader` rewrites the file; inside an undo operation each file write is recorded, so undo puts `mat.yaml` back. `setProperty` / `setTexture` stay runtime writes that last until the next mode change. ## Discovery - `asset.list("material")` — every registered material. - `asset.inspect("<name>")` — shader binding, property values, source path, this type README. - `ls /zero/source/<Name>.material` lists the files the folder holds. - `asset.resolve("<name>"):getProperties()` — the property fields exposed by the bound shader, each at the value it currently holds: what `mat.yaml` authored until something writes to the material, and the written value from then on, whichever call wrote it. That is the value the surface is drawn with. Read them back rather than guessing names; which fields exist comes from the shader. - `asset.resolve("<name>"):getDefinition()` — the authored `mat.yaml` bytes, the value the material rests at. - `asset.resolve("<name>"):getShader()` — the shader the material binds. ## Authoring conventions - Use lowercase, descriptive names (`brushed_steel`, `red_glow`, `tarmac_wet`). Avoid shader-name suffixes in the material name — the binding lives in `mat.yaml::shader`. - Drive every property the shader exposes; defaults are a fallback, not a contract for which fields exist. - Embed textures alongside the material (`textures/` subfolder) when they're used only by this material; reference shared textures from `@builtin::textures.*` or a library. ## Common pitfalls - **Property names must match the shader's uniform struct exactly** (case-sensitive). Misnamed properties silently get the shader's default. - **`base_color_texture` multiplies `base_color`.** A `color:` texture holding the same value as `base_color` multiplies the colour by its own sRGB-decoded value, so the surface renders far darker than the value written. Write a solid colour as `base_color` alone. - **Broken shaders break the material.** A material whose shader has a parse error renders as the magenta checkerboard. Inspect the shader first if the material looks wrong. - **`setProperty` targets the material, not the entity.** Changes affect every entity that references the material. - **`setProperty` is a runtime change.** It reaches the GPU, not the file: call `saveDefinition` to write the current values into `mat.yaml`. For a per-entity override that no other entity sees, give the entity its own copy with `Model:applySessionMaterial(renderer.material.create(...))`. - **Renaming the folder changes the identity.** A `Model` component or other reference to the material is recorded against the material itself, so renaming or moving it does not break them. ## Related types - `.shader` — defines what properties exist; required before a material can bind to it. - `.preset` — captures a component configuration; conceptually similar to a material, but for components instead of shaders.
▲ 0↑ born
▣
module · born here
❒asset
# ecs Public, typed, discoverable API for native ECS components. Generic verbs (`insert`, `get`, `set`, `has`, `remove`, `query`, ...) operate on any component, while per-component typed constructors (`ecs.Mesh`, `ecs.Material`, `ecs.Transform`, ...) build the Rust-shaped value the verbs apply. Each constructor is minted at module load from a spec under `ecs.components.<Name>`. ## Typed constructors `ecs.<Name>{...}` builds a component value: it runs the compiled conversion plan (asset-handle resolution, camelCase → snake_case field mapping, `vec3` expansion) and raises on an unknown field. The result is a value the upsert verbs accept. ```luau local ecs = require("modules.api.engine.ecs") local value = ecs.Transform{ position = { x = 0, y = 1, z = 0 } } ecs.insertSync(id, value) ``` The constructor also takes every shape the component is read back as, so a read hands straight to the constructor it came from: - the `ecs.get` handle — `ecs.Light(ecs.get(id, ecs.Light))`, - the engine-side field table `handle:read()` and `ecs.snapshot(id).<Name>` give back, - a value the constructor already built (copied, so the two are separately writable), - a table keyed by public field names, engine-side field names, or both. That makes changing one field a read, an assignment and a write back: ```luau local h = ecs.get(id, ecs.Light) h.intensity = 0 ecs.set(id, ecs.Light(h)) -- every other field keeps what it held ``` Each of those shapes names the component it holds, so handing one to another component's constructor says which component it is and which constructor takes it. The `ecs.get` handle writes its own fields as well — `h.intensity = 0` is already the whole write — so reach for the round trip when you want the component's value in hand. ## Verbs Every verb accepts an entity proxy (what `entity.spawn` returns) or a raw id string. - `ecs.insert(id, value) -> promise` — async upsert; await for same-tick visibility. - `ecs.insertSync(id, value)` — upsert visible this tick; raises on failure. - `ecs.insertMany(ids, value) -> number` — insert one value into many entities in a single crossing; returns the count applied. The three insert verbs warn per field a component could not hold the value it was given, naming the component, the entity, the field under its engine-side name and the value; the component holds that field's default and every other field lands. - `ecs.get(id, ecs.<Name>) -> handle?` — retained handle over a present component (`nil` when absent). See `handle`. - `ecs.set(id, value) -> ok, rejected` — patch fields of an already-present component; raises if the component is absent. `ok` is false and `rejected` lists the public field names that did not land when a field cannot hold the value it was given (a string outside an enum field's set, a shape the field's type does not read). Each name appears once and is warned once, with the component, the entity and every value that name refused — under the name you wrote it as, where the insert verbs name the engine-side one. Every field is attempted, so one refusal leaves the rest applied. - `ecs.has(id, ecs.<Name>) -> boolean` - `ecs.findInSubtree(id, ecs.<Name>) -> string?` — the id of the entity itself, or else of the first of its descendants (depth-first, each entity before its children, children in `entity.getChildren` order), that carries the component; `nil` when none does. The walk runs in the engine and builds nothing in Luau, so asking it every frame of a subtree that holds no such component allocates nothing. - `ecs.len(id, ecs.<Name>, field) -> number?` — element count of a collection-valued field (list/array/map/set), counted without building any element; `nil` when the component is absent or the field is not a collection. Reading the field to measure it converts everything in it — `#h.bones` on a 50-bone `Skeleton` costs ~1ms against one crossing here — so ask this whenever the question is how many, or whether any. - `ecs.remove(id, ecs.<Name>)` - `ecs.components(id) -> {string}?` — public component names present on the entity. - `ecs.snapshot(id) -> table?` — every native component on the entity, nested and keyed by public name, each holding that component's fields under the names the component itself uses. A catalogued component's field table names the component it came from, so it goes straight to that constructor. - `ecs.queryIds(...) -> {string}` — ids holding ALL the given `ecs.<Name>` types. - `ecs.query(...) -> {proxy}` — like `queryIds` but returns entity proxies. - `ecs.bind(id, component, field, mode?)` — retained component-field accessor by rust component name. - `ecs.bindEntities(ids)`. ## Discovery The engine is driven at runtime, so the catalog is introspectable in-engine: - `ecs.types() -> {string}` — public component names available as `ecs.<Name>`. - `ecs.describe() -> { schema, ... }` — the full catalog: every component with its fields. `ecs.describe(name | ecs.<Name>)` returns the schema for one component. - `ecs.<Name>:schema() -> { component, rust, fields = { {name, type, rust}, ... }, methods?, accepts }` — runtime field discovery for a single component; `accepts` lists the calls the name is accepted by, the round trip among them; behavior-bearing components also list their handle `methods`. ```luau for _, schema in ecs.describe() do print(schema.component, #schema.fields) end ``` ## Saved native components A saved record (a scene entity, a bundle `entity_template` entry) lists its native components in an `ecs` array beside `components`: `ecs = { { type = "Mesh", data = { mesh = "<mesh asset guid>" } }, { type = "Material", data = { id = "<material asset guid>" } } }`. `type` is the name under `ecs` and `data` the row `ecs.snapshot` answers, with every handle-typed field written as the guid of the asset the handle came from. The scene loader and `bundle:instantiate` resolve each guid to the handle the component holds (`ecs.handles`, see its README) and insert one value into every entity that states the same entry.
▲ 0↑ born
·
assettype · born here
❒asset
# toolbox (asset type) A toolbox is an asset grouping set of `<tool>.tool` assets around one area of work. Each tool in it becomes callable under the toolbox `<toolbox>.<tool>`, and is a shell command, `zero <toolbox> <tool> <args>`; `guides core/tools`, "A tool's command line", covers its flags, paths, `render.luau` and exit status. ## When to group tools together When creating tools for the engine, a common theme should be identified and and a toolbox created to house them, this allows each individual operation to be easily accessible instead of being scattered in a million places. ## Sharing functionality between tools A toolbox features ability to define functions that code inside each individual tool inside it can access, this is usefull when establishing helpers etc so you dont have to duplicate code for each new tool you write. A `shared.module` inside the toolbox root is where this code lives, each tool inside a toolbox can access its functions by requiring it with `require(".shared")`. ```luau -- <toolbox>.toolbox/shared.module/init.luau local M = {} -- One step a tool reports in its result. export type Step = { name: string, ok: boolean, detail: string? } --!desc Check that a numeric argument lies within bounds. --!arg arg The argument's name, for the error. --!arg value The value passed. --!arg min The lowest value allowed. --!arg max The highest value allowed. --!return The value; raises naming the argument and the range when it lies outside. --!example "count", 12, 1, 100 typed function M.range(arg: string, value: number, min: number, max: number): number if value < min or value > max then error(string.format("%s must be between %s and %s, got %s", arg, tostring(min), tostring(max), tostring(value))) end return value end --!desc A byte count as a readable size. --!arg bytes The count. --!return The size in B, KB, MB or GB. --!example 2681107 typed function M.size(bytes: number): string local units = { "B", "KB", "MB", "GB" } local i = 1 while bytes >= 1024 and i < #units do bytes /= 1024 i += 1 end return if i == 1 then string.format("%d %s", bytes, units[i]) else string.format("%.1f %s", bytes, units[i]) end --!desc A step for a tool's result. --!arg name What the step did. --!arg ok Whether it succeeded. --!arg detail What happened, when there is more to say. --!return The step. --!example "copy textures", true typed function M.step(name: string, ok: boolean, detail: string?): Step return { name = name, ok = ok, detail = detail } end --!desc The asset of `kind` that a caller named, looked up by that name. --!arg kind The asset type to look in. --!arg name The name the caller passed. --!return The asset; raises naming the kind and name when nothing matches. --!example "material", "gold" typed function M.named(kind: string, name: string): AssetRef local ref = asset.tryResolve(name, kind) if ref == nil then error(string.format("no %s named '%s'", kind, name)) end return ref end return M ``` This shared code should be limited to being used by the tools inside it, dont put general functionality you might need otuside the toolbox into its shared module. Instead reference those in the shared module should you wish to utilize something. A benefit the shared module shares with the tools own code is that it allows the author to write code that has computed references, meaning eg resolving an asset from a computed variable `asset.resolve(<type>,name)` that is normally not allowed in other parts of the engine surface, due to said references not being recorded. This is usefully for utilizing tools to handle operations that are called by users/agents and are dynamic in nature, such as finding/inspecting/testing assets, or content based on an input etc. When writing a shared module, you should follow standard module practices, please see `module.assetType` readme.md for more indepth information. ## Describing the toolbox When writing the readme for your toolbox, ensure you focus on the overall area what the toolbox focuses on, rather than listing individual tools inside it, discovery surfcaces already group tools and toolboxes together so a toolbox can be discoverd by the tools it hosts and doesnt require separately maintaining a list of the tools in it's readme. ## What are tools and when do i create ones? Tools are typed operations with a known serialized output format, made to enable efficient operation in the engine and provide an easily callable interface for operations around a topic. They are also useful in that they can be called from a multitude of surfaces, from `execute`, to `bash` to `tool_exec` to users Tools portion in the edui. A toolbox and its tools differ from eg a module that has multiple callable functionm in that they might return anything, and come with no guarantee that the output is meant to be inspected directly, where as tools are meant to perform an self contained operation and return results/info/relevant data in a readable format, including eg. image data. Whenever you identify an operation that requires specific orchestration and or is something that could be a repeated operation and makes it easier to manage the project/task or when you want to expose logic written in `luau` to the other call surfaces like `bash` under its `zero` command,you should reach for creating a toolbox. Toolboxes also come in handy for limiting control/inputs, exposing a limited set of functionality in a clean manner or ensuring the caller doesnt have to understand the entire code. For comparison, you could think of toolboxes as programs, and the tools inside them as commands. A package might contain tens of tousands of lines of code, dozens of modules, components etc, a toolbox turns that surface into a system that any agent/user can then utilize without having to read or understand the code inside. Its the UI equilevant to operations. For the indepth explanation of what `tool.assetType` is and does, read it's readme.
▲ 0↑ born
·
assettype · born here
❒asset
# Compute shader (asset type) A `.computeShader` is a GPU compute (GPGPU) program with a **zero-scaffolding** authoring contract: you write only `@compute fn main(...)` plus a declarative `bindings.yaml`, and the engine GENERATES every `@group/@binding` declaration — storage buffers, textures, samplers, storage textures, and a `params:` uniform — expands `#include`s, naga-validates the result, and registers it. The single source of truth for the binding layout is `bindings.yaml`; there are no hand-written `@binding` lines to keep in sync. > New to how content lives across the CPU and GPU? Read `core/resource-model` > first: it covers the asset / CPU / GPU forms every resource takes, the upload > path, and how compute fits the performance ladder (`core/performance`). ## Folder shape A `.computeShader` is a folder asset: ``` <name>.computeShader/ shader.wgsl # the WGSL body — only `@compute fn main` + helpers (required) bindings.yaml # the binding + params schema (required) README.md # a one-paragraph description of THIS shader (required) .metadata # asset metadata ``` Each file carries a committed `.meta` sidecar pinning its stable guid. The identity is `<name>` (the `.computeShader` suffix strips). Resolve the shader once, then dispatch through the reference: ```lua local carve = asset.resolve("carve", "computeShader") carve:dispatch({ buffers = { heights }, workgroups = { 64 } }) ``` `asset.resolve` is what records your script's dependency on the shader, so the shader travels with the world your script lives in — packed, pulled, or published. It compiles on first dispatch; there is no setup step. ## bindings.yaml One ordered `bindings:` list — the binding index is the list position (0, 1, 2, …) — plus an optional `params:` scalar-uniform block. `kind` defaults to `buffer` when omitted. ```yaml bindings: - { name: clouds, kind: storage3d, format: rgba16f } # texture_storage_3d<rgba16float, write> - { name: occupancy, kind: texture3d } # texture_3d<f32> - { name: smp, kind: sampler } # sampler - { name: out_tex, kind: storage2d, format: rgba16f } # texture_storage_2d<rgba16float, write> - { name: U, kind: buffer, access: read, element: f32 } # var<storage, read> U: array<f32> - { name: Uniforms, kind: buffer, access: read, element: VolumeUniforms, array: false } # var<storage, read> Uniforms: VolumeUniforms params: - { name: scale, type: float, default: 2.0 } - { name: count, type: int, default: 0 } ``` | `kind` | extra keys | generated WGSL declaration | |---|---|---| | `buffer` (default) | `access: read \| read_write` (default `read_write`), `element: <wgsl type>` (default `f32`), `array: true \| false` (default `true`) | `var<storage, ACCESS> NAME: array<ELEMENT>;` (or `… NAME: ELEMENT;` when `array: false`) | | `texture3d` | — | `var NAME: texture_3d<f32>;` | | `texture2d` | `sample: float \| uint \| sint` (default `float`) | `var NAME: texture_2d<f32>;`, or `<u32>` / `<i32>` for the other classes | | `texture_depth` | — | `var NAME: texture_depth_2d;` — the one sampled shape with no `sample:` of its own; a depth-aspect channel (`@scene.depth`) binds here, not through `texture2d` | | `storage3d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_3d<FMT, ACCESS>;` | | `storage2d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_2d<FMT, ACCESS>;` | | `sampler` | — | `var NAME: sampler;` | | `textureCubeArray` | — | `var NAME: texture_cube_array<f32>;` — the environment cube array, bound to `@scene.environment` by a render feature's pass | | `vertices` | `access: read \| read_write` (default `read_write`) | `var<storage, ACCESS> NAME: array<u32>;` plus the mesh's layout uniform and the `zeroVertex*` accessors | | `acceleration_structure` | — | `var NAME: acceleration_structure;` (hardware ray tracing) | - **Eight storage buffers per shader** — the WebGPU guarantee, and what the engine asks every device for. `buffer` and `vertices` bindings spend that budget; textures, samplers, storage textures and `params:` do not. An `acceleration_structure` brings engine-owned buffers with it — **three** where the device has hardware ray query (the tables `zeroHitSurface` / `zeroMaterial` read) and **five** on the software backend (those, plus the scene triangles and the hierarchy over them) — so a traced pass has three slots of its own on the backend web users get. Over budget, the engine refuses the shader and logs which buffers it declared. - A `buffer` defaults to `array<ELEMENT>`. Set `array: false` for a single NON-array storage buffer — a struct binding (e.g. `element: VolumeUniforms`, `array: false` → `var<storage, read> NAME: VolumeUniforms;`). The struct definition itself lives in `shader.wgsl`, not `bindings.yaml`. - **A sampled texture binds under the class its FORMAT puts it in**, so `sample` states that class and the generated `texture_2d<..>` matches it. An integer channel — `@scene.material`, which is `Rgba8Uint` — is `uint`; everything else is the `float` default. Bind an integer channel to a `float` slot and the engine refuses the pass and names both classes, because the device would otherwise reject the bind group and invalidate the pipeline. - A storage texture's `access` decides both the generated declaration and the layout the engine registers, so the two always agree. It defaults to `write`, the access every target grants every storage-compatible format. `read_write` is granted on `r32f` alone; declaring it on any other format is refused at the compile, with the reason on `compute.programState`. A pass that needs to read a wider target reads it through a separate `texture3d` / `texture2d` binding, or through a second storage binding declared `read`. - `format` tags (storage textures): `r8`, `r16f`, `r32f`, `rgba8`, `rgba16f`, `rgba32f`. Storage textures only allow storage-compatible formats (`r32f` / `rgba8` / `rgba16f` / `rgba32f`). - An `acceleration_structure` binding resolves to the scene acceleration structure when the shader runs as a render-pass with ray tracing enabled (`renderer.setRaytrace(true)`). Declaring one makes the engine emit the helper functions the body can call: `zeroTraceClosest(origin, dir, t_min, t_max) -> ZeroHit` (struct: `hit, t, instance, primitive, bary, attr`, where `instance` is the hit object's render slot), `zeroTraceAny(origin, dir, t_min, t_max) -> bool` (terminate-on-first-hit, for shadow/occlusion rays), and `zeroHitSurface(hit) -> ZeroSurface` (`normal, uv, material`) + `zeroMaterial(index) -> ZeroMaterial` (`base_color, emissive, metallic, roughness`) to shade what a hit landed on. The same surface works on both backends — hardware ray query and the software/compute path — so the shader doesn't branch on `renderer.raytraceCapability()`. Bind it from a render-pass, which is where the scene acceleration structure exists. `params:` declares scalar uniforms (`type: float | int`). When non-empty the engine appends a `ZeroComputeParams` uniform as the trailing binding (read it in WGSL as `params.<name>`) and tunes its values at runtime with `shaderRef:setParam(prop, value)`. ## The kernel ABI: `columns`, counted and appended outputs, `specialize`, `determinism` One shader asset can serve many shapes of data. `bindings.yaml` states the shape with these extensions, and the engine's compile path lowers them to the plain bindings and WGSL above (`modules/compute_abi`, whose README has the whole surface): ```yaml workgroup: 64 # the size the body declares (default 64) bindings: - { name: cols, kind: columns, access: read } # a table of columns in one binding - { name: src, kind: buffer, access: read, element: T } - { name: dst, kind: buffer, access: read_write, element: T, count: "len(src)" } - { name: hits, kind: buffer, access: read_write, element: vec4<f32>, capacity: "n * 4", append: true } specialize: - { name: T, options: [f32, i32, vec2<f32>, vec3<f32>, vec4<f32>] } - { name: FOLD, options: [add, min, max] } - { name: BODY, kind: source, default: "0.0" } # text that replaces the identifier determinism: exact # or float_order ``` - A `buffer` of a scalar or vector element gets `NAME_get(i)`, `NAME_len()` and (unless `access: read`) `NAME_set(i, v)`. A `vec3` element is stored as a flat scalar array, so a column of vec3 keeps its 12-byte stride. `zero_n()` is the dispatch size. - `columns` binds a table of columns (`compute_abi.table`) as one storage buffer; `cols_f32(c, i, lane)`, `cols_vec3(c, i)` and the rest read it. - `count` / `capacity` give the size, in elements, of an output the run allocates. `append: true` adds a live counter binding, `NAME_count`, with `NAME_store(slot, v)`, `NAME_set_count(n)` and, under `determinism: float_order`, `NAME_append(v)`. - `specialize` parameters are compile-time: type options become `alias NAME`, named options become `const NAME` and `NAME_<option>`, `kind: source` text replaces the identifier. Each specialization compiles once. - `determinism: exact` refuses `NAME_append`: an exact output is written at ranks the kernel computed. Dispatch such a shader through its program: ```lua local variant = shaderRef:program():variant({ specialize = { T = "vec3<f32>" } }) local run = variant:run({ n = 64, inputs = { src = srcBuffer } }) local values = require("@builtin::modules.compute_abi").read(run.outputs.dst.buffer) ``` `shaderRef:program()` answers the same program, with the variants it has lowered and compiled, for as long as `shader.wgsl` and `bindings.yaml` hold the bytes they held when it was made. A write to either file, from any origin (`vfs.contentVersion` moves), makes the next `program()` a new one, and a dispatch through it runs the new text. The schema `getBindings()` answers is the one the program was made over. ## Writing a mesh's vertices — `kind: vertices` A mesh's vertices are raw bytes on the GPU, and the engine stores a mesh in one of two layouts: 92 bytes a vertex with every attribute a `f32`, or 32 bytes a vertex with normals and tangents quantized to bytes and UVs to shorts. Which one a mesh got depends on the mesh. Declare `kind: vertices` and the shader is handed both the buffer and the layout that mesh is in, plus accessors that address it: ```yaml bindings: - { name: verts, kind: vertices } # the mesh, writable - { name: heights, kind: buffer, access: read, element: f32 } params: - { name: lift, type: float, default: 1.0 } ``` ```wgsl @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) { if (id.x >= zeroVertexCount()) { return; } var p = zeroVertexPosition(id.x); p.y = p.y + heights[id.x] * params.lift; zeroSetVertexPosition(id.x, p); zeroSetVertexNormal(id.x, vec3<f32>(0.0, 1.0, 0.0)); } ``` ```lua carve:dispatchOnVertices({ model = meshRef:handle().guid, buffers = { heights }, workgroups = { 64 } }) ``` The accessors, over a binding declared `read_write`: | read | write | |---|---| | `zeroVertexCount() -> u32` | — | | `zeroVertexPosition(i) -> vec3<f32>` | `zeroSetVertexPosition(i, vec3<f32>)` | | `zeroVertexNormal(i) -> vec3<f32>` | `zeroSetVertexNormal(i, vec3<f32>)` | | `zeroVertexTangent(i) -> vec4<f32>` | `zeroSetVertexTangent(i, vec4<f32>)` | | `zeroVertexUv(i) -> vec2<f32>` | `zeroSetVertexUv(i, vec2<f32>)` | | `zeroVertexColor(i) -> vec4<f32>` | `zeroSetVertexColor(i, vec4<f32>)` | | `zeroVertexNodeIndex(i) -> u32` | — | | `zeroVertexWord(i, offset) -> u32` | — | `access: read` gives you the readers only — a `var<storage, read>` binding cannot be assigned to, so the writers are left out rather than handed to you broken. Once a pass has written a mesh's vertices, the engine bounds that mesh by what the pass wrote: it reduces the vertices to an AABB every frame and culls against that, so geometry a pass moves across the scene needs no oversized placeholder to survive culling. `renderer.mesh.boundsSource(guid)` reports `"compute"` for such a mesh and `"geometry"` for one still bounded by what it was created with. A shader declares at most one `vertices` binding; the accessors are generated for that mesh. It can be declared anywhere in the list — the mesh is bound by the dispatch, and `buffers` fills the other storage slots in declaration order. The tangent's `w` carries handedness, and quantized normals/tangents come back in -1..1 while quantized UVs and colours come back in 0..1, so the values are the same ones a surface shader sees whichever layout the mesh is in. ## shader.wgsl Write only `@compute fn main` (and any helpers / `#include`s). The names declared in `bindings.yaml` are in scope — `data`, `out_tex`, `params.scale`, … — with no `@group`/`@binding` lines of your own. ```wgsl // @domain: compute // Bindings are declared in bindings.yaml — do NOT write @group/@binding here. @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) { if (id.x < arrayLength(&data)) { data[id.x] = data[id.x] * 2.0; } } ``` ## Dispatch & runtime Everything a compute shader does, it does through its reference: | method | what it does | |---|---| | `ref:dispatch(opts)` | `{ buffers, workgroups, params? }` — bind one buffer per declared storage binding, in order | | `ref:dispatchOnVertices(opts)` | `{ model, buffers?, workgroups, params? }` — bind the mesh `model` names to the `vertices` binding, `buffers` filling the rest | | `ref:dispatchEx(opts)` | `{ resources, workgroups }` — for shaders mixing textures, samplers and storage textures: one `{ kind, name }` per declared binding, in order | | `ref:setParam(prop, value)` | write one `params:` scalar uniform | | `ref:createBuffer(name, opts)` | `{ type, len, usage? }` — a GPU buffer owned by this shader | | `ref:buffer(name)` | the buffer this shader last made under `name` | | `ref:getBindings()` | the parsed `bindings.yaml` schema, read and parsed again only after the file is written | | `ref:getSource()` / `ref:setSource(wgsl)` | read / overwrite `shader.wgsl` | | `ref:compile()` | compile now instead of on the first dispatch | | `ref:status()` | what the engine did with this shader's dispatches, one record per target | The `params:` uniform is engine-owned and takes no entry in `buffers` or `resources`, and neither does a `vertices` binding's layout. `setParam` writes the uniform every later dispatch reads. A dispatch that passes `params = { name = value }` reads those values instead, in a copy of the uniform only it binds, with every name it leaves out at the value the shader holds — so one shader dispatched twice in a frame over different data reads different values each time: ```lua lift:dispatch({ buffers = { a }, workgroups = { 4 }, params = { height = 1.0 } }) lift:dispatch({ buffers = { b }, workgroups = { 4 }, params = { height = 3.0 } }) ``` A name the shader does not declare fails that dispatch, and the failure names what it does declare. ### `dispatchEx` resources Each `resources` entry fills the binding at its position. Its `kind` says what the resource is, in the words `bindings.yaml` uses, and the binding decides how it is read. A slot takes the kind it is declared with; a `texture2d` slot also reads a storage texture, a side of a history pair or the scene depth, and a `storage2d` slot also writes this frame's side of a history pair: | binding's `bindings.yaml` kind | `resources` entry | `name` | |---|---|---| | `buffer` | `{ kind = "buffer", name = buf }` | a buffer handle from `ref:createBuffer` | | `texture3d` | `{ kind = "texture3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` | | `storage3d` | `{ kind = "storage3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` made with `storage = true` | | `storage2d` | `{ kind = "storage2d", name = target }` | a storage texture handle from `ref:createStorageTexture2D` | | `storage2d` | `{ kind = "history_curr", name = history }` | a history pair from `ref:createTextureHistory`: this frame's side | | `texture2d` | `{ kind = "texture2d", name = tex }` | a handle `ref:copyBufferToTexture` returns, or a texture asset's guid once `texRef:handle()` has made it GPU-resident | | `texture2d` | `{ kind = "storage2d", name = target }` | a storage texture handle, read as a texture | | `texture2d` | `{ kind = "history_prev", name = history }` / `{ kind = "history_curr", name = history }` | a history pair: the previous frame's side or this frame's | | `texture2d` | `{ kind = "scene_depth" }` | none: the frame's scene depth | | `sampler` | `{ kind = "sampler", name = smp }` | a sampler handle from `ref:createSampler` | `texture3d` and `storage3d` name the same resource, a 3D texture, so either one fills either slot. The engine's own spellings name the same resources and keep working: `texture_3d` for `texture3d` and `storage3d`, `texture_2d` for `texture2d`, and `storage_2d` for `storage2d`. Any other `kind` is refused at the call, naming every kind it accepts. A `vertices` binding is filled by `ref:dispatchOnVertices`, and `texture_depth`, `textureCubeArray` and `acceleration_structure` bindings by a render feature's pass. ```lua local march = asset.resolve("volume_march", "computeShader") -- bindings.yaml: density (storage3d), out_tex (storage2d), U (buffer) march:dispatchEx({ resources = { { kind = "storage3d", name = density }, { kind = "storage2d", name = target }, { kind = "buffer", name = uniforms }, }, workgroups = { 8, 8, 8 }, }) ``` `workgroups` is `{ x, y, z }`, `{ x }`, or a bare `x`, and every dimension it leaves out is 1. A zero in any dimension is refused: the dispatch is dropped and recorded as a failure, so it surfaces in `ref:status()` and `compute.failing()` with the reason. A count derived from how much data there is passes through `math.max` first, so an empty set dispatches one workgroup rather than none: ```lua carve:dispatch({ buffers = { heights }, workgroups = { math.max(1, math.ceil(#points / 64)) } }) ``` ### Buffers and readback (the CPU side) A buffer is created through the shader that owns it and comes back as a handle. Pass the handle to a dispatch — including another shader's — to bind it there: ```lua local double = asset.resolve("@builtin::shaders.compute_double", "computeShader") -- `type` is the element the shader declares, `len` how many of them. local data = double:createBuffer("data", { type = "f32", len = 4, usage = { "readback" } }) data:write({ 1.0, 2.0, 3.0, 4.0 }) -- :writeU32 for integer words, :writeBytes for packed bytes double:dispatch({ buffers = { data }, workgroups = { 1, 1, 1 } }) local pending = data:read() -- starts an async GPU->CPU readback -- a frame or two later, drain it (nil until it has arrived): local out = pending:result() -- :resultU32 / :resultBytes read the same bytes another way data:destroy() -- free it when done ``` `type` is one of `"f32"`, `"vec3"`, `"vec4"`, `"quat"`, `"mat4"`, and `usage` adds `"readback"`, `"vertex"`, `"index"` or `"indirect"` on top of the storage a buffer always has. An `"indirect"` buffer holds a draw's arguments where the GPU reads them, so a shader that compacts geometry writes the drawn count into the same dispatch that produced it and a render feature's `kind = "draw"` pass submits exactly that — the `renderFeature` asset type's README documents that pass and the `storage.indirect` name it reads. The handle's key is the shader's guid plus the name you gave it and a serial, so two shaders that both want a buffer called `data` get one each — and so do two callers asking this same shader for one. `ref:buffer(name)` returns the last one made under that name, which is how two callers share one on purpose. A buffer that no shader computes — a vertex or index run that is only ever drawn — is allocated straight from the primitive instead: `substrate.createBuffer({ name = ..., type = ..., len = ..., kind = "gpu", usage = { "vertex" } })`. The first dispatch of a shader compiles it, so the very first readback can still reflect the un-run shader; dispatch again once it is compiled, or `ref:compile()` to pre-warm. This create/write/dispatch/readback loop is the CPU side of the resource model in `core/resource-model`. ### Is it compiled? `ref:compile()` queues the compile; the pipeline is built on the render side frames later, so that call cannot say whether it produced a program. `compute.programState(ref)` is where that lands: ```lua if compute.programState(carve) == "ready" then carve:dispatch(opts) end local state, reason = compute.programState(carve) if state == "failed" then print(reason) end ``` - `"absent"` — the engine holds nothing under this key and nothing is in flight: never asked for, or released. - `"pending"` — a compile was asked for and has not reached the device. A recompile of a resident program reads pending too, because what it produces is a different program from the one bound now — which is what makes this the precondition to wait on after an edit. - `"ready"` — compiled and resident, so a dispatch naming it binds it. - `"failed"` — the most recent compile produced no program, and the second return says why. A dispatch issued while the program is `"pending"` is held behind the compile and dropped if it never lands, so a readback taken before `"ready"` reports the buffer as it was. Wait for `"ready"`, not for a count of frames. ### Did it run? A dispatch is recorded into a command encoder frames after the call that asked for it returned, so that call's `true` means "queued", not "ran". `ref:status()` is where the outcome lands — one record per target, cumulative: ```lua for _, d in ipairs(carve:status()) do print(d.target, d.ok, d.dispatches, d.failures, d.lastError) end ``` `target` is the mesh guid for a `dispatchOnVertices` and the buffers it bound for a dispatch that writes only those, so two systems driving one shader over their own buffers read as the two passes they are. `ok` is the most recent outcome; `lastError` says why the last failure failed and is kept after a recovery. An empty result means nothing has dispatched this shader at all. `compute.failing()` answers the same question across every shader at once. A failing dispatch also posts a notice, so a pass that stops running reports itself rather than waiting to be found. ### Running one every frame A `kind = "compute"` substrate job queues one dispatch per frame: ```lua jobs.register({ phase = "main", executor = { kind = "compute", shader = asset.resolve("carve", "computeShader"), buffers = { "heights" }, workgroups = { 64 }, }, }) ``` ## Registration & hot reload Writing `shader.wgsl` or `bindings.yaml` fires the `.computeShader` assetType's `onChange`, which compiles it: the binding declarations are generated, `#include`s expanded, the WGSL validated, and the shader registered. This happens on create and on every edit, so saving recompiles with no world reload. A shader with invalid WGSL (a type mismatch, an undefined name) **fails to compile** with the reason logged (`[compute] Compile of '<name>' failed: …`) and is **not** registered. You don't need to register a shader before dispatching it — the first dispatch auto-compiles it on use. `ref:compile()` remains as an optional explicit pre-warm, only to avoid the one-frame first-dispatch warm-up in a latency-critical spot. ## What compute is holding, and why a key names nothing Every buffer, volume, storage target, history pair and sampler a dispatch can bind is filed under a key, and `compute.observe()` lists all of them with what each costs: ```lua local r = compute.observe() print(r.totals.count, r.totals.bytes) for _, res in ipairs(r.resources) do print(res.key, res.kind, res.bytes, res.owner.name) end ``` A row carries the key verbatim — the same string a dispatch names it by and a dispatch-failure message prints — plus its `kind`, its `bytes`, its extent and `format` where it has them, the `usage` bits it was created with, and the frame it was created on. `owner` is read back out of the key (`<shader-guid>::<name>#<serial>`), so a resource nothing has ever dispatched over still names the shader that made it. `compute.resources(ref)` narrows to one shader's — including the `<shader-guid>::__params` uniform the compile created for a `params:` block, which the shader owns like any other resource. `r.totals.bytes` is the `compute` figure of `renderer.gpuMemory()` — the two are read off the same registries, so a listing accounts for the category exactly. The same reading is served at `/zero/runtime/compute`. When a key names nothing, `compute.diagnose(key)` says which of the states the inventory distinguishes it is in, from the closed set `compute.absentReasons()` enumerates: | reason | what the inventory read | |---|---| | `resident` | a resource is filed under exactly this key; the row is on `resource` | | `replaced` | the owner holds the same name at a different serial — `current` names the live key | | `nameUnused` | the owner holds resources, none under this name | | `ownerAbsent` | no live resource carries this key's owner | | `unowned` | the key carries no owner segment, and nothing is filed under it | | `notPublished` | no renderer has published an inventory, so no key can be answered for | So a key out of `[compute] dispatch '…' failed` resolves against what exists, and a typo reports which part of it the engine could not match rather than coming back empty. A reason is the inventory at the moment the call read it. The reading is republished on a frame where a registry gained or lost an entry, so a resource created and diagnosed inside one script sees the reading from before it was made; wait a frame and ask again. ## Discovery - `asset.list("computeShader")` — every registered compute shader. - `asset.inspect("<name>")` — status, source, parse errors, this README. - `computeRef:getBindings()` — the parsed `bindings.yaml` schema (`{ bindings, params }`). - `compute.programState(ref)` — whether the program is compiled, still compiling, or failed, and why. - `compute.observe()` — every GPU resource compute holds, and what it costs. - `compute.diagnose(key)` — whether a key names a live resource, and why not. - `profiler.gpuFrame()` — what each dispatch of this shader spends on the GPU. A dispatch is timed under `compute.<identity>` — the same identity `asset.resolve` takes, so a timing row names the shader that produced it. ## Common pitfalls - **Compute shaders don't render** — verify output via a buffer readback or a debug pass, not a screenshot. - **`ref:compile()` returns before the program exists** — the pipeline is built on the render side; `compute.programState(ref)` says when it is `"ready"`. A dispatch issued before that is held behind the compile and dropped only if the compile never lands. - **A dispatch call returning true means queued** — ask `ref:status()` whether it ran. - **A destroyed buffer is refused where it is bound** — a handle outlives its storage, and `buf:alive()` reports which. - **Binding order is the contract** — `buffers` and `resources` bind in `bindings:` list order; reordering the list reorders the bindings. - **Don't write `@group`/`@binding` in `shader.wgsl`** — the engine owns them; re-declaring is the fastest way to a layout mismatch. - **Don't infer a mesh's vertex stride** — declare `kind: vertices` and use the accessors. A wrong stride writes positions correctly and normals into the wrong word, which renders as flat lighting rather than as broken geometry. - **Storage-texture format must be storage-compatible** — `r32f` / `rgba8` / `rgba16f` / `rgba32f`; others are rejected at compile. - **A key that comes back empty is not the same as one that failed** — `compute.diagnose(key)` separates a name never used from a generation that was replaced, and names the live key in the second case. ## Related types - `.shader`: render-domain shaders (surface, sky, post-process, screen). ## In the Inspector Selecting a compute shader opens its **Compute** section: whether its program is ready (and why not), how many dispatches it has run and failed in this session (and the last error), tables of the bindings and params its `bindings.yaml` declares, and openers for `shader.wgsl` and `bindings.yaml`.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_checker A checker of 64 cells across, 0.8 on 0.03: the high-frequency background a fast object crosses. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# postReference_colorChecker The 24 patches of the ColorChecker Classic, each its published sRGB value read as linear reflectance. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# denoiser (asset type) A denoiser filters the noisy image a render pass wrote into a quieter image of the same size, by passes it adds to the frame being drawn. Every denoiser implements the `denoiser` interface (`@builtin::interfaces.denoiser`), so a render feature that takes one as a setting calls any of them the same way. ## What a denoiser holds ``` myFilter.denoiser/ init.luau # the parameters and the four members README.md # how it filters .metadata # description and tags myFilter_pass.computeShader/ # the compute shaders it dispatches (any number) ``` `init.luau` returns a table: | Key | What it is | |---|---| | `settings` | Optional. The denoiser's parameters, as Field descriptors (`Field.scaled` ones follow the device's quality level). | | `denoise(owner, ctx, signal, opts, values)` | Adds the passes that filter `signal` to `ctx` at `opts.phase`, from `opts.order`, and answers the guid of the filtered image. `values` are the parameters in force: each setting's default, then `opts.values`, at the quality level in force. | | `orders(owner, values)` | How many consecutive orders `denoise` takes with these values. | | `restart(owner)` | The owner's next `denoise` starts from its own frame. | | `free(owner)` | Frees what the owner holds. | `owner` keys everything the denoiser keeps from frame to frame. A render feature's passes run once for every view the frame draws, so history kept in history targets (`renderer.texture.create { history = true }`) is kept per view as well. `~.<name>` inside the folder names the denoiser's own compute shaders, wherever it is installed: ```luau local temporal = asset.resolve("~.myFilter_temporal", "computeShader") ``` ## Using one ```luau -- a render feature's settings denoiser = Field.interfaceRef("denoiser", "@builtin::systems.denoising.svgf", NoSync, "The denoiser the noisy term goes through."), -- in render(ctx) local d = ctx.settings.denoiser:as("denoiser") local clean = d:denoise("myFeature", ctx, noisy.guid, { phase = "afterOpaqueLit", order = 20 }) local nextOrder = 20 + d:orders("myFeature") ``` `@builtin::systems.denoising.svgf` is the built-in one.
▲ 0↑ born
·
assettype · born here
❒asset
# texture An **image asset** — the raw bytes of a `png` / `jpg` / `jpeg` / `hdr` / `ktx2` / `webp` / `bmp` / `tga` file. A loose image written into the world is imported into a `<stem>.texture/` container (see "Internal layout"). > New to how a texture exists as an asset, as CPU-side pixels, and as a live GPU > texture (and how `renderer.texture.*` and render targets move between them)? > Read `core/resource-model` first. `texture` is a first-class assetType (not a bare plural-dir category) so that: - a texture has a stable asset **identity** and an explicit `asset_type` link, and - a material that references a texture records a real `.refs` edge to it — which is what lets the CPU-residency system cascade from a material to the textures it actually uses. ## CPU residency vs GPU residency A texture can be resident two fundamentally different ways, and they must not be conflated: - **CPU residency** (this assetType): the raw image **bytes in memory** — readable, hashable, decodable. You can operate on the bytes. - **GPU residency**: those bytes uploaded to the device as a GPU texture the renderer binds/samples. Byte-level reads are **not possible** on the GPU variant — that is simply how the device works. GPU residency is managed separately and is **not** part of this assetType. Same texture identity, two separate residency states, two separate operation sets, two separate reference counts. ## Internal layout A `.texture/` holds these files, and its child set is open. `asset.create("texture", name, ...)` and the **texture importer** (which creates through it when a loose raster image lands in `/source/`) produce this shape: ``` <name>.texture/ source.<ext> the retained source raster — see below source.ztex the full-resolution texels a cook dropped some of — see below settings.yaml the texture's settings — see below data.ztex canonical pre-encoded + pre-mipped payload (ZTEX magic) .metadata what data.ztex holds and was encoded from ``` `asset.create` keeps a copy of the image bytes it was given as `source.<ext>`; the importer moves the uploaded image in under its own name instead (`foo.png` stays `foo.png`). Either way it is the texture's retained source: rewriting it re-encodes `data.ztex` from the new pixels, and a rewrite carrying the bytes `data.ztex` was already encoded from changes nothing. An encode of a `normalMap` texture states the source's mean tilt, the angle in degrees from +Z of the mean decoded normal, as `meanTiltDegrees` in the `encoded` record of `.metadata` (`renderer.texture.normalMapTilt` reads it from any source image or payload). A map centred on its surface reads near 0; a map whose whole surface leans reads the lean, and every surface it covers leans by it. Above 3 degrees the encode raises the notice `notices.texture.normal_map_tilted`, which names the texture and its tilt. `data.ztex` is the **preferred primary**: when present the renderer resolves and uploads it verbatim — no re-mip. When absent the primary falls through to a raster image in the folder, so a container holding only an image file reads that image. That fallthrough takes the lowest-named raster image in the folder and never the rendered preview, which is made from the payload. A container that lost its encoded payload and holds no other image has no primary: `asset.diagnose(ref)` reports `noPrimaryFile`, `asset.validate(ref)` reports `texture.no_payload`, and `renderer.texture.loadCpu` refuses it. `asset.primaryFile(ref).path` names the file the resolution landed on; the asset-system guide covers `diagnose`. #### `settings.yaml` settings A texture's settings are declared in `settings.luau` and live in its `settings.yaml`. `asset.create` stamps them when the texture is made, and `texRef:setSettings({ ... })` (or `asset.setSettings(ref, patch)`) changes them. Editing an encode-relevant one re-runs the encode against the retained source and rewrites `data.ztex`. ```lua local tex = asset.create("texture", "hero_albedo", { bytes = png, ext = "png", settings = { maxDimension = 1024 }, }) tex:setSettings({ uastcRdo = "medium" }) ``` | key | values | default | meaning | |-----|--------|---------|---------| | `textureType` | `color` / `normalMap` / `mask` / `sprite` | `color`, or guessed from the name | what the texture holds, recorded in the payload. `normalMap`: tangent-space normals — when `generateMipmaps` builds the chain, every level of it, the base included, is renormalised to unit length; with `generateMipmaps = false` the one stored level is the source as given, and the chain the GPU builds from it at upload is a plain box filter. `mask`: linear data (roughness, metallic, occlusion, height, masks). `sprite`: a 2D image with transparency. A new texture's type is guessed from its name — `_normal` / `_nrm` / `_n` / … → `normalMap`, `_rough` / `_metal` / `_ao` / `_height` / `_mask` / … → `mask` — unless it is given. | | `colorSpace` | `srgb` / `linear` | follows `textureType`: `srgb` for `color` and `sprite`, `linear` for `normalMap` and `mask` | how the stored values are read when sampled. `srgb` for albedo/emissive/base-color, UI and sprites; `linear` for normal/RM/AO/height/mask data. | | `compression` | `uastc` / `rgba8` / `rgba16` / `rgba32f` | a new texture: `uastc`, a `sprite` `rgba8` | what the texels are stored as — see "What each compression stores" below. | | `effort` | `fastest` / `fast` / `thorough` | `fastest` | how long a `uastc` encode searches for each block — see "Block compression" below. | | `uastcRdo` | `none` / `low` / `medium` / `high` | `none` | how far a `uastc` encode moves from the source to make a payload that compresses smaller on disk and over the network — see "Block compression" below. | | `generateMipmaps` | `true` / `false` | `true` | bake the full mip chain into `data.ztex` at encode time. | | `maxDimension` | integer, `1` to `8192` | a new texture: `4096` | the longest side the encoded texture may have; a larger source is halved until it fits. A value past 8192 is refused. | | `filter` | `linear` / `nearest` | `linear` | sampler filtering recorded in the payload. A material slot and a UI image widget sample the texture with it. A post-process effect's texture property, a render pass's `@texture` input and a compute shader's `texture_2d` binding sample through a sampler of their own (the effect's `postprocess.setSampler`, the pass's, the compute shader's named `sampler` binding), which this setting does not change. | | `wrapU` | `repeat` / `clamp` / `mirror` | follows `textureType`: `clamp` for `sprite`, else `repeat` | how a material samples the texture past its left and right edges: tiled, the edge texel held, or mirrored. Recorded in the payload. | | `wrapV` | `repeat` / `clamp` / `mirror` | follows `textureType`: `clamp` for `sprite`, else `repeat` | the same, past its top and bottom edges. | | `anisotropy` | `world` / `1` / `2` / `4` / `8` / `16` | `world` | samples taken along a surface seen at a grazing angle. `world` follows the `render.anisotropy` world setting (`renderer.setAnisotropy`); a number fixes it for this texture, clamped to what the device supports. A `nearest` texture samples with 1. A write may give the number itself (`anisotropy = 8`); it is stored as the string. Recorded in the payload. | | `alpha` | `input` / `premultiplied` / `none` | `input` | what the encode does to alpha. `input`: kept as the source has it (straight alpha). `premultiplied`: colour multiplied by alpha — decoded to linear light, multiplied and re-encoded for an `srgb` texture, multiplied as stored for a `linear` one — the source a material with the `premultiplied` blend mode (`src + dst * (1 - src.a)`) composites. `none`: every texel opaque, colour kept. | | `alphaIsTransparency` | `true` / `false` | follows `textureType`: `true` for `sprite`, else `false` | fill every fully transparent texel with the average colour of its non-transparent neighbours, spreading outward, so bilinear filtering and mip averaging never pull black into the edge of a transparent area. Alpha stays 0. Runs before `alpha` and before the mips. | | `keepCpu` | `true` / `false` | `false` | keep the decoded pixels in the CPU store after the GPU upload — see below. | The type's colour space, `alphaIsTransparency`, `wrapU` and `wrapV` are stamped when the texture is created, and a later write that changes `textureType` moves them with it, unless the same write names them. A cook that drops texels — a `maxDimension` smaller than the source — keeps the full-resolution input as `source.ztex` (one RGBA8 level) when the container holds no source image, so raising `maxDimension` later re-encodes from every texel. A cook that drops nothing keeps nothing extra. A texture made from raw pixels whose cook dropped nothing keeps its payload as its only source, so a settings change re-encodes from that payload read back with straight alpha: what an earlier encode discarded stays discarded, after `alpha = none` its alpha is opaque, and a `uastc` payload re-encoded is the blocks' texels, not the pixels first given. A new texture's settings start from the texture type's own defaults — `uastc` with a `maxDimension` of 4096; `rgba8` for a `sprite`; a 16-bit PNG or `.hdr` source left to the schema's `rgba8` unless a layer names a compression — and a world's Preset Manager rows for `texture` override them (a world that ships at 2048, say), then an importer's settings, then the `settings` the create names. `filter`, `wrapU`, `wrapV` and `anisotropy` say how the texture is sampled, not what its texels are. A write that changes only those rewrites the payload's header (`renderer.texture.withSampler`): every level keeps its bytes, and no preview is rendered, because no pixel changed. Every material slot samples through its own texture's state, so two textures on one material can wrap and filter differently. UI image widgets honour `filter` and draw each image over its own bounds, so the wraps apply to materials. A post-process effect, a render pass `@texture` input and a compute shader sample through samplers of their own, so none of the four settings reaches them. `keepCpu` is a lifecycle setting, not an encode input — it never re-runs the encode. It acts on an already-materialised texture right away instead: `true` loads the decoded pixels into the CPU store when the texture is GPU-resident, `false` drops a resident CPU copy. The `data.ztex` payload is a `ZTEX` magic, a 32-byte header and the mip levels; the CPU encoder is exposed to Luau as `renderer.texture.*` and consumed by the texture importer and this assetType. #### What each compression stores | `compression` | In `data.ztex` | On the GPU | Limits | |---|---|---|---| | `uastc` | UASTC 4x4 blocks, whole mip chain, one byte per texel, each level compressed for storage. | Transcoded at upload to a block format the adapter samples: `Bc7RgbaUnorm[Srgb]` where it samples BC textures (desktop native, desktop WebGPU), ASTC 4x4 where it samples ASTC and not BC (phones, a browser on one), ETC2 RGBA8 where it samples only ETC2, each one byte per texel; RGBA8 at four bytes per texel on an adapter that samples none of them, and for a texture whose first level is not whole 4x4 blocks. | the texture keeps its own size; each level is the one above halved (rounded down, at least one texel). A first level whose sides are not multiples of four is not whole 4x4 blocks, which a device's block formats are addressed in, so it is resident as RGBA8 texels. | | `rgba8` | From an image with `generateMipmaps = false`, a `maxDimension` the image fits within, `alpha = input` and `alphaIsTransparency = false`: the source PNG / JPEG / WebP itself, decoded at load. Otherwise raw 8-bit RGBA with the encoder's box-filtered mip chain. | `Rgba8Unorm` / `Rgba8UnormSrgb`, four bytes per texel. | none | | `rgba16` | Raw 16-bit unsigned normalized, one level. An image is decoded at its own depth: a 16-bit PNG keeps every bit, an 8-bit channel `v` is stored as `v * 257`. The frames of an animated image are decoded at 8 bits. | `Rgba16Unorm` where the adapter grants 16-bit normalized textures (native); half float (`Rgba16Float`, about 11 significant bits) where it does not (every browser). | one level, no `maxDimension`, `linear` only. | | `rgba32f` | Raw 32-bit float, one level. An image channel is stored as its value over the channel's maximum. | `Rgba32Float`. Where the GPU filters 32-bit float, every consumer samples it. Where it does not (every browser): a material slot draws the shader's declared default; a UI image draws nothing; a render pass naming it as an `@texture` input is skipped; a compute shader that declares no sampler binds it and reads it with `textureLoad`, and one that declares a sampler refuses the dispatch — each logging once, naming the texture and its format. CPU reads (`:load()`, `renderer.texture.decode`) return every bit on every device. | one level, no `maxDimension`, `linear` only. | A high-precision compression turns `generateMipmaps` off, `maxDimension` to 8192 and the colour space to `linear` when the same write does not name them, and refuses a write that names a contradicting value. #### Block compression `compression = "uastc"` stores every mip level as UASTC blocks — sixteen bytes per 4x4 texels — a format no GPU samples directly but every one can be handed: at upload each level is transcoded to a block format the adapter samples, BC7 on a desktop GPU and ASTC 4x4 on a phone's (ETC2 on one that samples ETC2 alone), so one payload is resident at one byte per texel on each, and RGBA8 on an adapter that samples none; `renderer.textureMemory().blockFormat` names the format this adapter holds it in. Only the levels a device keeps are transcoded: under a texture-size cap (`renderer.setMaxTextureSize`) a texture is uploaded from the first level of its chain within the cap. Compression is lossy, which makes it the choice for colour, normal and detail maps; `rgba8` holds a texture exactly, which is what pixel art and a mask whose exact codes matter need. `effort` is how long the encode searches for each block. `fastest` tries one candidate for an opaque block, `fast` takes about 6 times as long and `thorough` about 17 times, each landing closer to the source texels. What the GPU holds is the same size at every effort, and so is the time a load takes. `uastcRdo` trades accuracy for a payload that compresses smaller: `none` encodes each block as close to the source as the encoder finds, and `low`, `medium` and `high` let a block move further from the source when a nearby block's bytes would let the payload compress better. What the GPU holds is the same size either way; what moves is the size of `data.ztex` on disk and over the network, and the encode time, which a pass more than doubles. The encode runs on the CPU when the texture is created or a setting that decides its texels changes. A call from a task that can yield cooks off the frame and the task waits for it, so the world keeps running: a 1024x1024 texture with its mip chain takes about a second on a desktop CPU. A texture whose settings say `rgba8` is never compressed. ## Reading an asset from its ref `texRef:settings()` reads the container's settings with every schema default filled in and `texRef:setSettings({ maxDimension = 1024 })` patches them; `texRef:load()` decodes the payload's pixels into the CPU store for per-pixel access, `texRef:handle()` puts the texture on the GPU under the asset's own guid, and `texRef:preview()` renders it as a swatch. `texRef:info()` reads the compiled `data.ztex` payload's header: the format it was compiled to — also as its `compression` and `colorSpace` — the `textureType`, `alpha` and `alphaIsTransparency` it was encoded under, its width and height, its mip and array-layer counts, the sampler recorded in it (`filter`, `wrapU`, `wrapV`, `anisotropy`), and, for an animated sequence, each layer's display time and the length of one pass: ```lua local info = texRef:info() print(info.width, info.height, info.format, info.mipCount) ``` It answers off that payload's own header, so a compiled texture reports how big it is for a header read where `load()` decodes its pixels and `handle()` uploads them. A container whose primary is a source image answers `(nil, err)`, and `load()` reads its size. The `compression` and `colorSpace` it reports are what the payload holds; the settings table holds what the encode was asked for. ## In the Inspector Selecting a texture opens its **Texture** section right below the asset's identity, then its Settings. The section draws the encoded texture through the texture's own sampler, so a `filter = "nearest"` texture reads crisp at every zoom. The zoom row offers **Fit** and each integer zoom (1×, 2×, 4×, 8×) whose drawn size fits 512 px; a 128 px texture offers up to 4×, and one wider than 512 px offers Fit alone. Below the view, the section lists every field of the `data.ztex` header (`texRef:info()`) — size, format, mip levels, filter, layers, and a sequence's frames and duration — and the GPU memory the encoded mip chain takes across its layers. The filter and the other encode settings change in the Settings section; the Texture section reports the re-encoded result.
▲ 0↑ born
◐
material · born here
❒asset
# Animated Color An opaque, back-culled surface whose colour animates over time, driven by `@builtin::shaders.animate_shader`. Starts from a white base colour (`1.0, 1.0, 1.0`) with an `emissive` of `1.0` so the shifting colour reads brightly, at mid roughness (`0.5`) and fully non-metallic (`metallic 0.0`). ## Inputs - `colors.base_color` — the starting colour the animation modulates. - `floats.emissive` (`1.0`) — self-illumination strength of the animated colour. - `floats.roughness` (`0.5`) — matte diffuse spread. - `floats.metallic` (`0.0`) — dielectric, non-metallic surface.
▲ 0↑ born
·
assettype · born here
❒asset
# Service (asset type) A **service** generates content you don't have yet — a 3D mesh, an image, a PBR material, a sound effect, a humanoid animation, a navigable splat world — from the inputs each operation declares, landing it as an asset in your world. When nothing in `asset.list` fits what you're building, a service is where new content comes from. A `<name>.service/` is a **declaration**, not code. The asset type ships the whole runtime — the metered invoke, the submit → poll → download → write pipeline, the async generation handle, error handling — in its `shared.module/`. An instance only declares its surface: which provider **offering** it meters, and the **operations** it offers. There is no HTTP, polling, credit, or secret code in a service. ## Using a service Every service is used the same way, whatever it generates: ```luau local mesh = asset.resolve("mesh_gen", "service") mesh:operations() -- callable operations, each with its inputs + credit cost mesh:cost() -- credits the next run costs (estimate) mesh:balance() -- credits you have local g = mesh:invoke({ prompt = "a wooden treasure chest" }) --> { id, task, asset_path, operation } -- async: the run is still going local row = tools.use("services", "status", { id = g.id }) -- poll until it settles -- once row.status == "completed", row.asset is the spawnable asset ``` `:invoke` returns immediately with a handle; the run finishes in the background. The `services` toolbox (`status`, `jobs`) is the agent-facing way to track a run to completion, and a completed row's `asset` is the asset to spawn — see the generating-assets-and-content guide. The handle's `asset_path` is where the run directs the raw generated file, which the importer turns into the asset that row names. A run outlives the engine that started it. The gateway keeps the job and its result for hours after the charge, and the run keeps its own record in the world — what it was asked for, the job doing the work, and the step it had reached — so when the world next loads, every run that did not finish is picked up where it left off and lands its asset the way an uninterrupted run does. Nothing is submitted, or paid for, a second time, and nothing is asked of the caller. A service with several operations selects via `input.operation` (`mesh:invoke({ operation = "from_image", image = "/zero/source/.../ref.png" })`); a single-operation service just takes its input. ## Asking a service for an answer Some operations produce an answer rather than an asset: a verdict, a classification, a completion. `:call` runs such an operation directly and returns the answer to the caller, with no run behind it: ```luau local text = asset.resolve("describe", "service"):call({ instructions = "Answer in one word.", content = "Name a colour.", }).value ``` Each step is one request on the caller's connection, answered at the provider's speed, metered like any call. Nothing is filed: no gateway job, no run record, no file, no `services.status` row. `value` is what the operation's result names; `bound` holds every value its steps bound. Inputs are checked the way `:invoke` checks them, and `asset_path` / `durable` are refused, since nothing is written. A run (`:invoke`) is what keeps a paid result safe through a crash, so an operation that produces an asset runs; one whose answer is the point is called. An offering with no `.service` is called the same way through `require("@builtin::modules.serviceCall")`: `call(offering, endpoint, opts)` for an endpoint that answers in one response, and `stream(offering, endpoint, opts, onEvent?)` for one that answers as a stream, such as the language-model offering `origozero/llm` (`chat`). `stream` returns the whole answer once it settles (`text`, `events`, `charged`) and hands each event to `onEvent` as it arrives. ## Authoring one ```luau -- <name>.service/init.luau local Service = asset.containing(__FILE__).modules.shared return Service.define({ name = "<name>", description = "Generate <thing> from a text prompt.", offering = "<provider>/<name>", -- the offering ZeroMind meters output = { kind = "mesh", ext = "glb", dir = "/zero/source/generated/meshes" }, operations = { generate = { description = "What this makes, agent-facing.", input = { prompt = { type = "string", required = true } }, cost = 5, steps = { … }, -- the pipeline (see below) result = { url = "$url" }, -- the framework downloads + writes it }, }, }) ``` An operation takes exactly the fields it declares in `input`, plus the `operation`, `asset_path` and `durable` the framework itself reads. A call carrying any other field is refused by name — ahead of the credit pre-flight and ahead of any endpoint — with the fields the operation does take named in the message, so a field the steps have no `$ref` for costs a message rather than a run. An operation that declares no `input` states nothing about its surface and takes any field. An input declaring `enum = { "2k", "4k", "8k" }` accepts those values and no others, and the set is published on the input so a reader learns it from the listing rather than from a refusal. A value outside it is refused with the same timing as an undeclared field — before the credit pre-flight, before any endpoint. That timing is the point where a pipeline spends per step: a value the last step's upstream rejects is one the earlier steps were already charged for. An input declaring `dimensions` takes an image size as a `WIDTHxHEIGHT` string in pixels, inside every bound the declaration states: `multipleOf` (each edge), `maxEdge`, `minPixels` / `maxPixels` (width times height) and `maxAspect` (the long edge over the short one). The words `also` lists (`also = { "auto" }`) are accepted beside a size. It is refused with the same timing for any other value, and the refusal names every bound, so a size the provider would refuse costs a message: ```luau size = { type = "string", dimensions = { multipleOf = 16, maxEdge = 3840, minPixels = 655360, also = { "auto" } }, } ``` A set may hold strings or numbers (`enum = { 24, 30, 60 }`), and a value matches only a member equal to it: the number `30` and the string `'30'` are different values, and the refusal quotes strings and leaves numbers bare so it reads that way. Whenever the provider honours a fixed set of values for an input, the set is its `enum` and the input's `desc` says what the choice does to the result, so the values a reader learns and the values the call accepts are one list. An input declaring `min` / `max` accepts numbers inside that span and is refused with the same timing for a figure outside it. Either bound stands on its own: `min` alone is a floor, `max` alone a ceiling. Both are published on the input beside `enum` and `default`. A span an upstream honours belongs here for the same reason a value set does: a figure the pass that reads it refuses is one every earlier pass has already been paid for. ### Declaring the pipeline `steps` is an ordered list of metered calls. Each step: - `call` — the offering's logical endpoint name. - `body` / `params` / `headers` — templated. `"$name"` injects an input or a prior step's bound value; `"${name}"` interpolates inside a string (a missing value drops the key); `"$name?"` is optional. `{ fromFile = "$path", dataUri = "image/png" }` sends a local asset; `{ firstOf = { a, b } }` uses the first present value; `{ scale = "$n", by = 1000 }` multiplies a number; `{ truncate = "$text", to = 64 }` clamps a string to at most that many characters, for an upstream that caps a field's length; `{ whenSet = "$n", use = true }` sends `use` when `$n` was named and drops the key when it wasn't, for an upstream that reads one field only while a companion flag is on — naming such a field alone is otherwise accepted, charged for, and ignored. - `poll` — when the call submits a job: `{ endpoint, param }` plus optional `idFrom` / `statusFrom` / `done` / `fail` / `doneWhen` / `failWhen` / `progressFrom` overrides (sensible defaults cover the common providers). - `bind` / `bindFrom` — name the value later steps reference; `bindFrom` extracts it (a dotted path, a fallback list `{ "a", "b" }`, or an array-find `{ find = "assets", where = { type = "x" }, get = "url" }`). For a polled step the default bind is the submitted job id. `result` is either `{ url = "$bound" }` (download the URL and write it) or `{ bytes = "$bound" }` (write bytes a step returned directly). `output` sets where the asset lands (`<dir>/<safe(prompt)>.<ext>`); a caller's `asset_path` overrides it. The run writes the file at that path and imports it like any other, so the completed row names the asset the importer produced. A path ending in an asset type's extension (`clips/door.soundClip`) names that asset: the file is written beside it under `output.ext` (`clips/door.mp3`) and imported into it. Two destinations keep the written file as the result: one inside another asset's folder, which is that asset's own content (a `.package` holds assets of their own, so a file inside one imports as usual), and a file no importer claims. The derived name is a truncation of the request, so several runs can derive one name — the same line under two voices, two prompts that open on a shared phrase. The framework hands each run a name no other run holds and no file in `<dir>` already spends, appending `_2`, `_3`, … when it must, and the handle's `asset_path` is the name that run will write. So a set of related generations can run at once and each result is readable at its own path. The written file is then imported, and the name is derived by the rule the importer names an asset with, so the name a run reserves is the name its finished asset carries. Read `mesh_gen` as the worked template: `asset.resolve("mesh_gen","service"):getDefinition()`. ## Discovery - `asset.list("service")` — every registered service. - `asset.resolve("<name>","service"):info()` — offering, output, operations. - `asset.resolve("<name>","service"):operations()` — each operation's inputs + cost. ## Related types - `.module` — reusable library code you `require` and call. - `.tool` — an agent-callable function that composes multiple engine steps. - `.component` — per-entity behaviour. ## In the Inspector Service: what the service does and each operation it offers, with its credit cost and inputs, parsed from its declaration without running it. Invoking an operation spends credits, so it is not offered here.
▲ 0↑ born
·
assettype · born here
❒asset
# serviceRun The durable record of one service generation — what was asked for, which gateway job is doing it, and what state that job reached. A generation is charged when it is submitted and then runs for minutes on the gateway, which keeps the job and its finished result for hours afterwards. The engine running the generation is the part that does not last: it can be restarted, rebuilt or closed while the provider is still working. A run asset is what survives that, so the answer to "what did I start, and where did it get to" outlives the process that asked. Every run carries the `jobId` its work is running under. That is the handle the result is reached by when a run's engine did not live long enough to collect it — `services.attach(jobId)` finishes a job that was already paid for, at no further cost. ## Shape `run.json` holds the record, and the same fields are mirrored onto `.metadata` so a run is findable by query without being opened: - `id` — the run handle `services.generate` returned - `service`, `operation`, `prompt` — what was asked for - `jobId` — the gateway job the work is running under - `status` — `submitted` / `polling` / `completed` / `failed` - `assetPath` — what it produced, once it has ## Reading them `services.jobs()` lists runs and `services.status(id)` reads one. Both answer from these records, so both keep answering after a restart. ## In the Inspector Run: which service and operation the run asked for, the status it reached, its gateway job, its error when it failed, and a link to the asset it produced. The ref answers `record()`, `jobId()` and `finished()`.
▲ 0↑ born
◐
material · born here
❒asset
# backdrop_sky The sky material of the `example_own_shaders` example: `backdrop_sky.shader` at its own default values. A sky-domain shader draws on the sky behind everything, so its `preview.png`, rendered on the preview studio's sphere, shows a flat colour; the look it gives is the sky the material backdrop draws.
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# Scene (asset type) A scene is a saved, loadable snapshot of an entity scenegraph inside a world: the entity hierarchy, transforms, components, lighting, and a declared `player` intent, plus an auto-discovered startup script. A scene is the unit of "level" or "screen" — a title screen, a lobby, a gameplay area, and an end-of-game summary each get their own scene. Scenes load as **layers**. One root scene is active at a time; additional scenes can load additively as overlays on top of it. Each scene owns its own multiplayer relay room. Switching scenes is a local call: the client that makes it leaves the old scene's room and joins the new scene's room. ## When to use one - You want a savable, re-loadable snapshot of an entity scenegraph plus its lighting and player setup. - You want a runnable starting state for a level or screen. - You want a scenes-as-data flow: `layers.load("lobby")`, edit live, then `layers.active:save()` to publish the edits back to the scene. For a reusable entity assembly (a prop, a vehicle, a UI panel) that many scenes spawn into themselves, use a `.bundle`. A scene is a whole-world snapshot; a bundle is one prefab that lives inside scenes. ## Folder shape A scene asset is a folder ending in `.scene`. Its identity is the folder name with the suffix stripped (`Lobby.scene` → `Lobby`). - `scene.json` — the scenegraph: `entities[]`, lighting, and the top-level `player` intent. **Required.** Written by the engine — a build, a save, a human dragging something in. Not hand-edited. - `build.luau` — what the scene is made of, written as code. Runs while you author; saving bakes its result into `scene.json` (see Building a scene). - `entrypoint.luau`: the startup script. **Required.** Auto-discovered as a sibling of `scene.json`; define lifecycle callbacks here (see The entrypoint). - `<name>.<type>/` — an asset the build makes, authored here by `build.asset` (see The assets a build makes), alongside `.build.assets`, which records which `build.luau` produced each of them. - `prefabs/` — optional subfolder for scene-local bundles. - `scripts/` — optional subfolder for scene-local Luau helpers, required from `entrypoint.luau`. - `README.md`: notes about THIS scene: what it shows or plays and what it is for. **Required.** The general scene model lives here, in `guides { path: "types/scene" }`. - `.metadata`: **Required.** `scene.json` is version 7. It carries `"format": "scene"`, `"version": 7`, an `entities[]` array, and a top-level `"player"` string intent. ## The `player` intent Every scene declares how it handles players with a top-level `player` field in `scene.json`: - `"spawns"` — the scene carries an authored player setup, and the engine spawns a player for each connecting user from it. This is the default for a freshly created scene. - `"none"` — the scene spawns no player and authors no camera. Author your own Camera entity for the view (menus, UI-only screens, cinematics). ### How `"spawns"` works A `"spawns"` scene authors two things in `scene.json`: 1. A **PlayerPrototype** — an entity carrying the `PlayerPrototype` component, whose `body` field names a child entity (the body). The body carries an avatar (an `Asset` pointing at an avatar, e.g. `@builtin::avatars.humanoid`). A `CameraRig` child carries a `Camera` with a camera behavior (e.g. `orbital_follow`). The prototype root is authored `PrototypeOnly` so it exists as a clonable template. 2. A **PlayerSpawn** — an entity carrying the `PlayerSpawn` component, whose `prototype` field names the PlayerPrototype to instantiate and whose transform is where players appear. The scaffolded scene groups these under two organizing entities, `PlayerSetups` (holding the prototype) and `Spawns` (holding the spawn), so the authoring tree stays legible. On each user join — entering play, and each subsequent connect — the engine runs the spawn for that user: - It clones the PlayerPrototype subtree. - The clone root becomes the user's **internal identity** — a registry-only entity named `user` carrying the `UserIdentity` component. The identity is the anchor for who the player is; it has no world presence. - The body named by `PlayerPrototype.body` is adopted as the user's **avatar** — their visible presence in the world — and placed at the PlayerSpawn's world transform. Move the PlayerSpawn (or drag it in the editor) to set where players appear. - The `CameraRig`'s Camera follows the bound avatar. The player prototype is live in edit mode so you can see and adjust it. In play mode it is deactivated and marked internal — it stays a clonable source while each user gets their own clone. ### Reaching the live player The player surface lives on the root scene's registry, `layers.active.players`: - `players.localPlayer` — this client's player, a curated handle. - `players.localReady` — `true` once the local player's avatar is bound (or the scene opted its avatar out). - `players:list()` / `players:count()` — the players connected in this scene's room. - `players:get(userId)` — a connected player by account id. - `players:ownerOf(avatar)` — the player whose body is a given avatar. A player handle is a data record about who the player is, plus a link to their body: - `player.avatar` — the body's entity ref. Act on the body through it (`player.avatar.position`, raycasts, rig access). - `player.isLocal` — whether this client owns the player. - `player.ready` — whether a live avatar is bound. - `player.userId` / `player.identity` / `player.displayName` — the player's account identity. - `player.avatar = ref` — bind a live body entity as the player's body (assign nil to clear). To use a `.bundle` / `.avatar` asset, spawn it into the world first, then bind the resulting entity. The player's identity entity is the internal anchor; the handle exposes the body (`player.avatar`) and the player's data, and reaching for `.entity` / `.id` / `.component` raises with a redirect to `player.avatar`. ## Building a scene `build.luau` declares what the scene holds. It is ordinary engine code — `entity.spawn`, `component.add`, transform writes, `for` loops, a `require` of a module that computes a layout — and what it creates is what ends up in the scene. ```lua function content() for i = 0, 4 do local crate = entity.spawn("crate") crate.localPosition = { i * 2, 0.5, 0 } crate.component.add("Model", { model = asset.resolve("cube", "mesh") }) end end ``` The build runs while you author, in **edit** mode, and what it created lands in the live scene. Saving the scene bakes it into `scene.json`, which is what makes the entities durable content: a human can select and inspect them, they replicate, and they are there when the world opens without `build.luau` running at all. Play mode never runs it — in play the entities load from `scene.json` like anything else the scene holds. **Editing the file rebuilds the scene in place.** Writing `build.luau` is the signal; there is nothing to reload, and the rebuild saves. An entity keeps the id it had, so a reference to it — a spawn naming a prototype, another entity's component naming this one — survives every rebuild. Add a crate to the loop and the other four do not move. A write through `write_file`, `edit_file` or the engine's `bash` answers once the rebuild it started has finished, so what the rebuild landed and kept comes back on that answer as a notice, whose `message` is the report's summary line: ``` [info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main", editorOnly="1", kept="1", message="build.luau against the scene: kept 1 value on 1 entity (crate_3); ..." } ``` A rebuild still running when the write's wait ends is named under the answer's `startedWork`, and its notice arrives on a later call. An edit saved while a rebuild is still running is an edit to code that rebuild has already read, so it gets a rebuild of its own once that one finishes, and says which it was: ``` [info] a write to build.luau arrived during a rebuild and was rebuilt after it { content="7", scene="scenes.main", editorOnly="1" } ``` Several edits saved during the same rebuild get the one run after it, which reads the file as it stands then. A scene that declares a build also runs it when it **loads** in edit, so the scene shows what the code says now, including an edit made while the world was closed. A load whose `.build.state` records the current script reads `scene.json` as the build and runs nothing. When the load does run it, a world's own scene saves the result, unless the scene holds unsaved edits: those stay the author's to keep or discard, and the file write waits for their save. A library scene (one under `/libs/`, the `@builtin` library included) is read by its load: the build lands in the live scene and its files stay as the library states them. Play reads `scene.json`, so it comes up without that build until `:build()` saves it. ### The two surfaces - `content()` — the scene's own entities. Present in play. - `editorOnly()` — entities present while authoring and absent in play. They carry the `EditorOnly` participation the runtime deactivates and hides when play begins, and they are baked too, so a collaborator opening the world sees the same ones. Anything an author needs to see and a player does not goes here — an alignment guide, a spacing marker, a debug volume. Both are optional. A scene with neither has no build. ### What a rebuild touches Only the entities the build itself placed. Anything a human dragged in, or a tool placed directly, is invisible to a rebuild and never moved or removed. Within what it owns, the build is authoritative: an entity the code stopped emitting is despawned, a component it stopped adding is removed. A plain rebuild keeps a hand edit to an entity the build placed: a value `build.luau` states the way the last build stated it is left as the scene holds it, so a move, a rename, an attribute, the active flag, the lifecycle mode, the replication scope or a component field changed since survives the rebuild, the one a write starts included. To see every such edit, ask the build for its report: ```lua local report = layers.active.asset:build({ save = false }) print(report.message) -- opens with one line counting all four lists ``` On a scene already holding what the build states it leaves nothing to save, and it answers `kept` (hand edits to entities the build placed), `driven` (fields another component writes at runtime, such as a sky orienting the sun), `handAdded` (components and attributes added by hand to built entities) and `handPlaced` (entities no build placed). An entity's render layer and its `hide()` switch are runtime state no build sets, so the lists leave them out; the answer states what the scene holds on both for the entities a build placed instead, in `renderLayers` (`{ entity, name, layer }`) and `hidden` (`{ entity, name }`), and its message counts them ("render layer set on 3 (...); hidden by hide() 0"). It also names the scene it compared: `client` is the client of the world it ran in (`user`, or a sub-client's id), since every client holds its own live scene, and `unsaved` lists the edits that scene held beyond the saved `scene.json` (the entries `sceneAuthoring.changes` lists), so an empty `unsaved` makes the report a statement about `scene.json`. To land `build.luau`'s values over the kept ones: ```lua layers.active.asset:build({ restate = true }) ``` A restate writes exactly the values `kept` names, so the scene's diff after one is the report. To bring a `handPlaced` entity into the build, delete the hand-made one and save the scene, then write it into `build.luau`: the write rebuilds at once in every client and the writing client saves its rebuild, so a delete left unsaved in another client can come back. A hand-made entity still standing under a name the build now places is reported with `builtTwin`, a second copy beside the build's, and the message names the calls that settle it. The message also compares the report against `scene.json` as saved: it names each unsaved edit and what it changed, and any entity whose live state differs from the scene's files with no unsaved edit behind it (a write this client has not taken), with the calls that take that client back to `scene.json` before anything saves from it. `guides { path: "core/scenes-as-code" }`, "What a rebuild touches", gives the shape of every entry and how `driven` and `restate` meet. The build writes its own name and each entity's place in the hierarchy onto the entity, and `scene.json` records that pair beside the entity's name and transform — which is why a rebuild after a reload, in a later session, lands on exactly the entities it placed the first time without anything having been remembered. ### When the file did not change `:build()` runs the build against what it resolves right now — for the case where something the builder *reads* changed and the file did not: a module it requires, an asset it resolves. After a write it is unnecessary; the write has already run it. ```lua layers.active.asset:build() -- rebuild and save layers.active.asset:build({ save = false }) ``` It answers with how many entities each surface placed — `{ content = 6, editorOnly = 1 }` — and with nil for a scene that has no `build.luau`. Called while a build for that scene is already running, it returns at once with `{ inFlight = true, scene, trigger, startedBy, message }` naming that build instead of starting a second one; `inFlight` is what tells the two answers apart. An operation the bake cannot hold is **refused** rather than applied. A build accepts what its records carry: entity lifecycle, transforms, hierarchy, names, visibility, active state, participation mode, network scope, attributes, and components with their public data. Anything else raises while the build runs, naming the operation and the build it answered to, instead of leaving the scene depending on something no reload brings back. When that happens the previous build stays exactly as it was. A runtime resource a build needs — a mesh it generates, a texture it writes — is made as an asset instead, below. Everything else a refusal names goes outside the builder, or into a component the builder attaches, which runs at play. ### The assets a build makes `build.asset(type, name, produce)` makes an asset the build's content names — a mesh a lathe produces, a texture a pattern writes. `produce` takes nothing and returns the creation parameters `asset.create` takes for that type; the call returns the asset's `AssetRef`, which is what a component field holds. ```lua function content() local tower = build.asset("mesh", "tower", function() local positions, indices = lathe(profile, 16) return { positions = positions, indices = indices } end) entity.spawn("tower").component.add("Model", { model = tower }) end ``` The asset is authored inside the scene's own folder — `Lobby.scene/tower.mesh` — and the scene records which `build.luau` produced it in `.build.assets`. So `produce` runs when the build script changed and never otherwise: a reload re-runs the build and reuses the asset, while editing the profile re-authors `tower.mesh` **in place**, keeping its path and its guid. That is what holds the reference — `scene.json` names assets by guid. For a part of a scene that several scenes place — or that one scene places many times with different settings — see `guides { path: "types/sceneModule" }`, which is the same idea with declared `inputs` a placement sets. `guides { path: "core/scenes-as-code" }` covers both. ## The entrypoint `entrypoint.luau` is the scene's **runtime** — what happens while the game is being played. What the scene *is* comes from `build.luau` above; nothing here has to construct it. `entrypoint.luau` is auto-discovered as a sibling of `scene.json`. The loader runs it in a fresh environment and folds its top-level `function name(...)` declarations into the matching scene lifecycle event. Define the callbacks the scene needs — the recognised set: - `onLoad()` — the scene loaded in **play** mode. Gameplay-start hook, runs on every connected client. - `onHostLoad()` — the scene loaded in **play** mode, on the client that owns the scene's synced content (the relay room creator; offline and single-player count as host). Fires once. Entities spawned here — and anywhere downstream — become synced automatically, so this is where shared world content is spawned: it runs on exactly one peer, and every other peer receives the entities from the relay snapshot. - `onEditLoad()` — the scene loaded in **edit** mode. Custom per-scene authoring tools. Writing this file while the scene is loaded in edit mode reloads its layer, so the new `onEditLoad` runs after the previous load's `onUnload`. - `onUnload()` — before the scene's entities are torn down. Extra cleanup; engine-managed teardown (entity despawn, resource release) runs separately. - `update(dt)` — per frame in play mode, while the gameplay clock runs. - `editorUpdate(dt)` — per frame in edit mode, running or paused. Play-paused ticks neither hook. The scene loader partitions these strictly on mode; a component's hooks of the same name read `engine.paused` instead, so the two rules differ — `man components` has that table. - `localPlayerReady(player)` — once the local player's avatar is ready. Gameplay wiring for the local player: attach state, bind UI, swap the avatar. The avatar is already placed at the PlayerSpawn, so this is for behavior, not positioning. - `playerJoined(player)` — a remote player joined this scene's room. Use for per-player UI (nameplates, greetings). The local player arrives through `localPlayerReady`. - `playerLeft(eid)` — a remote player left this scene's room. Receives the departed entity's id (the entity is already despawned). Each scene's entrypoint runs in its own environment, so two scenes can declare the same top-level names without clashing. Keep each callback short; push per-scene logic into `scripts/` modules and `require` them. ## Layers Scenes load through the `layers` namespace. - `layers.load(ref, opts?)` — load a scene. `ref` is a scene AssetRef or identity string. Without `opts.additive`, this is a **root** load: it replaces the current root scene. `opts`: - `additive` — load as an overlay alongside the current root instead of replacing it. - `persistent` — keep an additive overlay mounted across mode flips and root swaps. - `origin` — a `{x, y, z}` world offset for the overlay's entities. - `deferred` — spread the entity spawn across frames (for thousand-entity scenes); the load signals complete only once the scene has settled. - `layers.active` — the current root scene proxy (nil before any load). - `layers.list()` — every loaded layer (root + additive overlays). - `layers.find(ref)` / `layers.is_loaded(ref)` — look up a loaded layer by ref. - `layers.onLoad(cb)` / `layers.onUnload(cb)` / `layers.onBeforeLoad(cb)` — subscribe to every scene load / unload (distinct from a scene proxy's own `:on_load` / `:on_unload`, which fire only for that scene). A root scene carries the `players`, `camera`, and `settings` surfaces; additive overlays inherit the root's players and lighting and do not carry their own. ### The scene proxy `layers.active` (and `layers.find` / `layers.list` entries) returns a scene proxy: - Fields: `.guid` (canonical identity), `.name`, `.path`, `.asset`, `.additive`, `.visible`, `.state` (`"loading"` → `"loaded"` → `"ready"` → `"unloading"`), `.ready`, `.players`, `.camera`, `.settings`, `.entrypoint`. - `.camera` — a proxy over the scene's primary camera entity; read and write the live Camera component through it, and `.camera.behaviors._list()` enumerates the available camera behaviors. - `:save(opts?)` — publish the live scenegraph to canonical `scene.json` (see Saving). A convenience that forwards to the scene ASSET's `save` (`self.asset:save(opts)`): the proxy is the runtime view and owns nothing on disk, so persistence lives on the asset. - `:reload()`: unload and reload the same scene (a runtime respawn). A scene with a `build.luau` runs its build again and saves the scene, so `scene.json` holds what the reload built and the next play loads it; a library scene's rebuild lands in the live scene alone. - `:clearDirty()` — discard unsaved edits and respawn from canonical. Forwards to the scene asset's `discard` (`self.asset:discard(opts)`). - `:sceneAsset()` — the durable `AssetRef<scene>` this live layer maps to. - `:promoteDirty()` / `:writeDirty()` / `:hasDirty()` — manage the dirty overlay directly. - `:unload()` — despawn the layer and free its slot. - `:onReady(cb)` — fire once the scene reaches `ready` (latched: a late subscriber fires immediately). ## Multiplayer & relay rooms Every scene has its own relay room, keyed by the world guid, the boot profile, the mode, and the scene guid. Switching scenes with `layers.load` runs a room transition — leave the old room, tear down, join the destination scene's room — all on the client that made the call. Teardown of the old scene never leaks to peers in the new one. In play mode connected to a relay, the scene's entities are host-authoritative: only the room creator instantiates them (marked synced), and every joiner receives them from the relay snapshot rather than spawning their own. This is why shared world content belongs in `onHostLoad` — spawning it in `onLoad` would run on every peer and duplicate it. Each player's own avatar spawns per-user from the PlayerSpawn on every client. Edit mode and offline boots spawn locally and never auto-sync. ## Loading and saving **Loading** — `layers.load(ref)` for a root scene: 1. Despawns the current root scene's non-persistent entities. 2. Instantiates the entities from `scene.json` (including the player prototype and spawn for a `"spawns"` scene). 3. Applies lighting and sky. 4. Runs `entrypoint.luau` and fires lifecycle callbacks as their events occur. **Saving** — persistence lives on the scene ASSET. `sceneRef:save()` writes the scene's current state back to canonical `scene.json`; when the scene is loaded it captures the live scenegraph, and when it is not loaded it promotes the pending dirty overlay. `layers.active:save()` is the convenience form — it forwards to the active layer's mapped asset (`layers.active.asset:save()`). Writing canonical is the only path that does so: edit ↔ play cycles never save, so hitting play to test never overwrites the scene. Between saves, live edits accumulate in a per-scene dirty overlay that the loader merges on top of canonical. `sceneRef:discard()` throws the overlay away and restores the saved state — deleting the overlay, and respawning the live layer when the scene is loaded. It works whether or not the scene is loaded, because the overlay belongs to the asset, not the runtime layer. `layers.active:clearDirty()` forwards here. Saves capture entity data, not the entrypoint script — edits to `entrypoint.luau` and `scripts/` are always preserved. `opts.to` on `save`/`discard` targets a different scene ("save as"), taking either a bare name (`"level_2"`) or a full VFS path. **What a record states.** A component's record in `scene.json` holds the fields that instance's configuration states: the keys of the table it was added with (a `build.luau` call's own init table, or the record it was loaded from) and every field written since, through code, a tool or the inspector. A field nothing set stays out of the record and takes the component's declared default each time the scene loads, so changing that default reaches every entity that left the field to it. To have an entity follow the default again, remove the field from its record. A field set on a live entity after its record was made is a change the scene review names (`sceneAuthoring.changes` lists it as `+ Type.field = value`), and accepting it writes the field into the record. A stored value cannot be told apart from one an author chose, so a stored value loads and saves as it is, and a hot reload that changes a default one of them shadows names it. A stored field the component no longer declares is named by a `[component.add]` warning when the record loads and left out of the next save. ## Lighting Lights are ordinary entities: a directional light, an ambient light, and a sky are entities carrying `Light` / `ProceduralSky` components in `scene.json`. Author, move, and tune them like any other entity. If a scene is missing any of {directional light, ambient light, sky}, the loader adds a temporary default for the absent one so a scene never loads dark or skyless; the defaults are never saved into the scene. Scene-level lighting state that is not an entity — clear color and sky descriptor — lives under `layers.active.settings.lighting` (`clear_color`, `sky`); writing those fields updates the engine live. ## Modes Scenes load in both edit and play mode (see `man modes`). The mode governs behavior: - An entrypoint's `update(dt)` runs in play while the gameplay clock runs, and its `editorUpdate(dt)` runs in edit. A component's hooks of the same name follow the clock rather than the mode — `man components` has the four states that produces. - Player prototypes are live in edit and deactivated + internal in play, where each user instead gets a clone. `EditorOnly` entities follow the same edit-live / play-internal toggle. - `onLoad` / `onHostLoad` fire on a play-mode load; `onEditLoad` fires on an edit-mode load. ## How to create one ```luau asset.create("scene", "<Name>") -- Creates /zero/source/<Name>.scene/ with: -- build.luau where this scene's content is written. A new one starts -- with the sun / ambient / sky lighting and the "spawns" -- player setup, commented for editing — everything else the -- scene comes to hold is written here too. -- scene.json what that code produces, baked. -- entrypoint.luau commented lifecycle-callback stubs. ``` A freshly created scene has a player with a following camera on the first press of play. It carries no ground, so the first thing to author is what the player stands on — a `content()` line away in `build.luau`. ## Discovery - `asset.list("scene")` — every registered scene. - `asset.inspect("<name>")` — entity count, lighting summary, source path, and this type README. ## Authoring conventions - Keep static layout in `scene.json` — geometry, lights, props, the player prototype and spawn. - Keep dynamic setup in `entrypoint.luau` lifecycle callbacks — event listeners, gameplay state, services attached to spawned entities. - Spawn shared, synced world content from `onHostLoad`; spawn each player's own gameplay wiring from `localPlayerReady`. - Set the world's startup scene in `/.world_settings` — that is the scene the world boots into. - Y is up; -Z is forward. - Renaming the folder changes the scene's identity. References to the scene are recorded against the scene itself, so renaming or moving it does not break them. ## Related types - `.bundle` — reusable entity hierarchies that scenes spawn into themselves. - `.service`: a declarative content generator a scene can draw on. - `.world_settings` — picks the startup scene and world-level renderer / physics options. ## In the Inspector Selecting a scene opens its **Scene** section, read from `scene.json` without loading the scene: how many entities it holds, how many of them are roots (and their names), how players join and the file's format version when it states them, and whether the scene has edits not yet saved.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# Preset (asset type) A preset is a named set of typed values for one declarer's settings schema: the texture assetType's, an importer's, a component's, any asset that declares its own settings. Capture the settings something has now, then apply them to anything the same declarer governs, instead of setting the same values by hand each time. ## When to use one - The same settings recur across many assets or entities (e.g. "pixel art": every sprite texture with `filter = nearest` and no mipmaps; a tuned locomotion set for every character of one rig). - Designers swap configurations without editing code. - A configuration needs a stable name other content can refer to. If you're capturing a whole entity assembly, use a `.bundle`. If you're factoring shared logic (not configuration), use a `.module`. ## Where it lives - Source: `/zero/source/.../<Name>.preset/` - Identity: `<Name>` (the `.preset` suffix strips). - Folder shape: - `preset.yaml` — the target and the values. **Required.** - `README.md` — instance documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields (`title`, `description`). **Required.** ## The document ```yaml target: { __ref: "8cc28fc8-ed63-48ee-83a6-15f4192e27e1", type: assetType, name: texture } values: filter: nearest generateMipmaps: false ``` - `target` names the declarer by a guid envelope: `__ref` is its guid; `type` and the plain `name` tell a person reading the file what it points at. - `values` holds only the fields this preset sets. Fields it leaves out keep whatever the asset or component has. A component preset has the same shape, its target the component: ```yaml target: { __ref: "18dfece3-fe1b-4630-b7ad-0996f5043a2e", type: component, name: Locomotion } values: walkSpeed: 1.4 runSpeed: 2.5 ``` ## How to create one ```luau -- Capture what an asset has now: local p = preset.capture("hero_sprite", "pixel_art") -- Capture a component's live values on an entity: local tint = preset.capture({ entity = id, component = "Model" }, "red_tint") -- Both land at /zero/source/presets/<name>.preset/ (an absolute `.preset` -- path lands where it says; `{ overwrite = true }` re-authors an existing -- preset, keeping its guid). -- Or author it directly: asset.create("preset", "pixel_art", { target = "@builtin::assetTypes.texture", -- an identity or a guid values = { filter = "nearest" }, }) ``` Each checks every value against the target's schema and refuses the whole write on any violation, naming each one. ## How to use one - `preset.values(p)` returns `(values, report)`. Every value is checked against the target's current schema: valid fields are returned, and each invalid one is listed by path in `report.rejected`. - `preset.apply(p, into)` writes the valid values into an asset the target governs, or into a component on an entity named `{ entity = <id>, component = <name> }` whose component is the target. A struct group merges field by field; any other field is written whole. Applying to something another declarer governs raises, naming both. - `preset.setValues(p, values)` replaces the whole values table, checked first. Inside an undo operation the write is recorded into it, so undoing the operation puts back what `preset.yaml` held. - A preset is a snapshot, not a live binding: applying it writes values once. ```luau preset.apply("pixel_art", "enemy_sprite") preset.apply("synty", { entity = id, component = "Locomotion" }) local values, report = preset.values("synty") ``` ## Defaults for new things — the Preset Manager A world's Preset Manager rows make a preset the starting point for what is created from then on: ```luau local p = preset.capture("hero_sprite", "pixel_art") -- or asset.create("preset", …) preset.addDefault(p, { filter = "sprites/**" }) -- new things only ``` Each row names a declarer, a preset for it, and a filter. For a declarer, the first row whose filter matches the new thing's path applies. The rows live in `.world_settings` as `[[presets]]` blocks, sync with the world, and are edited in the Settings panel's **Preset Manager** section. **The layers a new thing's settings take**, each over the ones before it, field by field (a struct group merges field by field): 1. the schema's declared defaults; 2. the type's own `settingsDefaults`; 3. the first matching Preset Manager row; 4. the creating importer's settings for the type; 5. the values the caller passed. A component takes its `public` defaults, then the row, then the values the caller passed. **Rows change only new things.** A row's values are stamped into what is created while it stands. Editing or removing a row changes nothing that already exists, and opening a world applies nothing to its saved content. A re-import or an `overwrite = true` re-authoring keeps the settings the asset already holds. **The three creation moments, and what each filter reads:** | Moment | The row's declarer | The filter reads | |---|---|---| | `asset.create` | an assetType whose instances share its schema | the new asset's path under `/source` (`sprites/hero.texture`); a runtime asset reads the path the same call would give a durable one | | an import | an importer | the source file's path under `/source` at its first import (`sprites/hero.png`) | | `component.add` | a component | the entity's hierarchy path, names from the root down joined with `/` (`level/props/crate`) | A component takes a row when it is added in edit mode, and in any mode inside a scene build (a scene's `build.luau`, a `SceneModule` placement). A component put back from existing content (a saved scene, a peer's record, a template, a bundle's hierarchy, what a component's own code adds outside a build) takes none. A rebuild restates a component only when its code states it differently, so a row edit alone changes nothing a build already placed. **Checking what applies:** - `preset.defaults()` lists the rows in order, each resolved, with every problem that keeps it from applying. - `preset.defaultFor(declarer, path)` returns the values a new thing at `path` would take from the rows, and the row that gives them. ## In the Inspector Selecting a preset shows, beside its identity: - **Target** — the declarer as an asset chip and the guid the preset names it by, with a notice when the target changed since the preset pinned it or does not resolve. - **Values** — every field of the target's current schema as its typed control, the way the target's own Settings section shows it. An edit is checked against that schema, written with `preset.setValues`, and is one undo step. A stored value the schema refuses is named with the reason. Beneath the fields, **Apply to selection** writes the preset into every selected asset its target governs and into the target component on every selected entity, as one undo step. Every asset's and component card's Settings section offers **Save as preset**, which captures the values it shows as a preset targeting their declarer and selects it, and **Apply preset…**, which lists the presets targeting that declarer and applies the one picked. ## How the target stays bound - The preset resolves its target by the envelope's guid, and the preset's `.refs` pins that guid together with the target's checksum, so the link survives the target being renamed or moved. The envelope's `name` is never an identity, so the guid is the preset's one link to its target. - Every read re-checks the values against the target's schema as it is now. `report.pinned` is true once `.refs` pins the target; `report.targetChanged` is true while the target's checksum differs from the one pinned, and a field the target dropped or retyped is then rejected by name while the rest still apply. ## Discovery - `asset.list("preset")` — every registered preset. - `asset.inspect("<name>").detail` — `target`, `targetGuid`, `format`, `values`, `rejected`, `pinned`, `targetChanged`. - `asset.validate("<name>")` — `preset.target_unresolved` when the target does not resolve, `preset.value_rejected` for each value its target rejects. ## Authoring conventions - Name presets by the configuration they capture (`pixel_art`, `hdr_skybox`, `synty`), not by the declarer. - Keep `values` to the fields that define the configuration; fields left out stay as each asset or component has them. ## Common pitfalls - **Hand-edited values.** A value the target's schema rejects is reported, not applied, and every edit of the file warns naming it. - **A table-valued component field** (a `Field.table`) is written whole by `preset.apply`, so a preset holding one provides every key of it. ## Related types - `.assetType` / `.importer` / `.component` — the declarers whose settings a preset holds. - `.bundle` — for multi-component / multi-entity assemblies.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
# Error Text A 3D "ERROR" text model used as the visible fallback when an asset fails to load — spawned in place of missing geometry so a broken reference is obvious in-scene instead of silently invisible. Decomposed from `ERRORText.fbx` into this bundle (mesh + material + texture + entity template). ## Composition - Root `error_text` → `Sketchfab_model` → the `ERRORText.fbx` node hierarchy. - Carries the extruded "ERROR" letter mesh, its material, and texture as private subassets. ## Usage Spawned automatically by the engine as the placeholder for an unresolved asset; can also be spawned directly to test the fallback path.
▲ 0↑ born
◐
material · born here
❒asset
# Plastic White A clean white plastic — a non-metallic PBR surface with a pure white base colour (`1.0, 1.0, 1.0`) and mid roughness (`0.5`) for a soft dielectric sheen. Built on `@builtin::shaders.pbr`. Opaque, back-face culled, queue `2000`. ## Inputs - `colors.base_color` (`1.0, 1.0, 1.0`) — the white plastic tint. - `floats.roughness` (`0.5`) — soft, semi-glossy highlight. - `floats.metallic` (`0.0`) — dielectric (non-metal) response. - `floats.emissive` (`0.0`) — no self-illumination.
▲ 0↑ born
·
assettype · born here
❒asset
# Sky (asset type) A sky is the sky of a scene in one asset: a composition of **members**, each an asset whose type implements `applicable`, with the values the sky states for them. One of them is a **backdrop**, a render feature that writes the scene's `Sky` row (`@builtin::systems.sky.backdrops.procedural`, `@builtin::systems.sky.backdrops.material`, or a creator's own); the others are whatever else belongs to the sky, such as clouds. A sky has no parameter of its own: its parameters are its members', by path (`backdrop/timeOfDay`, `clouds/coverage`, `clouds/@enabled`). A member whose parameters follow from content its values name has those too: a material backdrop's parameters are its own (`material`, `exposure`, `rotation`) and the shader properties of the material it names (`backdrop/zenith`, `backdrop/glow_size`), each with the material's value as its default. ## Where it lives - Source: `<name>.sky/` - Identity: `<name>` (the `.sky` suffix strips from the identity) - Folder shape: - `sky.yaml`: the definition. **Required.** - `README.md`: what the sky draws. **Required.** - `.metadata`: `description` and `tags`. **Required.** - `preview.png`: its picture. Optional. ## The definition ```yaml members: - id: backdrop source: "@builtin::systems.sky.backdrops.procedural" values: { timeOfDay: 18.5, zenithColor: [0.2, 0.1, 0.3], horizonColor: [0.9, 0.4, 0.2], horizonHeight: 2 } - id: clouds source: "@builtin::systems.volumetrics.volumetricSky" # Omitted values use the package's complete default weather preset. ``` It is read the way a scene setup's is: the same member grammar, the same diagnostics, nested compositions under their member id. A member's `source` is an identity (`skies.parts.haze`, `@builtin::systems.sky.backdrops.procedural`) or a path with its type suffix: absolute (`/source/skies/parts/haze.renderFeature`), from the folder holding this sky (`haze.renderFeature`, `./haze.renderFeature`, `../parts/haze.renderFeature`) or from the world's source folder (`skies/parts/haze.renderFeature`). An identity drops the type suffix, so a sky and a scene setup of one name in one folder share it; their paths name each apart. The scene setup type's README has the whole grammar. A volumetric cloud member's weather is its `preset` table, and a value for it states the whole table. ## Using one A sky implements `applicable`: applied, it applies every member for the owner: ```lua local dusk = asset.resolve("my-dusk", "sky") dusk:as("applicable"):apply("myEntity:sky", { ["backdrop/timeOfDay"] = 19 }) local drawn = sky.drawn() -- { entity, source = dusk, description } dusk:as("applicable"):drop("myEntity:sky") ``` `sky.drawn().description` (the sky's own `describeSky`) is `{ material, timeOfDay, sunDirection, members, notice? }`, built from what is drawn; `notice` is what a member states about the settings it runs, by member path. A procedural backdrop draws its base colours (`zenithColor`, `horizonColor`, `groundColor`) in the shape `horizonHeight` gives them: the elevation in degrees where the sky is halfway from the horizon colour to the zenith colour (default 7.933). A palette whose horizon colour is a band, such as a sunset's orange under a violet sky, lowers it (to 2, say) so the zenith colour shows at eye level. The backdrop draws them while the sun is high and its night and dawn tint sets as the sun sinks, as far as `nightStrength` and `dawnStrength` say; a sky that holds one hour states its look in the base colours with both strengths at 0, and the notice names a set that masks the base colours at the hour drawn. The backdrop's README has the table of which set shows at which hour. A light that follows the sky (`lighting.followSky`) is oriented by a procedural backdrop's hour. **Moon and moonlight.** A procedural backdrop draws its moon opposite its sun, at the hour it draws. After dark a light that follows the sky stands at that moon: a sun that takes its intensity from the sky is out, and a light that keeps its own (`followSkyIntensity: false`) is moonlight at the intensity it states, from where the moon is drawn. A night setup keeps the two together by giving its moonlight `followSky: true`, `followSkyIntensity: false` and a moonlight intensity and colour (a setup nesting a day setup sets its sun's `followSkyIntensity` to `false` and its intensity to the moon's), so the light stands where the moon is drawn. ## A material sky's shader values A sky drawn by a material takes that material's shader properties as parameters, so a sky, a setup nesting it, or a placement states them by path like any other value, and a setup's card lists them: ```yaml # night_variant.sceneSetup/sceneSetup.yaml: the base setup, its sky's glow raised members: - id: base source: "./base.sceneSetup" values: "sky/backdrop/glow_intensity": 2.5 "sky/backdrop/zenith": [0.02, 0.01, 0.08, 1] ``` The backdrop draws the material itself while every value stated for it is the material's own, and a runtime copy of the material with the stated values laid over its own once one differs; the material asset is not written. Two applications of one backdrop are arbitrated the way every render feature's are: the newest that states something new is in force, and dropping it brings back the values of the one before it. ## Making one ```lua asset.create("sky", "aurora", { members = { { id = "backdrop", source = "@builtin::systems.sky.backdrops.material", values = { material = "my-aurora-material", exposure = 1.2 } }, } }) ```
▲ 0↑ born
◐
material · born here
❒asset
# postReference_darkRamp A ramp of light from 0 at the left edge to 0.1 at the right: the dark gradient an undithered 8-bit display path bands on. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
·
assettype · born here
❒asset
# menuTab One tab of the app menu (`appMenu`), the menu the pause action opens: Escape, a gamepad's Start, the on-screen Menu button and a headset's left menu button, in every profile and on every platform. A tab is a `<name>.menuTab/` folder whose `init.luau` returns its spec: ```luau return { title = "Game", build = function(ctx) -- ctx.presentation: "desktop" | "phone" | "vr"; ctx.width, ctx.height: -- the room the body has inside the menu's frame. return { type = "vertical", children = { ... } } end, onCallback = function(id, data) end, -- every callback the body raises back = function() return false end, -- one step back inside the tab onShow = function(ctx) end, -- each time the tab comes on screen } ``` `title` is text, or `{ key = "namespace.key", values? }` for the catalog message the menu says in the player's language each time it draws. A new world's tab reads the library's `app_menu` messages that way. A tab whose body shows state of its own (a settings value, a counter, the page of a sub-menu it is on) changes that state and calls `appMenu.redraw()`: the menu calls `build` again and draws what it returns. It works from `onCallback` and from anywhere else the state changes, a task or a timer included: ```luau local volume = 5 return { title = "Game", build = function(ctx) return { type = "vertical", children = { { type = "label", props = { text = `Volume {volume}` } }, { type = "button", props = { text = "+", onClick = "game:louder" } }, } } end, onCallback = function(id) if id == "game:louder" then volume += 1 appMenu.redraw() end end, } ``` The menu builds the tab it shows afresh each time it opens and each time a tab is selected, so a change made while the menu is closed shows when it opens. The body is an ordinary widget tree, the one `ui.registerScreen` takes, so a tab looks the way its world draws it. The menu draws the frame around it: Resume (back to the world), Enter or Exit VR, Recenter in a headset, and the tabs, across the top on a desktop, along the bottom on a phone, and along the bottom edge of the panel in a headset. Which tabs the menu counts is decided by where the asset lives: - **The world's own source** (`/source`, outside `libs/` and `deps/`): the world's tab, shown first as the World tab whatever the folder is named. A new world starts with one, `menuTabs/game.menuTab`, which the world rewrites for its game. A world with none shows its title, Resume and the way to another world. - **The built-in library**: the engine's tabs, ZeroMind (`@builtin::menuTabs.zeromind`) and System (`@builtin::menuTabs.system`). - **Anywhere else**, another library or the dependency tree of a world installed into this one: nothing. An installed world brings its content and no menu of its own. Opening the menu pauses nothing: every world is shared, and keeps running. Menu tabs stay out of search.
▲ 0↑ born
◐
material · born here
❒asset
# Lit Checkerboard A static, lit checkerboard surface built on `@builtin::shaders.lit_checkerboard` — the default ground material for newly seeded worlds. It uses a neutral light-grey base colour (`0.85, 0.85, 0.85`) with a grey emissive tint (`0.35, 0.35, 0.35`) so the pattern stays readable in dim scenes, high roughness (`0.7`), no metallic, opaque, and instanced. ## Inputs - `colors.base_color` (`0.85, 0.85, 0.85, 1.0`) — neutral grey checker palette. - `colors.dark_color` (`0.35, 0.35, 0.35, 1.0`) — the dark square colour, close enough to the base that the pattern stays readable in low light. - `floats.roughness` (`0.7`) — mostly diffuse surface. - `render.instancing` (`true`) — supports instanced draws.
▲ 0↑ born
·
assettype · born here
❒asset
# Test Suite (asset type) A **test suite** is a registrable asset that bundles one group of automated engine tests. Each `<name>.testSuite/` folder holds an `init.luau` whose body registers a suite (and its tests) against the test framework this **type** ships in its `shared.module/`, reached with `asset.containing(__FILE__).modules.shared`, plus a `README.md` describing what the suite validates. Test suites are the engine's regression net. Every Luau-facing system — FFI bindings, components, the renderer, the VFS, multiplayer, the input stack — ships its coverage as one or more `.testSuite` assets. Because a suite is an ordinary registrable asset, a new system or package adds its own tests by dropping a `.testSuite` folder next to its code; nothing central (the runner, the shell script, CI) has to be edited. ## When to use one - You added or changed a Luau-facing capability and want a permanent regression guard for it. - You fixed a bug — add a test that reproduces it so it can't silently come back (the `bug_regression` suite is the canonical home for one-test-per-issue guards). - A package or system ships behavior that should be validated on every CI run. If you just want to *manually* exercise something once, use `execute` directly — don't author a throwaway suite. ## Where it lives - World suites: anywhere under `/zero/source/`. - Package / system suites: anywhere under the package, e.g. `…/voxelEngine.package/tests/voxel_grid.testSuite/`. - Identity: the folder stem (`strip_suffix: true`), e.g. `vfs`. Suite **names must be unique** across the whole tree — the runner and CI key on the stem. ## Folder shape ``` <name>.testSuite/ ├── init.luau # registers the suite via Test.describe / Test.it ├── README.md # what this suite validates + how to run it └── .metadata # agent-editable tags + free-form fields ``` The type declares only those three files and does not set `allow_unlisted`, so a suite may ship fixture files (helper `.module` folders, sample data) alongside `init.luau`, but `asset.validate` reports each one as a `structure.unexpected_file` warning. The warning does not block publishing. ## How to construct a new suite 1. Create `<name>.testSuite/init.luau`. Reach the framework the type ships, then declare the suite with `Test.describe(name, fn)` and each test with `Test.it(name, fn)`. Documentation is authored as doc-comments the engine's doc parser extracts statically: a top-of-file `--!desc` for the suite, and a `--!desc` (what the test checks) plus `--!pass` (the condition that must hold) directly above each `Test.it`. ```lua --!desc Spawn / despawn / exists / find over the entity API. local Test = asset.containing(__FILE__).modules.shared Test.describe("Entity Lifecycle", function() --!desc entity.spawn(name) creates an entity and returns its proxy. --!pass The returned id is a non-empty string and entity.exists(id) is true. Test.it("spawn returns a stable string id", function() local id = entity.spawn("probe").id Test.expect(type(id)).toBe("string") Test.expect(entity.exists(id)).toBe(true) end) end) return true ``` 2. Create `<name>.testSuite/README.md` describing the suite (what system it covers, notable edge cases, how to run just this suite). 3. That's it. No registration step, no runner edit. The next test run discovers the suite via `asset.list("testSuite")`. See `template/` for a copy-ready skeleton (the templater fills in the `[name]` markers). ## How to run tests - **All suites** (writes `/source/tmp/test_results.md` + `.json`; refused in play mode). A bare `run()` covers the world-authored suites; `"*"` adds the baked `@builtin` library: ```lua return tools.use("tests", "run", "*") ``` - **One suite directly** (instance-direct — runs only this suite): ```lua return asset.resolve("vfs", "testSuite"):run() ``` - **From inside the engine** (agent loop): the `tests` toolbox — `tools.use("tests", "list")`, `tools.use("tests", "run", { suite = "vfs" })`, `tools.use("tests", "compare", before, after)` to diff two runs and surface NEW failures. See the toolbox README. A suite whose `init.luau` runs without registering a single `Test.it` with the framework the runner reads has run nothing, so its run fails with a `registers at least one test` record naming the suite. An installed package's suite registers with the same framework the runner reads: the engine runs one copy of the framework its asset type ships, whatever version the package recorded. ## Discovery commands ```lua asset.list("testSuite") -- every registered suite, as AssetRef handles asset.inspect("vfs") -- summary for one suite asset.resolve("vfs", "testSuite") -- handle { guid, identity, path, type } tools.use("tests", "list") -- { count, suites = { { name, identity, path, origin, testCount? } } } ``` ## Authoring conventions - **One suite per asset.** Keep a suite focused on one system; large systems split into multiple `.testSuite` assets (e.g. `zinput_state`, `zinput_events`, `zinput_actions`). - **No `await()` inside `Test.it()`.** The framework runs synchronously; for multi-frame behavior use the per-test context `t.waitFrames(n)` (see the framework README). - **Clean up.** Entities the runner can't attribute are despawned automatically, but prefer `Test.afterEach` for deterministic cleanup. - **Write fixtures via `Test.tmpPath`.** Any file a test writes to the VFS must go under its per-test sandbox: `Test.tmpPath("Foo.component/init.luau")` → `/zero/source/tmp/tests/<suite>/<test>/...`. That root is under `/source/tmp/` (excluded from world saves + multiplayer sync, so it never clogs the synced VFS) and is torn down per-test and again at end-of-run, regardless of pass/fail/crash. Call it INSIDE the test body. For a fixture shared across tests in one block, write under `Test.TMP_ROOT` directly (survives per-test cleanup, still swept at end-of-run). Never hand-roll a bare `/source/<name>` path — it persists and syncs. - **Idempotent.** A suite must produce the same result run twice and must not depend on ordering between suites. - **Never silence the LSP.** No `--!nocheck` / `---@diagnostic disable` in a suite — fix the underlying type/global instead. - **Declare a call that is wrong on purpose.** A test asserting that an API rejects a wrong-typed or wrong-arity call carries `--!expect-error <code>` on the line above that call (`--!expect-error type-mismatch`), which is also how the call runs under the strict gate of `execute`. The checker holds the line to it: once the API starts accepting the call, the directive reports `expect-error-unfulfilled`. A cast to `any` keeps quiet through that change, so the directive is the form a rejection test uses. ## Common pitfalls - **Duplicate stem.** Two `.testSuite` folders with the same stem collide; the runner warns and skips the duplicate, and `--list` fails. Pick a unique name. - **Forgetting `return true`.** Harmless but conventional — every suite ends with `return true`. - **Deferred mutations.** `despawn` / `setParent` / scene clears apply next frame; verify their effects with `t.waitFrames` or a follow-up query, not in the same frame. ## Related types - **`.module`** — reusable Luau library (a suite often requires the system module under test). - **`.tool`** — agent-callable function; the `tests` toolbox tools are `.tool` assets. - **`.component`** — script component; component behavior is frequently what a suite exercises. ## In the Inspector Tests: how many tests the suite declares and their names, parsed without running it, and **Run**, which runs this suite alone in edit mode and reports its passed, failed, skipped and quarantined counts.
▲ 0↑ born
◐
material · born here
❒asset
# Decal Default The default material a `DecalProjector` stamps when none is assigned. A flat cyan tint (`0.05, 0.95, 1.0`) on `@builtin::shaders.pbr`. Assign a material with a `base_color_texture` to project a texture; the projector samples the material's base colour at the box-local XY of every surface inside its projection box.
▲ 0↑ born
·
assettype · born here
❒asset
# inputMap assetType A control scheme, expressed as an asset. A `<name>.inputMap/` folder whose `init.luau` returns the map record, and whose **controls are the `<name>.inputBinding/` child folders beside it** — the same containment a `.toolbox` has with its `.tool` children. Containment records the reference, so a scene carrying its map carries every control it declares. ``` racer.inputMap/ init.luau -- what the map is, and how it composes boost.inputBinding/ init.luau steer.inputBinding/ init.luau ``` ```luau -- racer.inputMap/init.luau return { name = "racer", description = "Throttle, steering and boost.", -- The group these controls belong to, and the groups this map stands -- down while it is live. Declaring neither composes with everything. group = "vehicle", suppresses = { "player" }, } ``` Each control carries `kbm`, `gamepad` and `touch`; the `inputBinding` assetType covers the record shape. ## Reading it A controller activates the map it needs and subscribes to the controls it drives. Nothing is live until something asks for it. ```luau public = { inputMap = Field.assetRef("inputMap", "@builtin::inputMaps.default", NoSync, "The controls this component reads."), speed = Field.number(5, NoSync, "World units per second at full deflection."), jumps = Field.number(0, NoSync, "How many times the jump control was pressed."), } local controls function awake() controls = public.inputMap:activate() controls.move:onInput(function(v, dt, active) if not active then return end local p = public.entity.position local step = public.speed * dt public.entity.position = { p.x + v.x * step, p.y, p.z - v.y * step } end) controls.jump:onPressed(function() public.jumps += 1 end) end function onDestroy() public.inputMap:deactivate(controls) end ``` What `activate` returned is this holder's **claim** on the map. Keep it and hand it back: releasing the claim disconnects the subscriptions made through it, and the map stays live for whoever else holds it. A control the map does not declare reads as `nil`, so a typo raises at the subscribe call. A controller written against more than one map tests for an optional control first — `if controls.crouch then controls.crouch:onInput(...) end`. Several maps can be live at once, and the player's surface is the union of them. `group` / `suppresses` are how one map stands another down — a car takes the player over by naming the `player` group, and walking resumes the moment the car releases. `Zin.scheme.live()` reports each live map's `group`, `suppresses` and `suppressedBy`, and `heldBy` — who opened each activation still standing on it, so a control that goes quiet under a suppression leads to the activation doing it rather than to the map. ## Whose keys a map reads A key belongs to the surface it was pressed on. In the editor, where the scene shares the window with panels, the scene holds the keys pressed while it was the active input context: the last click landed in the viewport's picture (on the scene or on the game's own UI drawn there), or play just started. A key pressed after a click on a panel is the editor's, and a game's controls never see it. A map reads the scene's keys unless it declares otherwise: ```luau return { label = "Editor", group = "editor", surface = "editor", -- every key no focused widget took } ``` `surface = "editor"` is for controls that belong to the editor around the scene — its hotkeys, its viewport camera — and answer wherever the author last clicked. Pads and touch belong to no panel and read the same on either surface. `Zin.scheme.live()` reports each map's `surface`. ## Ref methods - `:activate(label?)` — load every `<name>.inputBinding/` child, validate them, add them to the live binding set, and return the handles keyed by control name. Every fault across every child is reported in one error. Activating a map already live adds a holder, so two components sharing one map read one set of controls — each through its own handles, which are the claim it releases by. Every activation reads the children again, so a binding added, edited or removed since the map came up reaches the running set here and reaches the holders already standing on it. `label` names this activation in `Zin.scheme.live()`. - `:deactivate(claim)` — release one holder's claim, disconnecting every subscription that claim made. The map stays live while another holder remains; the last one out takes the controls out of the live set. Name no claim and the caller's own most recent one goes. - `:controls()` — `{ name, label, kind, classes, problems }` per child, read without activating anything, so an authoring tool can show a map's whole surface and everything wrong with it before it goes live. - `:record()` — the raw record its `init.luau` returns. - `:effective()` — the materialized effective map, without activating it. - `:bindingsFor(name, class)` — the bindings a named entry has for one device class in this map's effective form. ## Writing one The `inputAuthor` toolbox writes a map and its controls together, filling in canonical defaults for a control whose name it recognises: ```luau tools.use("inputAuthor", "map", "racer", { "throttle", "steer", "boost" }, { group = "vehicle", suppresses = { "player" } }) tools.use("inputAuthor", "check", "/zero/source/inputMaps/racer.inputMap") ``` `asset.create("inputMap", name, { record = ... })` bakes a record into both shapes a map is read in — `init.luau` beside one `<name>.inputBinding/` child per entry, each carrying all three device classes, a class the record had nothing for written as `false` with the reason beside it. That is the hook `Zin.map.bake(name)` drives to turn the active effective map into an editable asset. The engine's built-in schemes live under `@builtin::inputMaps.<name>`; `asset.list("inputMap")` lists them with every other map. ## In the Inspector Controls: whether this map is the one taking input now, how many controls it declares, and each control's name, label, kind, device classes and problem count.
▲ 0↑ born
·
assettype · born here
❒asset
# Shader module (asset type) A `.shaderModule` is a block of WGSL that other shaders **include** rather than copy — a lighting model, a set of colour-space helpers, one package's shared prelude. It declares no entry point and is never dispatched or drawn on its own account; it exists to be expanded into the shaders that name it. ## Folder shape ``` <name>.shaderModule/ module.wgsl # the WGSL — helpers, structs, constants (required) README.md # what THIS module provides (required) .metadata # tags and free-form fields (required) ``` Each file carries a committed `.meta` sidecar pinning its stable guid, and the folder carries one of its own. ## Including one A shader names a module by identity, and the identity is what records the dependency — so a shader that is packed, pulled or published carries the modules it includes with it: ```wgsl #include "~.colour" // a module under the same `~.` #include "@builtin::shaderModules.pbr_shading" // one from the builtin library ``` A missing module is a hard error at compile: a shader that names an interface which no longer exists fails loudly rather than compiling against a stale copy. Each module is expanded at most once per shader, so two shaders that both include the same module — or a module that includes another — produce one copy, not a duplicate-definition error. ## Writing one Write only what other shaders need in scope: functions, structs, constants. A module may reference a binding its includers declare, which is how a package's prelude can read that package's uniform block. ```wgsl const LUMA: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722); fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> { let lo = c / 12.92; let hi = pow(max(c + vec3<f32>(0.055), vec3<f32>(0.0)) / 1.055, vec3<f32>(2.4)); return select(hi, lo, c <= vec3<f32>(0.04045)); } ``` ## Answering to another name A module declares extra names it answers to with `@alias` lines in the header of `module.wgsl`: ```wgsl // @alias: colour_helpers // @alias: @mypack::shaderModules.colour ``` Each becomes an alias on the asset, so the name resolves everywhere an identity does: `asset.resolve`, an `#include`, and the publish gate alike. Only the header is read — the scan stops at the first line that is not a comment, so a directive cannot hide in the module body. A name another asset already holds is refused and reported, since an alias extends the identity namespace rather than taking a name out of another asset's hands. ## Registration & hot reload Writing `module.wgsl` registers the module under every name the asset answers to — its guid, its identity, and any alias — so a shader includes it by whichever name it holds. Saving re-registers it and the shaders that include it recompile, with no world reload. ## Discovery - `asset.list("shaderModule")` — every registered module. - `moduleRef:getSource()` — the module's WGSL. ## Related types - `.shader` — render-domain shaders (surface, sky, post-process, screen). - `.computeShader` — compute programs. ## In the Inspector Selecting a shader module opens its **Module** section: how many lines it holds, the aliases a shader `#include`s it by, and an opener for `module.wgsl`.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Sky Equirectangular An equirectangular panorama sky/environment background built on `@builtin::shaders.equirect_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), with adjustable rotation and exposure. Assign an equirectangular image to `sky_texture` (via `material.setTexture` or a Skybox) to display a panorama. ## Inputs - `textures.sky_texture` — the equirectangular panorama image to sample. Falls back to black, so a sky with nothing assigned reads as night rather than as an error. Assign a `.texture` by guid, identity, name, or path: ```luau renderer.material.setTexture("@builtin::materials.sky_equirect", "sky_texture", "my_panorama.texture") ``` An image dropped into `/zero/source` imports into a sibling `<stem>.texture` container and the loose file is removed, so reference the container (or its identity) rather than the original image path. - `floats.rotation` (`0.0`) — yaw rotation of the panorama around the vertical axis. - `floats.exposure` (`1.0`) — brightness multiplier applied to the sampled colour.
▲ 0↑ born
·
assettype · born here
❒asset
# `.font` asset type A `.font` is a first-class font asset: font-file bytes (TTF / OTF / WOFF / WOFF2) converted into a guid-anchored asset via `asset.create("font", name, { bytes = … })`. A font is a **general CPU resource** usable by any text surface. The `onRegister` hook calls the engine `font.register(name, bytes)` primitive, which installs the parsed face into **both** the 2D/3D text system (`text.*`) and the egui UI text system, under the family name the font file itself reports. A registration is what puts the face in the database; whether `fontFamily = "<name>"` selects it is the separate question of whether the shaper matches that name, and `font.reconcile()` answers it per family: ```lua for _, f in ipairs(font.reconcile()) do if not f.selectable then print(f.family .. " is registered but shapes as " .. f.shapedWith) end end ``` `text.face(handle)` gives the same answer for one label. A family the shaper's database holds is selectable under its own weights and for the glyphs its faces cover: a row that reads `familyCoveredNoGlyph` names a family the shaper picks whose faces have no glyph for the text asked of it. `topics/text` covers reading a label that came out in the wrong face. Fonts are CPU resources (not GPU), so the primitive lives in the `font.*` namespace, the CPU analogue of `renderer.texture.create`. ## Layout ``` <name>.font/ data.zfnt the baked payload `asset.create("font", ...)` writes face.json optional: family group, role, aliases, on-demand entries ``` ## Editing a font's files A write to a file the registration reads (`face.json`, `data.zfnt`, or a raw font file in the folder) installs the font again from what the folder now holds. The names the new `face.json` gives it (its group and each alias) select it on every text surface from then on, and a name the earlier descriptor gave it and the new one does not stops selecting it; a changed `group` moves the face to that group. Text laid out under a name the edit decides is laid out again, and a `Text3D` label draws it again on the next frame. For an on-demand face the same holds for the font and coverage files its entries name: the entries are declared again from their coverage files, and an entry already installed is registered again from its font file with the names the descriptor now gives. ## On-demand faces A face whose file is large and whose script most sessions never draw is declared by the codepoints it covers instead of being read at boot. Its `face.json` lists the font files of the folder under `onDemand`, each beside a coverage file: ``` NotoSansCJK.font/ face.json { group, role, aliases, license, onDemand = [ { name, file, coverage }, ... ] } kana.otf a font file (TTF / OTF) kana.coverage the codepoints it maps: "3000-30ff,ff01-ff5e,..." ... OFL.txt the license the files are distributed under ``` `onRegister` reads the coverage files and calls `font.declare(name, coverage, { file, family, role, aliases })` for each entry; no font file is read. The first time a label or a `text.*` object meets a character an entry covers and no installed face draws, the engine requests that entry: its file is read without blocking the frame and registered with `font.register`, and from then on every text surface draws the character from it. `font.onDemand()` reports each entry as `declared`, `requested`, `installed` or `failed`, and `font.prefetch(text)` requests the entries a text needs before it is drawn. `font.coverage(bytes)` writes a coverage file from a font file's character map. Splitting one large face into several entries (by script, and by how common a character is) means a session reads only the part its text reaches: the built-in `NotoSansCJK.font` is cut that way, and a page of Japanese reads its kana and common-ideograph entries alone. Every registered face, on-demand or not, is a per-glyph fallback for every family the UI holds: a character the selected family has no glyph for is drawn from the first face that has one. ## In the Inspector Selecting a font opens its **Font** section: the family the face registers under, its role and aliases from `face.json`, whether the text system has the family registered and, when it holds it, how many faces and which weights. Below the facts, a sample line is drawn in the family at 14, 20 and 32 px.
▲ 0↑ born
·
assettype · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# error_marker The material of the ERROR sign a Model or SkinnedModel shows in place of a mesh that failed to resolve, to become GPU-resident, or to pose. It draws the `error_marker` shader's magenta checker.
▲ 0↑ born
◐
material · born here
❒asset
# Instance Color Unlit An unlit white surface that every instance wearing it colours from its own shader-data lane 2, built on the `unlit` shader with `instance_color_lane = 2`. It draws exactly the picture `Model.tint` gives an unlit surface for the same colour and blend, at the cost of one `renderer.instanceData.set` per member and with nothing replicated, so it is the material for flat per-instance colour that changes every frame: a heat map, a stress readout, indicator lights. ```luau renderer.instanceData.set(id, 2, 1, 0, 0, 1) -- this member red, fully covered renderer.instanceData.set(id, 2, 1, 0, 0, 0) -- back to the material's white ``` The lane's `rgb` is the colour and its `a` is how much of it covers the material's own colour, 0 none through 1 all; a lane never written reads zero and leaves it white. Set `instance_emission` above 0 to add the colour again on top, scaled, for a colour that blooms. ## Inputs - `floats.instance_color_lane` (`2`): the lane read. - `floats.instance_emission` (`0`): how much of the lane colour is added on top where it covers. - `colors.base_color` (white) over `textures.base_color_texture` (`default:white`): the colour under the lane colour.
▲ 0↑ born
▣
module · born here
❒asset
# proc Code-authored, graph-backed procedural generation for the Zero engine. A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`, the returned table is the graph's outputs, and `io.output` is how the graph stands in the world. `builder.module/README.md` holds every rule of that form. This module owns the whole procedural model: the graph builder + data model, the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op implementations. Authored `.procGraph` graphs are persisted via `procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in `procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)` from a script or an agent's `tool_exec` script, or `zero procgen preview` in the shell. Generated meshes/materials/textures/bundles are persisted through their own `.assetType`. An op family can also come from outside this package: a `.procPack` asset registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones shipped here (`proc.registerPack(name, ops)` is what it registers through, and what a test or a tool calls to hold a family for the life of one VM). `terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/` and covering a whole landscape; `guides { path = "systems/terrainSystem/documentation/terrain" }` is its guide. To find out what the registry holds, use the `procgen` toolbox: `searchNodes` searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and `proc.schema(id)` are the same answers in-process, for a graph builder looking something up while it runs.
▲ 0↑ born
◐
material · born here
❒asset
# Brushed Metal A brushed metallic surface built on the `pbr` shader — fully metallic (`metallic: 1.0`) with a neutral grey base colour (`0.6, 0.6, 0.6`) and moderate roughness (`0.3`) that softens reflections into the muted sheen of brushed steel or aluminium. Opaque, back-face culled, instanced, with the `_METALLICSPECGLOSSMAP` keyword enabled. ## Inputs - `colors.base_color` (`0.6, 0.6, 0.6, 1.0`) — neutral metal grey. - `floats.metallic` (`1.0`) — fully metallic. - `floats.roughness` (`0.3`) — softened, brushed reflections. - `textures.base_color_texture` (`default:white`): the white base texture the colour multiplies against, so the surface renders `base_color` alone.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_emitter A flat emitter answering with 16 times the display's white: the source a bloom reading is taken around. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
◐
material · born here
❒asset
# Sky Solid A flat solid-colour background built on `@builtin::shaders.solid_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), filling the sky with a single dark-grey colour (`0.2, 0.2, 0.2`) at unit exposure. ## Inputs - `colors.solid_color` (`0.2, 0.2, 0.2`) — the flat fill colour of the background. - `floats.exposure` (`1.0`) — brightness multiplier applied to the fill colour.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Grass A soft green ground surface built on `@builtin::shaders.grass_material`, with a natural green base colour (`0.22, 0.62, 0.16`), high roughness (`0.75`) for a diffuse, non-shiny look, and no metallic or emissive contribution. It inherits the Rust-side render defaults (opaque, back-face culled, queue `2000`) so its pipeline matches the library variant compiled at startup. It leaves the shader's `sway` at its default of `0`, so it shades whatever geometry it is applied to and leaves every vertex where the mesh puts it; `@builtin::materials.grass_blades` is the same green on a blade mesh that bends. ## Inputs - `colors.base_color` (`0.22, 0.62, 0.16, 1.0`) — the grass green tint. - `floats.roughness` (`0.75`) — matte, diffuse surface. - `floats.metallic` (`0.0`) / `floats.emissive` (`0.0`) — non-metallic, non-glowing.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# population A hardware-instanced population at rest: one mesh drawn at every transform of a baked placement, as ONE draw call per variant at any instance count. The asset is the recipe — which `.mesh` and material each variant draws with, plus the instance matrices as bytes. Its `instantiate` method is what turns that recipe back into a live draw, so a scene records ONE entity for a population of a million instances instead of a million entities. ## Layout ``` <name>.population/ population.json { version, total, variants: [ { mesh, material | materialKey, count, offset } ] } transforms.bin total × 64 B — little-endian f32, column-major mat4 per instance ``` `offset` counts INSTANCES, not bytes: variant *k*'s matrices start at `offset × 64` bytes of `transforms.bin` and run for `count × 64`. Each matrix is column-major, which puts its translation at floats 13/14/15 of the block — the layout the engine reads a transform buffer as `array<mat4x4<f32>>`. The matrices are taken in the space of the entity drawing the population, so it draws where the recipe placed it relative to that entity and moves with it. `mesh` and `material` are asset references (`{ "__ref": "<guid>" }`), so the geometry and material a population draws travel with it in the dependency graph. A variant drawing with a material the renderer's registry holds but no asset backs names it in `materialKey` instead. ## Putting one in a scene ```lua local pop = asset.resolve("forest", "population") pop:instantiate(nil, { position = { 0, 0, 0 } }) -- one entity, one draw call ``` That spawns an entity carrying the `Population` component, which owns the live GPU buffers and draw registrations for as long as the entity lives — a reload replaces them rather than stacking a second set. The same contract is what `Asset { source = <population> }` drives, which is how a baked procgen bundle carries a population: a root record plus one child holding the reference. ## Building one `proc`'s `population.write` sink persists a `Population` value: ```lua local pop = proc.registry.get("instances.draw").eval({}, { instances = iset }, {}).population proc.registry.get("population.write").eval({}, { population = pop }, { name = "forest" }) ``` Or through `asset.create` directly, with each variant's matrices as a flat `count × 16` column-major float array: ```lua asset.create("population", "forest", { variants = { { mesh = meshGuid, material = materialGuid, transforms = flat } }, }) ``` ## Reading and drawing one by hand ```lua local recipe = pop:spec() -- { version, total, variants } local live = pop:draw() -- allocate buffers + register draws print(live:count(), live:drawCalls()) live:destroy() -- drop the registrations, free the buffers ``` The value `:draw()` returns OWNS those resources. Hold it and release it — a registration nobody holds can be neither enumerated nor dropped afterwards. ## In the Inspector Selecting a population opens its **Population** section: how many instances it places, across how many variants, and a table of each variant's mesh, material, instance count and offset, with a link to each variant's mesh.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# 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.
▲ 0↑ born
◐
material · born here
❒asset
# Cubemap Env A chrome-ball environment surface that samples a cubemap for mirror-like reflections, built on `@builtin::shaders.cubemap_unlit`. `reflect_mode` (`1.0`) selects the reflection path, and the `Ryfjallet_cubemap` builtin texture supplies the environment. Opaque, with a white base colour (`1.0, 1.0, 1.0`) so the cubemap colours pass through untinted. ## Inputs - `textures.base_color_texture` (`@builtin/textures/Ryfjallet_cubemap`) — the environment cubemap that is reflected. - `floats.reflect_mode` (`1.0`) — selects the reflection sampling mode. - `colors.base_color` — white tint that leaves the reflected colours unchanged.
▲ 0↑ born
◐
material · born here
❒asset
# Solid Line A flat, opaque line surface with a bright green base colour (`0.0, 1.0, 0.5`) for drawing gizmos, paths, and debug geometry. Opaque, back-face culled, instanced, and rendered in the opaque queue (`2000`). Built on `@builtin::shaders.line_material`. ## Inputs - `colors.base_color` (`0.0, 1.0, 0.5`) — the line colour. - `floats.roughness` (`0.5`) — surface roughness. - `floats.emissive` (`0.0`) — no self-illumination. - `render.instancing` (`true`) — many lines draw in a single instanced batch.
▲ 0↑ born
·
assettype · born here
❒asset
# loadingScreen The screen players see while your world loads, as an asset: a `<name>.loadingScreen/` folder whose `screen.yaml` states the title, a line of text or rotating tips, a background picture, a logo, the colours and how the load's progress is drawn, with its pictures beside it. The world names the one it shows in its settings, and every boot of the world draws it on native, web and Android. ## Make one and show it ```luau local screen = asset.create("loadingScreen", "title", { folder = "branding" }) -- /zero/source/branding/title.loadingScreen/ vfs.write(screen.path .. "/screen.yaml", [[ title: "Skyward" text: "The islands are waking up" tips: - "Hold Shift to sprint." - "Wind currents carry you further." background: background.png logo: logo.png colors: background: "#0b1626" accent: "#7ad3ff" text: "#f2f7ff" progress: bar ]]) world.loading_screen = screen -- writes [world] loading_screen = "branding.title" ``` Put the pictures in the folder (`upload_file`, `vfs.write`, or a generated image saved there), then push the world (`zm add . && zm commit -m '...' && zm push`). The screen is part of the world's content: it is versioned and published with it like everything else, and an unset `world.loading_screen` (`world.loading_screen = nil`) brings back the engine's own loading screen. `.world_settings` holds the choice as an asset identity: ```toml [world] loading_screen = "branding.title" ``` ## `screen.yaml` Every key is optional. A key left out keeps the engine's own loading screen look: the origozero.ai palette, the world's cover picture as a card, its title, and a progress bar with the percentage under it. | Key | Type | What it states | |---|---|---| | `title` | text | Drawn large in the middle. The world's title when left out. | | `text` | text | One line under the title. | | `tips` | list of text | Lines shown one at a time under the text, each for `tipSeconds`. A single text counts as a list of one. | | `tipSeconds` | number | Seconds each tip stays up (default 6). | | `background` | picture | Fills the whole window behind everything, cropped to cover it. | | `logo` | picture | Drawn above the title, 96 pixels tall. | | `cover` | true / false | Whether the world's cover picture shows as a card above the title (default true). | | `status` | true / false | Whether the line naming the step the load is at shows (default true). | | `progress` | `bar` / `percent` / `none` | A bar with the percentage under it (the default), the percentage alone, or no progress. | | `colors` | mapping | `background` (the window), `accent` (the status line and the bar), `text` (title and text), `muted` (tips and the percentage), `track` (the bar's empty part). Each is `#rgb`, `#rrggbb` or `#rrggbbaa`. | A picture is a file name inside the screen's folder (`background.png`) or a path from the world's source root (`/source/art/key.png`). PNG and JPEG both work. A key the type does not take, a colour that is not a colour and a value of the wrong kind are each named in `ref:spec().problems` and in the Inspector, and the screen keeps the default for that key. ## When it shows The engine shows the screen from the moment it knows which world it is loading, before the world's content has synced: it reads the world's published `.world_settings`, `screen.yaml` and pictures from ZeroMind first, which is what a player opening the world sees. A player sees the screen the world's latest push states, so a change to it reaches players with the next `zm push`, and a world that has pushed nothing yet shows its screen once its own content is in place. Once the world's own content is in place, the screen is read again from it, so an editor sees the screen their working copy states. The screen stays up until the window shows the world's first frame, so the handover from the screen to the world shows no black frame. The world's first frame follows the world's `onWorldLoad` returning: work that runs for the whole session goes in a component, a service or a `task.spawn` that `onWorldLoad` starts, and an `onWorldLoad` that keeps running holds the screen up for as long as it runs. A world that names no loading screen, or names one whose `screen.yaml` is missing, shows the engine's own loading screen. ## See it `screen:preview(seconds)` draws the screen over the whole window exactly as a boot of the world draws it, for `seconds` (default 15): the progress fills and the tips change on the screen's own clock. Capture it while it is up: ```luau world.loading_screen:preview(20) -- then: capture { source = "window" } world.loading_screen:preview(0) -- takes it down early ``` ## From a script ```luau local read = world.loading_screen:spec() -- { spec, problems } print(read.spec.title, read.spec.progress, #read.problems) print(world.loading_screen:isShown()) -- true: the world names it ``` ## In the Inspector Loading screen: the title, text, number of tips, pictures, whether the cover card and the status line show, how progress is drawn and the colours, whether the world shows this screen while it loads, every problem that kept a key out, **Preview**, which draws the screen over the window for 15 seconds as a boot does, and **Show while the world loads**, which names this screen in the world's settings.
▲ 0↑ born
·
assettype · born here
❒asset
# `rig` asset type A skeleton, as a composite asset. A rig is its own primitive — not a mesh and not an animation. The folder `<name>.rig/` carries: - **`rig.json`** — the readable skeleton document, the asset's *primary*. Consumers reference the `.rig` asset's guid, never this inner file. It holds: - **`bones`** — ordered bones, each with a `name`, a `parent` index (-1 for a root), the `node` index it maps to, its `rest` local transform (translation / rotation / scale relative to the parent — the bone's offset and length), and its `inverseBind` matrix (16 floats). The `inverseBind` is what skinning reads. - **`bind`** — where the rig's bind pose, the pose retargeting reads anatomy from, comes from: `"skin"` (its inverse binds are a skin's bind, as a model import writes), `"rest"` (it has none: its inverse binds restate its rest, as an animation-only import's rest is the clip's first frame), or `{ "__ref": <rig guid> }` (a skinned rig of the same skeleton whose bind it shares; an animation-only import names one when the world holds it). A rig with no `bind` reads its own inverse binds. - **`overrides`** — what an author set by hand, keyed by avatar type guid: `{ [typeGuid] = { roles = { [role] = boneName | false } } }`. `false` leaves a role empty. Carried across a re-import of the rig's source file. `avatar.map` and `avatar.unmap` write it. The format is JSON, not binary, because a rig is small structural metadata an agent inspects and corrects — the bulk binary `.mesh`/`.animation` carry their own decode paths, but a rig is meant to be read. ## How a rig maps onto an avatar type Which bone is the hips, the left hand, a hair strand, is derived from the bones whenever it is asked for, by the avatar type (see the `avatarType` asset type) — never stored. The skeleton's structure decides it, for any naming and in any pose the rig rests in, and the author's overrides are laid over the result. ```luau local rig = asset.resolve(rigGuid, "rig") local q = rig:qualify() -- the builtin humanoid type; pass another type to ask it print(q.qualifies, q.reason) -- whether it is a humanoid, and why not print(q.mapping.roles.hips) -- the bone filling a role print(q.report.verdict, #q.report.stale) ``` | Method | Returns | |---|---| | `:doc()` | The decoded `rig.json`. | | `:structure()` | The skeleton's structure (`modules.rigStructure`). | | `:qualify(avatarType?)` | Whether the rig qualifies as the type, the effective mapping, and the report (confidence per chain, missing chains, ambiguities, name contradictions, overrides naming bones the rig lacks). | | `:mapping(avatarType?)` | `:qualify(avatarType).mapping`. | | `:isHumanoid()` | Whether the rig qualifies as the builtin humanoid. | ## Read and correct a mapping A character that stands still, bends an arm or a leg the wrong way, or twists as it walks is read and corrected with the `avatar` toolbox, which works on the rig of an avatar, a body bundle or a character standing in the scene: - `avatar.inspect(target)` lists every role with its bone, `detected` or set by hand (`override`), and the confidence of its chain; `{ scores = true }` measures how idle, walk and run retarget onto the body. - `avatar.map(target, role, bone)` sets a role by hand (`false` leaves it empty); `avatar.unmap(target, role)` clears one, or every role set by hand, back to detection. - `avatar.detect(target)` asks every avatar type again and names where detection and the roles set by hand differ. `modules.avatarMapping` is the same from code. `guides { path: "core/avatars" }` has the whole of it. A skinned `.mesh` references a `.rig` (the mesh keeps only per-vertex skin weights; the skeleton lives here). An `.animation` references its source `.rig`. Retargeting maps a clip from its source rig onto a body's rig through the roles both rigs fill. ## In the Inspector Selecting a rig opens its **Skeleton** section: the bone count, the number of roots, whether the rig qualifies as a humanoid with its verdict and confidence, and the bone hierarchy, indented by depth. Its **Mapping** section lists every role with its bone, where the bone came from and its chain's confidence, the report's warnings and the secondary chains, with a role and bone picker that sets a role by hand and actions that detect again, clear the roles set by hand and measure the retarget of idle, walk and run.
▲ 0↑ born
·
assettype · born here
❒asset
# sceneModule — a part of a scene, authored as code A `.sceneModule` is a recipe for scene content: a folder whose `init.luau` declares the inputs a placement may set and returns the function that builds the content. Placing one runs the builder and lands what it built in the scene as ordinary entities — named, selectable, movable, saved in `scene.json`, and replicated like anything else an author placed by hand. ``` CoinPusher.sceneModule/ init.luau -- declared inputs + the build code Coin.mesh/ -- an asset the build makes (see The assets a build makes) .build.assets -- which init.luau produced each of them README.md .metadata ``` The entities are not baked into the folder — the scene holds those. What the folder holds is the code, and the assets that code makes. ## The builder is ordinary engine code ```lua inputs = { seed = Field.number(0, NoSync), coinCount = Field.number(40, NoSync), stroke = Field.number(0.8, NoSync), } return function() local base = entity.spawn("base") base.component.add("Model", { model = asset.resolve("PusherBase", "mesh") }) local pusher = entity.spawn("pusher", { parent = base }) pusher.component.add("PusherDrive", { stroke = inputs.stroke }) math.randomseed(inputs.seed) local coinMesh = asset.resolve("Coin", "mesh") for i = 1, inputs.coinCount do local coin = entity.spawn("coin_" .. i, { parent = base }) coin.localPosition = { math.random() * 1.6 - 0.8, 0.5, math.random() * 2 - 1 } coin.component.add("Model", { model = coinMesh }) end end ``` Real loops, real conditionals, real locals, real `require` — `entity.spawn`, `component.add`, and transform writes are the same calls they are anywhere else. The builder **authors**; components **behave**. A coin pusher's machine, coins, and colliders are construction, so they belong in the builder; `PusherDrive` is runtime logic, so it stays a component the builder attaches. The builder runs inside a capture scope, which records what it created and holds it to the operations that end up in the scene. A build accepts an operation exactly when a scene record carries its result; anything else is refused by name while the build runs — never applied and then dropped, so nothing the builder appears to do goes missing later. A refusal is cheap, so try the thing you are unsure of. The refused call never lands, the build is abandoned whole, and the previous build stays in the scene untouched — one rebuild tells you the answer and costs nothing. `guides { path: "core/scenes-as-code" }` states the rule and works through placing an asset that expands into a hierarchy, such as a `.bundle`. Anything the entry script pulls in uses an absolute require (`require("@builtin::modules.json")`): the script is compiled into its own environment, which is what gives `inputs` its meaning below. That environment holds `inputs` and `build`, and falls through to the engine's global one for every other name, so a builder reaches everything a script reaches anywhere else — `entity`, `asset`, `Transform`, `math`, `require`, `vfs`, `task`, `tools`, `world`, `string`, `table`, `os`, `Field`, `NoSync`. `Transform.quatFromAxisAngle(ax, ay, az, angle)` and `require("@builtin::modules.json")` behave inside the builder exactly as they do outside it, so the engine's own maths and modules are the ones to reach for. A toolbox is reached with `tools.use("wld", "mode")`, the same call it takes anywhere. ## Inputs `inputs` follows the component `public` convention exactly. The table literal **declares** the fields with the same `Field.*` constructors components use, and a read of `inputs.<name>` inside the builder returns the **resolved** value for the placement being built — the param override when the placement sets one, else the declared default. ```lua inputs = { -- a placement that sets nothing builds with 0 seed = Field.number(0, NoSync), style = Field.enum({ "brass", "steel" }, "brass", NoSync), lit = Field.bool(true, NoSync), } ``` The replication mode is the one every component field names, on the same constructors. The placement carries the whole resolved set in one `params` field, which is what replicates, so an input declares `NoSync`. Declare `inputs` as a global, the way a component declares `public`. Reading a name the module never declared raises and lists the ones it does, so a typo says so instead of silently building with nothing. ## The assets a build makes Some of what a module states is an asset rather than an entity — the coin mesh above is one. `build.asset(type, name, produce)` makes it: `produce` takes nothing and returns the creation parameters `asset.create` takes for that type, and the call returns the asset's `AssetRef`, which is what a component field holds. ```lua local coinMesh = build.asset("mesh", "Coin", function() local positions, indices = disc(0.4, 24) return { positions = positions, indices = indices } end) local coinGold = build.asset("material", "CoinGold", function() return { shader = "pbr", properties = { base_color = { 1, 0.84, 0.28, 1 }, metallic = 1, roughness = 0.25, }, } end) return function() for i = 1, inputs.coinCount do entity.spawn("coin_" .. i).component.add("Model", { model = coinMesh, material = coinGold, }) end end ``` The first argument is the type, so a module makes every kind of asset its content names, not only geometry. A material's overrides go in **one `properties` table**, colours as `{r, g, b, a}` arrays; passing a `floats`, `colors`, `ints` or `bools` section name is refused with the shape to use. The producer owns what it makes. Editing a generated asset at runtime — setting a property on the live material, hand-editing its files — leaves it in a state the next produce does not know about. Edit the producer and rebuild. The asset is authored inside the module's own folder — `CoinPusher.sceneModule/ Coin.mesh` — and the module records which `init.luau` produced it in `.build.assets`. So `produce` runs when the entry script changed and never otherwise: every later placement and rebuild reuses the asset, while editing the disc re-authors `Coin.mesh` **in place**, keeping its path and its guid. That is what holds the reference — `scene.json` names assets by guid. This is the answer to a refusal that names a runtime resource: `renderer.mesh.create` makes a GPU mesh that lives as long as the session, which no record can hold, and the same geometry made as an asset is held by every record that names it. ## Placement A sceneModule defines `instantiate`, so it is accepted anywhere a scene-instantiable asset is: an `Asset`-style field gated by `Field.instantiableRef`, a viewport drop, a tool argument. ```lua local pusher = entity.spawn("pusher_0") pusher.component.add("SceneModule", { source = asset.resolve("CoinPusher", "sceneModule"), params = { seed = 0 }, }) ``` `SceneModule` is the placement component: it holds the module the placement is bound to and the params it sets, and it is what re-runs the build. Placing the same module twice with different params yields two different results from one asset, each with its own stable ids. See its README for the full field set. ## Rebuilds hold ids Editing `init.luau`, or changing a placement's params, re-runs the builder in edit mode and **reconciles** the result: an entity the previous build placed is updated in place, one the build no longer emits is removed, and a new one is spawned. Same entities, same ids, updated contents — so a reference to a built entity survives every rebuild. A change is what rebuilds. A placement that already holds a build runs nothing when the scene loads or the mode flips — the entities are there, holding what the last bake gave them. `SceneModule:rebuild()` forces a rebuild for a change nothing else reports, such as a module edited while the world was closed. In play of an editor session the placement builds into the play scene alone and records nothing. A runtime-profile boot builds nothing: the entities are already in `scene.json` and load as authored content, and the placement component is inert. ## Ref methods - `ref:build(params)` — run the builder and return the records, leaving the scene untouched. - `ref:inputs()` — the declared inputs, sorted: `{ name, kind, default, values? }`. - `ref:getInitScript()` — the entry script source. - `ref:instantiate(target?, opts?)` — the uniform placement call. ## In the Inspector Selecting a scene module opens its **Inputs** section: a table of the inputs the builder declares, each with its kind, default and allowed values, and an opener for `init.luau` in the Code panel. A placement sets their values on its SceneModule component.
▲ 0↑ born
◐
material · born here
❒asset
# Glass Clear glass — a smooth, transparent PBR surface with a faint blue tint (`0.9, 0.95, 1.0`) and low alpha (`0.3`). Rendered in the transparent queue with backface culling off (`cull: none`) so both faces of thin geometry show. Built on `@builtin::shaders.pbr`. ## Inputs - `colors.base_color` — tint and opacity (the alpha channel drives how much shows through). - `floats.roughness` (`0.0`) — perfectly smooth; raise for frosted glass.
▲ 0↑ born
·
assettype · born here
❒asset
# assetType (asset type) An asset type says what a kind of asset is: the files an asset of the kind is made of, the code that gives it behaviour, the interface a person uses to work with it, and how it is found, pictured and checked. A `<typename>.assetType/` folder declares a type called `<typename>`, and every `<name>.<typename>/` folder is an asset of it. `assetType` is itself a type, so a type is an asset like any other: it is created, versioned, installed and contributed the same way. ## Making a type `asset.create("assetType", "<typename>")` scaffolds a type. The type registers the moment its folder is written, anywhere under `/zero/source/`, and from then on `<name>.<typename>/` folders are its assets. An asset of a type that is not registered yet is not an asset, so make the type first. A type folder is a root: `~.x` in any file inside it names the type's own `x`, wherever the type is installed. Keep the type's whole implementation inside its folder and reach it that way. What a type folder must hold is set by this type's own `type.yaml`, the same way every type's `type.yaml` sets what its assets hold. `asset.validate` on a type reports anything missing, and the scaffold produces a folder that passes. ## What sets your type's schema (`type.yaml`) `type.yaml` is the structural contract every asset of the type is checked against. The keys below are the ones the engine reads; a key not listed here is ignored. | Key | What it controls | |---|---| | `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. | | `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. | | `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. | | `is_container` | Whether the suffix stays in the identities of what the asset holds. | | `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. | | `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. | | `is_text_default` | Whether the asset's files are text unless stated otherwise. | | `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. | | `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. | | `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. | | `files: { required, optional }` | The files an asset holds (below). | | `allow_unlisted` | `false` reports every file the type does not declare. | | `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. | | `settings:` | Typed per-asset settings (below). | | `inspector:` | The interface people use for the type and its assets (below). | | `preview:` | How an asset is pictured (below). | | `references:` | Names of other assets the type's files carry (below). | | `indexing:` | What search reads for each asset (below). | | `describe:` | How a missing description is generated (below). | ### The files an asset holds Each entry under `files.required` or `files.optional` is `{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches within one segment. Entries that share a `one_of_group` are satisfied by any one of them. `content` lists checks on the file's bytes: | Check | Passes when | |---|---| | `non_empty` | the file has content | | `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape | | `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML | | `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") | Each check takes a `message`, which is what the author is told when it fails. ### Settings `settings: { values, schema: { type | instance, export? } }` gives every asset typed settings. `values` names the file an asset's values live in; `schema.type` declares one schema for the whole type, and `schema.instance` names a file each asset declares its own in. `asset.create` writes the resolved values, and a write to the values file reaches `onChange` with what changed. ## The human side (`inspector.luau`) A type is used by people through its Inspector, and without one the type is usable only from code. The Inspector is the type's interface for a person: for a procedural graph it is the graph editor, for a kit it is the tracking view of what the kit holds and what is still missing. Writing it is part of writing the type. `inspector: { type, instance? }` in `type.yaml` names the files. `type` is the interface for the type itself and for its assets; `instance` names a file an asset may ship to add its own. Each returns: ```luau return { sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } }, replace = { contents = { ... } }, -- replace a default section by id order = { "graph", "contents" }, -- section order } ``` `build(ctx)` receives the asset and builds the section. A section's `title`, and the text its rows carry, is a string or an `i18n.text` value read from a catalog (`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType", ...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a type that names no inspector, or names one that does not load, reports it. ## Say what your type is for (`about.yaml`) Every type carries an `about.yaml` that says what the type is for, in three plain-language texts: ```yaml intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering." function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text." usage: "You choose it by name for your UI or your text, and the text appears in that typeface." ``` - **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes. - **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes. - **`usage`** is what a person or an agent does with one. Up to 1200 bytes. Write about the type as a whole, not one asset of it, and say what it does now. Agents read these texts to learn when to reach for the type and how; people searching find the type by them. The scaffold starts each text with `[[describe]]` and a note on what to write; a text that still starts that way counts as not written. `services describe` can write them. They show up in `asset.inspect` as `detail.about`, in `assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide, and at the top of the type's Inspector. ## Ask your assets to say what they are A type can require each asset to carry a description: a file, written by the author or generated, saying what the asset is and what it is for. Declare it with a `described` check: ```yaml files: required: - path: "README.md" kind: "file" content: - { check: "described", message: "Say what this widget is for and where it goes." } ``` A file that is missing, empty or still has a line starting with `[[describe]]` fails the check, and so does a YAML file whose named `keys` are missing or over their `max_bytes`, or a Markdown file missing a named heading. `asset.validate` names the asset, and a push that carries it is refused with `message`. `services describe` finds such assets and writes their descriptions. `describe:` steers what is generated: ```yaml describe: guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI." examples: - "<identity of an asset of this type whose description reads well>" ``` An example is an asset of your type whose description is a true, written one, never a placeholder and never the asset being described; with none, leave `examples` empty. A type whose assets the model cannot perceive (a sound, a motion) says so in `guidance`, and the description is drawn only from what the asset's own files state. Start the file unwritten in your `template/`: a heading and one line starting with `[[describe]]`, never example content, which every new asset would carry verbatim. A type whose assets say what they are through their own content (a mesh, a texture) declares no check. ## The type's code (`behavior.luau`) `behavior.luau` returns one table. These are the keys the engine reads from it; anything else on the table is the type's own. ### What the type's assets can do | Key | Shape | What the engine does with it | |---|---|---| | `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. | | `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. | | `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. | | `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). | | `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. | | `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. | Some `ref` names mean the same for every type, and the engine calls them: - **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below). - **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below). - **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe. - **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints. - **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode. Some names are answered for every asset before the type is asked, so a `ref` entry of the same name is never reached: `getSource`, `getBytes`, `getText`, `exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`, `gpu_resident`. ### When the engine calls the type | Hook | Signature | When it runs | |---|---|---| | `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. | | `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. | | `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. | | `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. | | `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. | | `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. | | `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. | ### Settings hooks | Hook | When it runs | |---|---| | `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. | | `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. | | `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. | | `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. | | `settingsHealed(values, stored)` | On a read, to repair stored values. | | `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. | `creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options that are inputs to the type rather than settings. ### Reloading An edit to `behavior.luau` reaches existing assets with no restart. ## How an asset is pictured (`preview:`) | `kind` | The picture is | The type provides | |---|---|---| | `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` | | `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order | | `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` | | `custom` | whatever `ref.preview` returns | `ref.preview` | ```yaml preview: kind: surface mesh: sphere ``` `angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop and the framing, so an asset pictures the same in every world. A type with no `preview:` that defines `instantiate` still answers `ref:preview()`. A picture is rendered when something asks to view it (the editor showing the asset, `ref:preview()`), when previews are generated on request (`assets.generatePreviews`), and when the asset is staged. An edit alone renders nothing. The picture records what it was made from, so a stale one is told from a current one. ## The names your type's assets hold (`references:`) Where your type's own format or API carries the name of another asset, declare it here: ```yaml references: keys: # a top-level key of the type's files that holds a name, or a table of them - { key: "shader", type: "shader" } args: # an argument of a call, counting from 1 - { call: "g:node", position: 2, type: "procNode" } fields: # a field of the options table a call takes - { call: "fx.beam", field: "material", type: "material" } ``` `type` is the category the name resolves in. `asset.declareReferenceKey`, `asset.declareReferenceArg` and `asset.declareReferenceField` declare the same from a script. ## What search reads (`indexing:`) `indexing:` is how assets are found. Search reaches an asset only through what its type's `indexing:` names, and adds nothing of its own. That includes you: an asset indexed badly is one you cannot find later, when you are making something else and need it. A type whose assets are never looked for says `indexing: none`. ```yaml indexing: data: # text, read from the asset's files - role: identity extractor: verbatim source: { file: "README.md" } - role: interface extractor: symbols source: { files: ["init.luau"] } - role: implementation extractor: verbatim source: { files: ["init.luau"] } content: # the picture - role: identity modality: image source: { file: "preview.png" } facets: # what a query filters and re-ranks by file: ".metadata" rigged: { type: bool, from: { components: { contains: SkinnedModel } } } roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } } ``` **Roles.** Each `data` and `content` entry has a `role`, and a query matches in two slots: - **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is. - **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both. Ask what a person would recognise an asset of the type by, and what it does, and point each role at the file that says it. For text, that is the asset's description: the file your template starts with a `[[describe]]` block, which the author writes or `services describe` fills in (see "Ask your assets to say what they are"). **`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`. Never index a file name (`source: { field: name }`): one or two words carry nothing to match. **`content`.** `modality: image` embeds the picture itself, so a text query matches what the asset looks like. A type whose assets are looked at makes the picture its identity. **`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded whole, so keys nobody declared in it are still found. Each further key is computed for every asset and states a value for every one, including `false`: a file can imply "not rigged" but never say it, and a query separates rigged from unrigged only because the unrigged ones say `rigged: false`. A key is `{ type: bool | number | enum, filter?: range, from }`, where `from` is `{ file, field }` (a field of one of the asset's files, dotted for nesting), `{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the asset's entities carry). ## What blocks a push A push checks every asset it carries against its type. These refuse it: - a required file that is missing, a `content` check that fails, a `described` file not written yet; - an error from the type's `validate`. Unlisted files and warnings do not. A `described` file blocks only a push that changes the asset. When a push is refused, the message names each asset and what it lacks. `world.publishBlockers()` and `zm status` read the same list without pushing. ## Typing a result from the asset (`refShapes`) A `ref` method whose result depends on the asset (one entry per child folder, per row of a config, per control a map declares) can only be annotated as `{ [string]: Thing }`, which accepts any key. `refShapes` states the result for each asset instead: a function returning a Luau type expression for that asset, and the module whose types the expression uses. Read the asset; never run it. ```lua -- inputMap.assetType/behavior.luau M.refShapes = { activate = function(self): (string, string) local names = {} for _, control in ipairs(M.ref.controls(self)) do table.insert(names, control.name .. ": Handle") end if #names == 0 then return "", "" end return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme" end, } ``` With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported. A per-asset type applies where the call site names which asset: a component field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`. `asset.resolve(name, category)` carries only the category, and a name computed at runtime carries nothing, so calls on those keep the declared return. The type belongs to the call's result: index it there, or bind what you need from it there, and the names stay checked. `require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows what was published: `categories` (each type's method surface) and `returns` (per-asset results by identity, then method). An identity missing from `returns` was never published. Results are recomputed when an asset is written; at most 64 assets of one type are read. ## Putting an asset in a scene (`ref.instantiate`) A caller writes one piece of code against every instantiable type, so what `instantiate` returns is fixed: ```lua local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable") M.ref = { instantiate = function(self, target, opts) local root = Instantiable.root(self, target, opts) -- compose the asset under `root`, now return Instantiable.result(self, root, idMap) end, } ``` **In.** `target` is the entity the asset lands under, or onto for a hierarchy type; with none, the type spawns a new root. `position`, `rotation` (three numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the same for every type: `Instantiable.root` applies them to a root you make, `Instantiable.place` to one you adopt. Document any options of your own in the hook's `--!arg` docs. **Out.** `(root, idMap)`. `root` is the composed root, live when you return: build synchronously, never defer to a component's `awake`. `idMap` maps each original id to the spawned one, so a component that composes the asset again on every load can pass it back in and keep references into the composition. Every call goes through `Instantiable.result`, which refuses a root that is not live and turns a missing `idMap` into `{}`. ## Inspecting an asset (`ref.inspect`) `asset.inspect(ref)` builds a record every asset shares (`identity`, `name`, `guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then calls `ref.inspect(self)` for the type's own `detail`: ```lua M.ref = { inspect = function(self) -- read the asset's own files, never runtime state: inspect works on an asset -- that has not been compiled, uploaded or registered return { --[[ what makes this asset what it is ]] } end, } ``` Without it, the record is the shared part alone, and an agent inspecting the asset learns nothing of what it is. A hook that raises leaves `detail` empty and sets `record.warning`. ## Discovery - `asset.list("assetType")`: every registered type. - `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts. - `asset.resolve("<typename>", "assetType")`: the type itself.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# interface (asset type) An interface is a named guarantee, defined once as an asset. A type that lists it under `interfaces:` guarantees that its members exist with the interface's signatures and keep its meaning. A consumer that accepts the interface calls those members on any asset of such a type without checking, and it works for types the consumer has never heard of, including types published later by someone else. The `indexing:` role named `interface` is a different thing: it names the file that states the signatures a caller of an asset uses. ## What an interface holds ``` applicable.interface/ interface.yaml # the members and properties (required) README.md # the guarantee and how to implement it (required) .metadata # description and tags (required) contract.module/ # the shared half (optional) applicableConformance.testSuite/ # the required behaviour as tests (optional) ``` ```yaml # interface.yaml description: "The guarantee, in one paragraph." members: glow: signature: "(self, owner: string, strength: number) -> boolean" inputs: owner: "Who asks for the glow; with the asset, it identifies the glow." strength: "How strong, from 0 to 1." returns: "Whether the asset is glowing now." properties: presence: type: number default: 0 meaning: "How prominently a consumer presents the asset among others." type_keys: [settings] contract: "~.contract" conformance: "~.applicableConformance" ``` | Key | Meaning | |---|---| | `description` | Required. The guarantee, stated once, read by people, agents and search. | | `members` | Required. Every member a type meets, by name: `signature` (the parameters, `self` first, then `-> returns`), `inputs` (each base input and its one meaning for every implementer) and `returns`. | | `properties` | Optional. Named, typed values every implementer exposes. `type` is `string`, `number`, `boolean`, `{ enum: [...] }` or `{ asset: <category> }`; `default` is optional, and a property with none must be met by the type. | | `type_keys` | Optional. `type.yaml` keys every implementing type states. The README line that starts with the key in backticks says what the key states, and a refusal quotes it. | | `contract` | Optional. The module holding the shared half: the `gate` every call of a member passes through. `~.contract` names the interface's own `contract.module`. | | `conformance` | Optional. The `testSuite` stating the required behaviour as tests, run over every implementer or over the types a run names (`Test.subjects()`), named by its place in the interface (`~.<name>Conformance`, a `<name>Conformance.testSuite` the interface holds) or by identity. It is test content, which the built library leaves out; it is named by path and recorded in no reference table. An interface whose `conformance` or `contract` names nothing is refused (`interfaces.conformance`, `interfaces.contract`), and `asset.validate` of a world's own type runs the suite over that type (`interfaces.conformanceFailed`). | | `legacy` | Optional. `{ implied_by: <member> }`: a type that lists no `interfaces:` key and defines this member implements the interface, with a warning. | An unknown key is a warning (`interface.key.unknown`), so a definition written for a later engine loads on an earlier one. ## Implementing an interface A type lists the interfaces it implements in its `type.yaml`: ```yaml interfaces: [glowable] ``` and meets each member in its `behavior.luau`, implicitly with its own method of the member's name and signature: ```lua M.ref = { glow = function(self, owner, strength) ... end, } ``` or explicitly, when the type's own method of that name means something else: ```lua M.ref = { glow = function(self, kind) ... end } -- the type's own meaning M.interfaces = { glowable = { glow = function(self, owner, strength) ... end }, } ``` `M.interfaces` is keyed by the interface's name as the type lists it. A property is met by a value or a getter `(self) -> value` in the same two places, else by its default. Every asset of the type implements every interface the type lists, and an asset of a type that lists nothing never implements it. `ref:implements(x)` asks, and `ref:as(x):member(...)` calls through the interface. ## What registration checks Every listed name resolves to an interface; every member is met with at least the signature's number of parameters (a function taking `...` meets any count); every property is met or has a default and holds its type; every `type_keys` key is in `type.yaml`; every entry under `M.interfaces` names a listed interface and one of its members. A declaration that breaks a check carries no marks until every problem is fixed, `asset.validate` reports each problem as an error that refuses a push, and the engine log states each once. | Code | The fault | |---|---| | `interfaces.shape` | `interfaces` is not a list of names | | `interfaces.unknown` | a name answers to no interface | | `interfaces.ambiguous` | a name answers to more than one interface | | `interfaces.duplicate` | a name is listed twice | | `interfaces.missing` | a member is met by neither `M.ref` nor `M.interfaces` | | `interfaces.arity` | a member's function takes fewer parameters than the signature | | `interfaces.typeKey` | a `type_keys` key is missing from `type.yaml` | | `interfaces.explicitUnclaimed` | `M.interfaces` meets an interface the type does not list | | `interfaces.explicitUnknown` | `M.interfaces` meets a name the interface does not have | | `interfaces.propertyMissing` | a property is met by nothing and has no default | | `interfaces.propertyType` | a property's value is not its type | | `interfaces.conflict` | one function meets one member of two interfaces whose signatures differ | | `interfaces.unloadable` | the type's `behavior.luau` did not load | | `interfaces.implied` (warning) | a legacy type defines the member and lists nothing | An interface's own faults are `interface.definition` (the file does not read), `interface.contract` (the contract module does not load), `interface.key.unknown` (warning) and `interface.breakingEdit` (warning: this version changes a member of a version other content pins). ## Versioning An interface is versioned like any asset, and an implementer pins the version it was written against. Adding a member, removing one, or changing a signature or an input's meaning breaks every implementer that moves, so publish such a change as a new interface. Wording that keeps the meaning is an ordinary edit. ## The shared half The contract module exports `gate(member, self, impl, ...)`. Every call of a member of an interface the asset implements passes through it: the gate checks the inputs, calls `impl`, and checks the output, so a type that breaks the shape fails at its own call and names itself. Base inputs mean the same for every implementer; a type's own extras travel in `opts`, are always optional, and never change a base input's meaning. ## Discovery - `asset.resolve("<name>", "interface"):definition()`: the definition as written. - `asset.resolve("<name>", "interface"):implementers()`: the types that list it. - `asset.inspect("<name>", "interface")`: the same in one record.
▲ 0↑ born
◐
material · born here
❒asset
# Default The neutral fallback surface — a plain white, non-metallic PBR material with mid roughness (`0.5`), sampling the built-in white texture. This is what an object renders as when no material is assigned. Built on `@builtin::shaders.pbr`. ## Inputs - `colors.base_color` — the flat tint (white by default). - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — a neutral matte dielectric. - `textures.base_color_texture` — the built-in `default:white` texture.
▲ 0↑ born
◐
material · born here
❒asset
# Triplanar Checker A checkerboard surface projected triplanarly, so the pattern stays uniform across arbitrary geometry with no UVs and no stretching. Neutral white base colour (`1.0, 1.0, 1.0`), half roughness (`0.5`), non-metallic, with a projection sharpness of `4.0` controlling how tightly the three axis projections blend at edges. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.triplanar`, sampling `@builtin/textures/array_texture`. ## Inputs - `floats.triplanar_sharpness` (`4.0`) — blend tightness between the X/Y/Z projections. - `colors.base_color` (`1.0, 1.0, 1.0`) — tint over the projected texture. - `textures.base_color_texture` — the projected checker source (`@builtin/textures/array_texture`). - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric, mid-gloss default.
▲ 0↑ born
◐
material · born here
❒asset
# Plastic Red A glossy red plastic — a non-metallic PBR surface with a saturated red base colour (`0.8, 0.1, 0.1`) and mid roughness (`0.5`) for a soft dielectric sheen. Built on `@builtin::shaders.pbr`. Opaque, back-face culled, queue `2000`. ## Inputs - `colors.base_color` (`0.8, 0.1, 0.1`) — the red plastic tint. - `floats.roughness` (`0.5`) — soft, semi-glossy highlight. - `floats.metallic` (`0.0`) — dielectric (non-metal) response. - `floats.emissive` (`0.0`) — no self-illumination.
▲ 0↑ born
·
assettype · born here
❒asset
# Component (asset type) A component is a reusable behavior + data unit attached to an entity. The component file declares public fields, methods, and lifecycle callbacks; the engine instantiates one per attachment and drives its hooks every frame. Components are the primary unit of gameplay code — movement, AI, animations, UI panels, network sync, and per-entity state all live here. ## When to use one - You need per-entity state that survives across frames. - You need per-entity behavior driven by engine lifecycle hooks (`start`, `update`, `onDestroy`). - You want to expose configurable fields to designers / `entity.spawn` callers / scenes without code changes. If you need a stateless pure-function library, use a `.module`. If you need to generate content declaratively, use a `.service`; compute work belongs in a `.computeShader`. ## Where it lives - Source: `/zero/source/.../<Name>.component/` - Identity: `<Name>` (the `.component` suffix strips from the identity, but the folder retains the suffix on disk). - Folder shape: - `init.luau` (or `init.lua`) — declares the component. **Required.** - `README.md` — instance-level documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** The structural contract is enforced by `asset.validate` against this type's `type.yaml`. ## How to create one Always start with the scaffold — it guarantees the folder shape matches `type.yaml` from the moment it's on disk: ```luau asset.create("component", "<Name>") -- Creates: /zero/source/<Name>.component/ -- init.luau (canonical declare + public block + hooks stubbed) -- README.md (instance README template) ``` After scaffolding, edit `init.luau` to fill in the actual fields and behaviour. The component registers as soon as the file is written — hot-reload is automatic; no engine restart required. ## How it operates 1. **Registration.** Writing `init.luau` into a `.component/` folder indexes the asset, mints a guid (in the `.meta` sidecar), and surfaces the type to the engine's component registry. Same-frame visible to `entity.component.add`. 2. **Attachment.** `entity(id).component.add(name, data)` (or the batch form `tools.use("entityOps", "addComponents", targets, { [name] = data })`) attaches an instance. The `data` table's fields override the component's declared defaults; omitted fields take the declared default. The `data` values are copied into `public.*` BEFORE `awake()` runs. 3. **Lifecycle.** The hooks run in this order: - `awake()` — same frame as attach, immediately after the data copy. Initialise state, set up native bridges, register with other systems. Other components on the same entity may not have awoken yet. - `start()` — the next frame. Every component on the entity has completed `awake()` by then, so cross-component setup is safe here. - `update(dt)` — same frame as `start()`, then every frame after, for as long as the gameplay clock is running. `fixedUpdate(dt)` runs once per physics step, straight after it, with the step's `dt`, so a frame can run it several times or not at all; `editorUpdate(dt)` runs while the clock is held. Which of them ticks is decided by `engine.mode` AND `engine.paused` together — see **Per-frame hooks and the two axes** below, and `man modes`. - `onDestroy()` — when the component is removed via `component.remove` or when the owning entity is despawned. Release resources, drop native ECS components. For the full list (`onEnable`, `onDisable`, `fixedUpdate`, `editorUpdate`, `onPropertyChanged`, `onAssetReload`, `onModuleReload`, `onBeforeSave`, …) and the timing details, **read `man components` — that is the canonical lifecycle reference. Generic component patterns (declare blocks, public fields, sync, ECS bindings, typed methods) all live there.** 4. **Public surface.** Fields declared in `public` are inspectable, editable in the inspector, and persist with the entity. Methods are declared on that same table with a colon — `typed function public:method(args)` — and every one of them takes the component ref as `self`, so a caller invokes it with a colon too: `entity(id).component.get(name):method(args)`. That is the one calling convention a component ref answers to: the reflection methods `ref:fields()` / `ref:getField(name)` / `ref:setField(name, value)` take the same spelling. A function the chunk declares at file scope (`function helper()`) is the component's own, reachable from its hooks under its bare name; `public` is what the ref carries. 5. **Settings and the Inspector card.** `type.yaml` names the component's settings schema as `settings: { schema: { instance: "init.luau", export: "public" } }`: the `public` table IS the schema, and its values live on each entity the component is on, so `asset.schema(componentRef)` answers the Field descriptors and no values file exists. On an entity the Inspector shows the component as a card whose generic `settings` section edits those fields as typed controls, each edit checked against the schema and written to the live component as one undoable operation. `type.yaml` also names `inspector: { instance: "inspector.luau" }`: a component that ships an `inspector.luau` beside its `init.luau` shapes its card — the file returns `{ sections, replace, order }` (see `assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)` reading `ctx.component` (the live component) and `ctx.selection.id` (the entity). `SceneModule.component/inspector.luau` replaces `settings` with the bound module's declared inputs. 6. **Events.** An `events` block declares typed moments the component fires from inside — `events = { onHit = Event({ dmg = Field.number(0, NoSync) }) }`. The owner fires with `events.onHit:fire({ dmg = 10 })`; outside code subscribes through the proxy's subscribe-only facade, `entity(id).component.get(name).events.onHit:connect(fn)` (`:once` / `:wait` too). Pass `Sync` as the event's second argument to replicate a fire to other peers. Events let one component react to another's moments without polling. Full reference: **`man components`**, Events section. 7. **Hot reload.** Editing `init.luau` reloads the component definition; live instances are reconciled with the new declaration in-place, and each crosses one lifecycle boundary: `onDestroy()` ends the running life, then `awake()` and `start()` construct the one that replaces it, and `update()` resumes on the next frame. `public` and `private` values carry across; module-level `local`s belong to the chunk, so the new life starts with them at their initial values and its `awake`/`start` are what fill them in. Whatever the old life handed elsewhere — a subscription, a shared registration, a spawned entity — is released in `onDestroy`, the call that pairs with the construction about to run. An edit that leaves the source byte-identical crosses no boundary at all. A field carries its value across when something stated it: a key of the `data` table the instance was attached with (a scene record's data is that table), or a write made since. Every other field takes the edited source's declared default, so changing a default reaches every instance that left the field to it. An instance that states its own value for a field whose default the edit changed keeps that value, and the reload logs a `[HotReload]` warning naming the field, the entity, the value kept and both defaults. ## Discovery - `asset.list("component")` — every registered component (engine + world + libraries). - `asset.inspect("<name>")` — identity, scope, public fields, lifecycle methods, source path, and this type README. `detail` carries the component's declared `fields`, `methods`, and `events`, parsed from its source — `tools.use("assets","describe", "<name>")` renders it as markdown, so a component's events are visible without opening its source. - `ls /zero/source/<Name>.component` lists the files the folder holds. - `entity(id).component.list()` — components attached to an entity. ## Per-frame hooks and the two axes `engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay clock) are independent, and the per-frame hooks read them separately: - `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is running** — whichever mode the engine is in. - `editorUpdate(dt)` ticks while **the clock is held** — because the mode is `edit`, or because play is paused — and also alongside `update` whenever edit is running. Which gives four states, and this table is the contract: | `engine.mode` | `engine.paused` | hooks that tick | |---|---|---| | `edit` | `true` | `editorUpdate` | | `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` | | `play` | `false` | `update`, `fixedUpdate` | | `play` | `true` | `editorUpdate` | Entering edit sets `paused = true` and entering play sets it back to `false`, so a session that never writes `engine.paused` only ever sees rows 1 and 3 — which is where the shorthand "`update` is the play tick, `editorUpdate` is the edit tick" comes from. It is the two default rows of a four-row table, not the rule. **Row 2 is the one that surprises.** With `engine.paused = false` in edit — set by hand, or by a tool that advances the gameplay clock to sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate` both fire, once each, every frame. A component that declares both and routes them to one body therefore runs that body **twice per frame**: ```luau local function drive(dt) ... end function update(dt) drive(dt) end function editorUpdate(dt) drive(dt) end -- twice per frame in row 2 ``` Nothing reports the doubling; it reads as an animation running at twice its intended speed. To get exactly one tick per frame in every row, ask which axis you meant and answer it in the body: ```luau function update(dt) drive(dt) end function editorUpdate(dt) if engine.paused then drive(dt) end end ``` A scene `entrypoint.luau` declaring the same two hook names is dispatched by the scene loader, not by this table: there `update` needs play AND running, `editorUpdate` needs edit, and play-paused ticks neither. Read `man scenes` before carrying a component's rule to an entrypoint. ## Authoring conventions - Annotate public fields with `--!desc` so the inspector + LSP show documentation alongside the field name. - Declare lifecycle hooks (`start`, `update`, `onDestroy`) explicitly rather than relying on engine defaults — readers can see at a glance what runs when. - Keep `update(dt)` cheap — it runs every frame per instance. Move heavy work to `start`, to a `.computeShader`, or behind a job (`man jobs`). - For multi-entity batching, prefer `tools.use("entityOps", "addComponents", targets, components)` over a loop of `entity(id).component.add` — it takes many targets and many components in one call. ## Common pitfalls - **Naming.** The component identity is the folder stem with `.component` stripped (e.g. `<Spinner>.component/` → identity `Spinner`). Don't repeat the suffix in the identity passed to `component.add`. - **`init.lua` vs `init.luau`.** Either is accepted (it's a `one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both in one folder is invalid. - **`update` in edit mode.** It runs whenever the gameplay clock is running, and entering edit stops that clock — so `update` is idle in a freshly-entered edit session and ticks again the moment anything sets `engine.paused = false`. Use `tools.use("wld", "play")` to test update logic under the mode it ships in; `tools.use("wld", "edit")` to return. See **Per-frame hooks and the two axes** above. - **Renaming.** Renaming the folder changes the identity. References to the component are recorded against the component itself, so renaming or moving it does not break them. ## Related types - `.module` — pure-function library, no per-entity state. - `.service`: a declarative content generator, no per-entity state. - `.preset` — a captured component configuration, replayable into `component.add` without re-typing fields. - `.bundle` — entity hierarchies that may carry component attachments as part of the bundle. ## In the Inspector Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
▲ 0↑ born
·
assettype · born here
❒asset
# procNode: one reusable step of procedural generation A `.procNode` is a node authored as content: a folder whose `init.luau` is the node. It returns `proc.define(function(g) ... end)`, the same function-of-`g` form a `.procGraph` is written in, so a node is a small graph that other graphs call. Its `g:describe` text says what it makes and when to use it, its `g:input` declarations are what a call passes, and what it returns (or declares with `g:output`) is what the call gives back. ``` MyNode.procNode/ init.luau -- the node README.md -- what it produces, its inputs, its outputs .metadata -- description and tags ``` ## What a node states - **`g:describe(text)`**: what the node produces and when to use it. It is the text search, the node catalogue and the Inspector show. - **`g:input(name, default, opts)`**: one input of the node. The default types it (`Float`, `String`, `Bool`, `Vec3`, `Color`, `List<T>`, `Record`); `opts` adds `type` (for a default that does not state one, or none), `description`, `options`, `min`, `max` and `optional`. A call names inputs in a table, or passes them in declaration order. - **Outputs**: the returned table names them (`return { geometry = geometry }`), and `g:output(name, value)` declares one as the node builds. A node with one output answers that value to its caller; a node with several answers a record by output name; a node with none answers nothing. - **Written as literals.** What a node takes and gives is read from its source without running it, the way search and description read it here and the way ZeroMind reads it, so each declaration states its values as written: `g:describe` and each `g:input` once, at the top level of the function, with a literal name, default and options (a file constant holding a literal, or `asset.resolve("<identity>", "<type>")`, reads as one); outputs named by the table the function returns, or by `g:output`, the same names on every branch of a condition and never inside a loop. `asset.interface(node)` answers what the source declares, with each part it cannot read as a problem, and a push refuses a node with such a problem (`interface.unreadable`). - **The body** is the node's work: calls to other nodes, arithmetic over sockets, `for`, folds, steps and state, as the builder README (`proc.module/builder.module/README.md`) describes. A node that uses another node is recorded in the graph that calls it, so a node can be built from nodes. ## How a graph calls a node A node inside a `<family>.nodebox` is called by its box and folder name: `points.nodebox/disc.procNode` is `g.points.disc({ ... })`, and nothing inside the node states that name. A node is also reached by: - its path (`g["/zero/source/fx/ring.procNode"]`), - `~`, the nearest enclosing package, effect or world root (`g["~/ring"]`), - its guid, - a short name only one node answers to (`g.disc`). A name that matches two nodes and a name that matches none are errors that name the candidates. Each call is recorded in the calling graph by the node's guid, so the node travels with every graph that uses it, and a rename or a move keeps the reference. A `.procGraph` is called the same way and answers what it returns. ## Nodeboxes A nodebox is the family a node lives in: a namespace folder grouping related nodes (`points`, `mesh`, `field`, `terrain`). `nodebox.assetType` describes it. A node placed in a box takes the box's name as its prefix; a node outside any box is reached by path, `~` or guid. `asset.create("nodebox", family)` makes a box and `asset.create("procNode", name, { into = box })` makes a node in it. ## Finding nodes `asset.list("procNode")` lists every node. The `procgen` toolbox's `searchNodes` finds them by meaning across every published node, and with no query lists the ones this engine holds grouped by family; its `describeNode` answers one node's inputs, their types and defaults, and its outputs. Both read what each node's source declares and run no node. The type's `indexing` recipe embeds a node's README and its source, so a search by meaning finds a node by what its description and README say it is for: write them in the words someone looking for the node would use. ## Registration Every node the asset index lists is known to the procgen registry by what its source declares, read when it is asked for and read again when the source changes; nothing runs a node to list it. Its code loads the first time a build runs it. After that, the lifecycle hooks keep it current: `onChange` loads it again and hot-reloads on an edit, `onDelete` removes it. Editing `init.luau` cooks again every graph that reaches the node, and only the nodes downstream of the change do work. `init.luau` is compiled from its current source on each load, so a module it pulls in uses an absolute require (`require("@builtin::systems.procgen.proc")`). What a node is built from is more than its own file. A module its `init.luau` requires while it builds, at any depth of requires, is part of it: when that module changes, `onDependencyChange` loads the node again from the module as it now stands. A file its `init.luau` reads with `vfs.read` while it builds is part of it too, and so is a file a module it calls reads with `proc.read` (a module's own `vfs.read` is its own and makes no dependency). Writing such a file loads the node again (`proc.sourceChanged`). Either way the node's definition moves, so every graph and Generator reaching it cooks again, from one version of everything it was built from. `proc.builder.readsOf("<node>.procNode/init.luau")` lists the files its last build read. A graph that references a node which is not registered errors at load, naming the missing guid. A graph that reaches itself, directly or through other nodes, errors at cook. ## Content requirements `README.md` carries real text: what the node produces, its inputs and its outputs. `.metadata` carries a `description` (what the node computes and the value type it answers) and `tags` (the family, so search finds it). It may state where the node works: `context`, `pulls` and `pushes` (the values `proc.registry.contexts()`, `"scene"` and `"asset"` name). A node in a nodebox that states none takes its box's; `procgen` `describeNode` and `searchNodes` answer them. A node written with `proc.graph` and `g:node` (the `procNodes/` of the procgen package) is called only by a `proc.graph` graph, through `g:node`. A graph built with `proc.define` does not call it: `g.op.<name>` of it is refused where it is written, naming the node written in the call form that answers to the same name. ## In the Inspector Operation: the node's id and what it does, its cost and caching when it declares them, and its inputs and outputs, from the procgen registry's schema for it. A node that did not register says so.
▲ 0↑ born
·
assettype · born here
❒asset
# dynamicAsset (asset type) A **prompt-driven, self-regenerating 3D asset**. A `<name>.dynamicAsset/` folder holds a text `prompt.json`; the asset's model is generated from that prompt by the `mesh_gen` text-to-3D service. Editing the prompt regenerates the model and version-controls the old one — no explicit call needed. This type is the **reference example** for the asset-type `onChange` change-callback (the type-level analogue of a component's `onAssetReload`). Read its `behavior.luau` to see the pattern end to end. ## Folder shape ``` <name>.dynamicAsset/ ├── prompt.json { "prompt": "a mossy stone golem" } ├── .metadata generation status + start date + last prompt ├── model/ (after first generation) │ ├── model.glb the current generated mesh │ └── model.json manifest (prompt, date, service handle) └── versions/ (after the prompt changes at least once) ├── v1/ │ ├── model/model.glb │ ├── prompt.json the prompt that produced this version │ └── meta.json └── v2/ … ``` ## Lifecycle 1. **Generate** — `ref:generate("a mossy stone golem")` writes the prompt, sets `.metadata.generationStatus = "inflight"` + `generationStartedAt`, and starts a `mesh_gen` generation. The GLB is written straight into `model/`. 2. **Status** — `ref:status()` reads the state from `.metadata`: `status` (`empty`/`inflight`/`succeeded`/`failed`), `stage` (live generation stage), `prompt`, `startedAt`, `finishedAt`, `error`, `handle`. Use it to find finished / failed / in-flight assets at a glance. 3. **Edit the prompt → regenerate** — writing `prompt.json` (by hand, `vfs.write`, `ref:setPrompt(...)`, or a pull) fires `onChange`. If the prompt actually changed, the current `model/` is archived into `versions/v<N>/` (incrementing) and a fresh generation starts. ## Methods (`AssetRef<dynamicAsset>`) | Method | What it does | |--------|--------------| | `:generate(prompt?)` | Generate/regenerate now (async). Returns the generation task id (a number); a generation already in flight returns that task's id. | | `:status()` | Read generation status from `.metadata`. | | `:getPrompt()` / `:setPrompt(text)` | Read / set `prompt.json` (set triggers regeneration). | | `:modelPath()` | VFS path of the current GLB, or nil. | | `:versions()` | Archived version indices (oldest first). | | `:restoreVersion(n)` | Make version `n` the current model and prompt again, with no generation and no credits. The model it replaces is kept as the next version. | | `:spawn(name?, x?, y?, z?)` | Spawn the current model into the scene. | ## Setup Generation goes through the metered `mesh_gen` service, so it spends credits. When the service call fails, `:status().status` is `"failed"` and `:status().error` says why. ## Usage ```luau asset.create("dynamicAsset", "Golem") local golem = asset.resolve("Golem", "dynamicAsset") golem:generate("a mossy stone golem, low-poly") -- … wait … print(golem:status().status) -- "succeeded" golem:spawn("golem", 0, 0, 0) -- Change the prompt → archives v1, regenerates: golem:setPrompt("a bronze golem, ornate") print(golem:versions()) -- { 1 } ``` ## Notes - Generation is async and can take minutes. `onChange` returns immediately; the model appears when `:status().status` flips to `"succeeded"`. - `onChange` is convergent: it only acts when the prompt differs from the last generated prompt and queues edits made mid-generation (`pendingPrompt`), so it never loops on its own writes. ## In the Inspector Selecting a generated asset opens its **Generation** section: the status of its last generation ("not generated" before the first), and, once a generation has filled them, its stage, prompt, start and finish times and error; how many versions exist; the model in use ("none yet" before one exists); and an opener for `prompt.json`. Generating spends credits, so it stays in Operations, where restoring an earlier version (free) is listed too.
▲ 0↑ born
·
assettype · born here
❒asset
# Input macro (asset type) An input macro is a recorded or hand-authored sequence of input simulation events — keystrokes, mouse moves, button clicks, scroll wheel deltas — timestamped and played back via the `inputSim` toolbox (`tools.use("inputSim", "macro", <name>)` from Luau). Macros are the canonical generic surface for "make the engine receive these inputs at these times": testing, demos, automated repro of input sequences. The engine deliberately does NOT ship per-feature input recipes (walk, sprint, drive). Authors record or hand-write the macro they need; the playback primitive is type-agnostic. ## When to use one - You want to script an input sequence for testing (e.g. "walk forward 3 seconds, jump, look around"). - You're capturing a demo / repro of a user interaction sequence. - You want deterministic input playback across runs. If you need per-frame programmatic input (more than a fixed sequence allows), drive the `inputSim` toolbox's `key` / `click` tools directly from a script. If you need real input handling, that's the `input` API (`man input`). ## Where it lives - Source: `/zero/source/.../<name>.inputMacro/` - Identity: `<name>` (the `.inputMacro` suffix strips). - Folder shape: - `events.json` — JSON array of `{ t, op, arg }` event tuples. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** ## How to create one Two paths: ```luau -- Record a live sequence: recordMacro captures real input for -- `duration` seconds and returns the recorded events; saveMacro -- persists them as the asset. local events = tools.use("inputSim", "recordMacro", { duration = 5 }) tools.use("inputSim", "saveMacro", "<name>", events) -- Hand-author an empty macro scaffold and fill events in: asset.create("inputMacro", "<name>") ``` The record path is preferred for sequences any human could perform; hand-authoring is for synthetic or precisely-timed sequences. ## How it operates 1. **Event format.** `events.json` is a JSON array of triples: ```jsonc { "t": 0.5, "op": "keyDown", "arg": "KeyW" } ``` - `t`: seconds since macro start. - `op`: the name of an `inputSim` verb that drives input — the keyboard and mouse verbs (`keyDown`, `keyUp`, `key`, `mouseDown`, `mouseUp`, `mouseMove`, `mouseMoveBy`, `click`, `scroll`, `lockPointer`), the pad verbs (`pad`, `padOff`, `padDown`, `padUp`, `padPress`, `padStick`, `padTrigger`) and the touch verbs (`touch`, `touchDown`, `touchMove`, `touchUp`, `stick`, `tapButton`, `drag`, `pinch`). - `arg`: that verb's arguments — the value itself when the verb takes one (a key code such as `"KeyW"`, a mouse button index where 0 = LMB, 1 = RMB, 2 = MMB, a canonical pad button name such as `"south"`), or a table keyed by the verb's parameter names when it takes several (`{ x = 400, y = 300 }` for `mouseMove`, `{ dx = 200, dy = 0 }` for `mouseMoveBy`, `{ stick = "left", x = 0, y = -1 }` for `padStick`, `{ x = 714, y = 984, id = 1 }` for `touchDown`). 2. **Playback.** `tools.use("inputSim", "macro", "<name>")` schedules every event at its `t` offset relative to playback start; events are played in order of `t`, and events sharing one `t` play in the order the list writes them. The same tool takes an inline event list or an `AssetRef<inputMacro>` instead of a name. 3. **Determinism.** Macros are deterministic relative to engine state at playback start — same start state + same macro = same end state. 4. **Recording.** `tools.use("inputSim", "recordMacro", { duration = n })` polls live input state and returns the recorded events; `tools.use("inputSim", "saveMacro", "<name>", events)` writes them to `/zero/source/<name>.inputMacro/events.json` and returns the macro's `AssetRef`. ## Discovery - `asset.list("inputMacro")` — every registered macro. - `asset.inspect("<name>")` — event count, duration, source, this type README. - `ls /zero/source/<name>.inputMacro` lists the files the folder holds. - `tools.use("inputSim", "listMacros")` — every registered `.inputMacro`. ## Authoring conventions - Start macros from a known state (call `layers.load("base")` before playback) so determinism holds across runs. - Keep macros focused on one user-facing action sequence. Longer macros are harder to compose and debug; chain shorter ones via `tools.use("inputSim", "macro", "a")` then `tools.use("inputSim", "macro", "b")`. - Keep the expected start state and end state in mind when you name a macro: what scene / mode / focus the playback assumes. ## Common pitfalls - **Non-deterministic start state.** Playing a macro from a different starting scene produces different outcomes. Always lead with a scene load. - **Frame-rate dependence.** Times are in seconds; the dispatcher schedules events relative to wall time, not frames. Effects that depend on per-frame logic may diverge across hardware. - **`mouseMove` argument.** The verb itself takes an absolute screen position `{ x, y }`; a relative motion is `mouseMoveBy` with `{ dx, dy }`. The macro player also accepts `{ dx, dy }` on a `mouseMove` event and plays it as `mouseMoveBy`, so a recorded delta replays as a delta. Check which form your events carry. ## Related types - `.tool` — for agent-callable input wrappers that may invoke macros as part of larger flows. - `.scene` — macros pair with scenes for deterministic test setups. ## In the Inspector Events: how many events the macro records, when the last one fires, and the first 50 events in order (time, op, argument). Replaying it stays in Operations.
▲ 0↑ born
◐
material · born here
❒asset
# Cel Shaded A stylised, toon-shaded opaque surface built on `@builtin::shaders.extended_material`, with a warm red-orange base colour (`0.9, 0.3, 0.2`). The sun's light is cut into flat bands that multiply the base colour, so every band renders the hue of `base_color` and only its brightness steps; ambient light lifts the side facing away from the sun in the same hue. High roughness (`0.8`) keeps the surface matte: its specular term stays below the first band, so each lit band is one flat colour. ## Inputs - `colors.base_color`: the surface colour every band renders in, multiplied by `base_color_texture`. - `floats.roughness` (`0.8`): the size and strength of the specular highlight, which is banded with the rest of the sun's light; 0 is a small bright highlight. At four bands, a roughness of 0.5 or more keeps the highlight below the first band, so none shows. - `floats.quantize_steps` (`4`): the number of bands the sun's light is cut into; 0 shades smoothly. - `textures.base_color_texture`: an optional surface texture, drawn multiplied by `base_color`. Unset, it is white, and the surface renders `base_color` alone.
▲ 0↑ born
◇
component · born here
❒asset
# ScreenSpaceReflections Reflections off the scene's own drawn frame, as a one-feature component. A scene lists its features together, each with its settings, on `RenderFeatures` (`{ feature = "@builtin::systems.reflections.ssr", settings = { ... } }`); this component carries the same knobs as fields for one feature. ```lua local id = entity.spawn("reflections").id entity(id).component.add("ScreenSpaceReflections", { intensity = 1.0, maxDistance = 40, quality = "high", }) ``` Polished floors start reflecting what stands on them, wet ground reflects what is above it, and metal picks up its surroundings — all from geometry the camera can already see, with nothing authored per surface. Roughness decides who gets them. A screen-space ray traces one direction, which is a mirror; `roughnessCutoff` is where that stops being a fair stand-in for a surface's real lobe, and past it the pass leaves the surface alone. Every field is live: edit one in the inspector and the reflections follow. Setting `intensity` to 0 turns them off without losing the rest of the settings. Several of these in one scene share one set of reflections: the one edited last is in force, removing it hands the reflections to the newest of the others, and only removing the last one takes them down. While one stands in the scene, the reflections come back if something else takes them down. How much a reflection shows through is the surface's own Fresnel term, so metal takes almost all of it and a dielectric floor takes a few percent head-on and more at a grazing angle — the same way a wet road reads dry underfoot and mirror-like down the street. For code that adjusts reflections at runtime, reach for `@builtin::systems.reflections.ssr` — same options, no component. The full description of what each knob does and how the passes work is in the package readme: `guides { path = "systems/reflections" }`.
▲ 0↑ born
·
scene · born here
❒asset
# Polished floor A polished stone floor with three coloured pillars standing on it, under an afternoon sky, with screen-space reflections listed on the scene's `RenderFeatures` entity — so the floor reflects the pillars, and a player walking across it, rather than the sky alone. Load `@builtin::systems.reflections.demo.polished_floor` with the `scene.load` tool. Players arrive facing the pillars from floor height, which is the grazing angle a polished dielectric reflects at most strongly. ## What it shows - **The feature on one entity.** `render_features` carries a `RenderFeatures` list with `@builtin::systems.reflections.ssr` at `intensity = 1`, `maxDistance = 60`, `quality = "high"`. Delete the entity and the floor mirrors the sky alone; put it back and the pillars stand in the floor. - **Only what the camera sees.** A pillar's reflection comes from the frame the camera drew, so turning away from a pillar takes its reflection with it, and the reflection fades toward the screen edge rather than cutting off. - **The environment underneath.** Where a ray finds nothing the floor keeps the sky reflection the environment gives it, at the same mip and Fresnel weight, so the seam between the two is a change of content and not of brightness. - **Roughness decides how they look.** The floor sits at roughness 0.06 and reflects as a mirror. The pillars sit at 0.55, under the feature's `roughnessCutoff`, and reflect glossily: soft and stretched along the lobe their roughness describes. ## Contents - `floor` — a 60 m slab of `PolishedStone`, a near-black dielectric at roughness 0.06, with a collider. - `pillar_1..3` — 1.6 × 5 × 1.6 m boxes in `PillarRed`, `PillarGreen`, `PillarBlue`, sunk into the slab. - `sun`, `ambient`, `sky` — a side-lit afternoon under a `ProceduralSky`. - `render_features` — the `RenderFeatures` entity this scene exists for. - `PlayerSetups` / `Spawns` — the humanoid player on an orbital-follow camera, spawning in front of the pillars. The scene's player intent is `"spawns"`. ## Entry point - `entrypoint.luau` — nothing to set up: the reflections run from the `RenderFeatures` entity the moment the scene loads.
▲ 0↑ born
▣
module · born here
❒asset
# ssr Screen-space reflections — polished floors reflect what stands on them, from the frame the engine has already drawn. ```lua local ssr = require("@builtin::systems.reflections.ssr") ssr.set({ intensity = 1, maxDistance = 40, quality = "high" }) ssr.get() --> the settings in force ssr.active() --> are the reflection passes running ssr.clear() --> off, settings kept for the next set() ``` `set` takes any subset — omitted fields keep their current value, so adjusting one knob does not mean restating the rest. An `intensity` of 0 turns reflections off and releases the passes rather than running them at zero strength. `roughnessCutoff` is the field that decides who gets reflections at all. A screen-space ray traces one direction, which describes a mirror; past the cutoff a real surface scatters over a lobe too wide for one ray to stand in for, and the pass leaves those surfaces alone. `maxDistance` and `quality` trade against each other. Quality sets how many steps the march spends, so a long distance at a low quality samples coarsely — reflections thin out at range rather than disappearing, because refinement adapts to the step size on its own. For reflections a scene should simply have, author the `ScreenSpaceReflections` component instead — it carries the same settings, persists with the scene, and edits live in the inspector. This module is for code that changes reflections at runtime: a quality slider, a cutscene, weather turning pavement wet. The full description of what each knob does and how the passes work is in the package readme: `guides { path = "systems/reflections" }`.
▲ 0↑ born
·
renderfeature · born here
❒asset
# ssr The render feature behind `ScreenSpaceReflections` and `@builtin::systems.reflections.ssr`. Two compute passes run at the `afterDepthPrepass` seam, once the visibility raster has laid the frame's depth and before anything shades: | order | pass | output | |---|---|---| | 60 | `ssr_trace` | one ray per pixel, drawn from the pixel's GGX lobe: where it hit and how confident the hit is, or the direction it travelled when it found nothing, into the feature's `ssr_rays` target | | 61 | `ssr_resolve` | each pixel's lobe gathered over its own ray and its neighbours' rays, accumulated over frames in the feature's history target, into `@scene.reflection` | That channel is what a material's environment term reads the same frame, at its own pixel: the traced light, mixed over the probes and the sky by the share of the surface's lobe the screen answered, with the material's own Fresnel, roughness and tint weighing it into the pixel the way they weigh any environment. Nothing here touches the lit picture. The trace marches against this frame's depth, which the visibility raster has just written, so the reflection stands where the camera is now. What it reads about the surfaces (the reflecting surface's normal and roughness, the hit's normal) comes from the previous frame: the G-buffer as that frame left it (`readsPrevious`), reprojected through the previous view-projection `@frame.camera` carries in its rows `[5..9)`. The resolve reads the light at each hit from `@scene.colorHistory`, the light the previous frame ended with, at the pixel the hit stood at then. A point the previous frame did not show reflects its environment alone. ## The rays Every pixel draws one ray from the lobe its roughness describes. A mirror (below perceptual roughness 0.1) takes the reflection vector. A rougher pixel samples a half vector from the distribution of normals visible from the camera (Heitz 2018) at `alpha = roughness²`, and reflects the view ray about it, from noise that depends on the pixel and the frame. Each ray carries the density it was drawn with, as `log2(pdf)`, so the resolve can weigh it against another pixel's lobe. The ray texel is `rgba16f`: for a hit, `xy` is the hit pixel minus this pixel (in whole pixels), `z` is `log2(pdf)` and `w` the confidence in (0, 1]; for a ray that found nothing, `xy` is the octahedral encoding of the direction, `z` the same `log2(pdf)` and `w` is -1; a pixel that traced no ray holds zero. A mirror ray carries 15 in `z` in place of a density. ## The march `ssr_trace` walks the ray through the depth buffer. Steps are uniform in **screen** space, not world space. A ray heading toward the horizon covers enormous world distance across a few pixels, so stepping in world units there means either missing every thin occluder near the camera or spending the whole budget on distance nothing can be seen at. The world parameter is recovered from the screen parameter through `1/w`, which is what interpolates linearly under perspective. At each step the ray's world position is compared against the world position reconstructed from the depth sample under it. Comparing in world space is what lets `thickness` mean a distance in world units rather than a depth-buffer epsilon whose meaning changes with range. The march looks only for the **crossing**, where the ray first passes behind the depth buffer. Thickness is tested after bisecting that crossing, not during the march: one march step covers roughly as much depth as a surface is thick, so a ray tested during the march can jump from in front of a surface to well behind it without ever landing inside it. Bisection runs for whichever is larger, the quality tier's budget or however many halvings bring one march step under `thickness`. A coarse march that stopped bisecting early would leave the crossing bracketed more loosely than a surface is thick, and every hit would then fail the thickness test, so long-range reflections would vanish outright instead of thinning. A rough pixel's ray marches fewer steps and refinements (down to 0.35 of the tier's, reached 0.65 of roughness above a mirror), because the resolve blurs what the rays find. A hit on a surface that faces along the ray (what is on screen there is that surface's far side) is trusted at half the confidence. ## The resolve For each pixel the resolve gathers its own ray and up to `taps` neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`) on a disk of up to 6 px that turns with the pixel and the frame and grows with roughness. A neighbour counts only where its normal is within 0.9 of the pixel's and its depth within 5 percent. Each ray is weighed by the pixel's own lobe: `D · Vis · cos / pdf`. A pixel's result is the light of the rays that hit and the share of the lobe they cover. A ray that found nothing counts toward the lobe and carries no light. The history accumulates that result, premultiplied, at up to 0.9 of the previous frame for a rough surface and none for a mirror, with the history's light and coverage both held to the mean plus or minus 1.25 standard deviations of the rays gathered: a reflection whose rays now find nothing keeps nothing. ## What the channel holds `@scene.reflection` holds linear radiance in `.rgb` and in `.a` the share of the lobe the screen answered, multiplied by `intensity` and by the hand-over above `roughnessCutoff`. A surface at or below the cutoff keeps the full share, one 0.1 above it holds zero, and between the two the share fades. A miss is a zero the material reads as "the environment alone". The channel is cleared at the top of every scene render this feature does not run for, so such a frame reflects the environment alone too. The passes read the light the previous frame ended with, so they run on the lit channel alone (`debugChannel = 0`); a camera drawing a diagnostic pass is drawn lit first, unpresented, so the passes run for where that camera stands, and the diagnostic reads the channel gathered for it. ## Memory Each view that draws the feature holds three screen-sized `rgba16f` images: the rays and the history pair. At 1080p that is about 16.6 MB each, about 50 MB for the viewport.
▲ 0↑ born
·
shadermodule · born here
❒asset
# ssr_common The screen-space reflection passes' shared ground: the view-space reconstruction from depth, the ray-to-screen projection the march steps along, the GGX lobe helpers (distribution, masking, visible-normal sampling and its density), the octahedral direction coding, the per-pixel noise and the frame it is turned to, the camera and surface reconstruction both passes read, and the constants that fix the lobe sampling (the mirror roughness, the hand-over width, the neighbourhood radius, the history weight). Included with `#include "@builtin::systems.reflections.ssr_common"` by a shader that declares the bindings `frame_cam`, `scene_depth`, `scene_normal`, `scene_material`, `ssr_params` and `history_state` (the feature's history target's state buffer) and includes `shaderModules.gbuffer_material`.
▲ 0↑ born
·
computeshader · born here
❒asset
# ssr_resolve Gathers each pixel's reflection lobe from the rays the trace drew, accumulates it over frames, and writes the result into `@scene.reflection`. A pixel's lobe is the GGX distribution its roughness describes. The pixel's own ray and the rays of up to `taps` neighbours on a disk (turned by pixel and frame, radius up to 6 px, growing with roughness) are weighed against that lobe: `D · Vis · cos / pdf`, where `pdf` is the density the neighbour's ray was drawn with. A neighbour counts only where it shows the same surface: its normal within 0.9 (cosine) of the pixel's and its depth within 5 percent of the pixel's. Each ray carries the place it hit, not the light. The resolve reads the light from `@scene.colorHistory` where the hit stood in the previous frame, and takes a sky hit's direction from the camera ray through the sky pixel. The output states two things per pixel: `.rgb`, the light of the rays that found something on screen, and `.a`, the share of the lobe those rays cover. A ray that found nothing counts toward the lobe and carries no light, so a lobe the screen answers half of is `a = 0.5`, and the material fills the other half from the probes and the sky. `.a` also carries `intensity` and the hand-over above `roughnessCutoff`. The accumulated value is stored premultiplied in the feature's history target, and every frame the history is held to what this frame's rays found, within 1.25 standard deviations of their mean: - its coverage, to the coverage of every ray that reached an answer: a hit covers by its confidence, and a ray that left the screen through open space covers nothing, so a reflection whose rays now find nothing keeps nothing; - its light, to the light of the hits, in a space where bright values do not own the average. A pixel whose rays found no light keeps no history. A surface above roughness 0.25 keeps up to 0.9 of the previous frame; a surface below 0.1 keeps nothing, takes no neighbours and reads its one ray. A surface in between whose lobe is narrower than a pixel lends no neighbour's light to its own, and reads its 4 nearest rays (within 1.5 px) for the spread its history is held to. ## Includes - `ssr_common` - `gbuffer_material` - `display` ## Bindings | name | kind | |------|------| | `ssr_rays` | `texture2d` | | `scene_color` | `texture2d` | | `scene_depth` | `texture_depth` | | `scene_normal` | `texture2d` | | `scene_material` | `texture2d` (`sample: uint`) | | `history_prev` | `texture2d` | | `frame_cam` | `buffer` | | `ssr_params` | `buffer` | | `history_state` | `buffer` | | `history_out` | `storage2d (rgba16f)` | | `ssr_out` | `storage2d (rgba16f)` |
▲ 0↑ born
·
computeshader · born here
❒asset
# ssr_trace Draws one ray per pixel from the pixel's GGX lobe, marches it through the depth buffer and reports where it hit. ## Includes - `ssr_common` - `gbuffer_material` - `display` ## Bindings | name | kind | |------|------| | `scene_depth` | `texture_depth` | | `scene_normal` | `texture2d` | | `scene_material` | `texture2d` (`sample: uint`) | | `frame_cam` | `buffer` | | `ssr_params` | `buffer` | | `ssr_rays` | `storage2d (rgba16f)` |
▲ 0↑ born
◐
material · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# Shader (asset type) A shader is a WGSL program that runs on the GPU. Materials reference shaders and supply property values; renderable entities reference materials, not shaders directly. This README is the canonical reference for writing **every** kind of shader — it covers all domains, the surface authoring contract, the material property schema, the engine library functions you can call, and how a shader registers and compiles. > New to how shaders, materials, meshes, and textures relate as assets and live > GPU resources? Read `core/resource-model` first. ## Folder shape A `.shader` is a folder asset: ``` <name>.shader/ shader.wgsl # the WGSL body (required) properties.yaml # the material property schema (optional; surface shaders) README.md # a one-paragraph description of THIS shader (required) .metadata # asset metadata ``` Each file carries a committed `.meta` sidecar pinning its stable guid. The identity is `<name>` (the `.shader` suffix strips). A shader's material properties are exactly the ones its `properties.yaml` declares: a shader with no `properties.yaml` declares none, and the engine reads no property from the WGSL body. A `.wgsl` file standing on its own, outside a `.shader` folder, is WGSL source rather than a shader: a material draws with the `.shader` folder that holds it as `shader.wgsl`. Materials and other assets reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw string. ## Domains The first line of `shader.wgsl` declares the domain: ```wgsl // @domain: surface ``` | Domain | What it is | You write | |---|---|---| | `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. | | `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `compute` | GPU data processing, no rasterization. | An `@compute @workgroup_size(...)` entry over storage buffers; you write the `@group/@binding` lines yourself. For compute work, the `.computeShader` assetType (see below) generates them for you. | `// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui` as further spellings of `post-process` and `screen`. A body carrying no `@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body declares, a further spelling as the domain it names. Any other name is refused where the shader registers, with an error naming the spellings that resolve, so a shader reaches the renderer only under a domain the compiler scaffolds. Particles are drawn and simulated through these domains like anything else: the particle package's `particle_sprite` and `particle_mesh` are `surface` shaders, and its simulation, culling and sorting steps are `.computeShader` assets. ## Texture coordinate space A shader that samples a texture through a coordinate it builds itself declares which space that coordinate lives in, on a line beside `@domain:`: ```wgsl // @domain: surface // @uv_space: world ``` | Value | The coordinate | A material's `uv_scale` means | |---|---|---| | `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. | | `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. | Texture residency reads the declaration to work out how finely a frame samples each texture: a material laying eight copies of its texture across a surface samples each copy at an eighth of the surface's size, and the mip level that serves it is three levels coarser than the surface's own footprint implies. Leaving the line out puts the shader in mesh space, which is what sampling `input.uv` is. `renderer.textureStreaming().textures` reads back the span each texture was measured at and the level that span asked for. **Compute shaders have their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`. **Surface**, **sky**, **post-process**, and **screen** shaders all get engine-generated scaffolding — you write only `fragment()` and declare properties in `properties.yaml`; the engine generates the entry points and the group(1) material interface. (Each domain's `fragment` takes a domain-specific input instead of `FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and "Post-process & screen shaders" below.) Compute shaders get the same treatment via the separate `.computeShader` assetType (write only `@compute fn main`, declare bindings in `bindings.yaml`). The `compute` domain here writes its own entry points directly — see `man compute`. ## Surface shaders A surface shader writes **only** the parts that are unique to it. The engine owns all the scaffolding — the vertex stage, every render-mode entry point (`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights, shadows, and the material rows), and the material interface generated from `properties.yaml` (`material` and your texture slots). Adding a render path never touches your shader. Inside `fragment()` you have access to exactly four things — nothing is hidden: 1. **`input: FragmentData`** — the interpolated per-fragment surface data the engine hands you: world position, world normal, uv, view direction, vertex colour, and more. Every field is in the `FragmentData` table below. 2. **`material.*` and your textures** — the material inputs **you** declare in `properties.yaml`. The mapping is mechanical: a scalar property named `foo` becomes `material.foo`; a texture property named `bar` becomes `bar` (the texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields your `properties.yaml` declares and no others — to add an input, add a property. List what a shader exposes with `shaderRef:getProperties()` or `asset.inspect("<name>")`. 3. **Engine state** — the scene's camera, lights, time, and shadows that the renderer binds for every surface shader. In a surface shader `uniforms.*` (sun direction/colour, ambient, `camera_pos`, `time`) and the punctual lights (`zero_point_light(i)`) are always in scope (a post-process shader has neither; its section below names what it reads instead); the shadow functions come from `#include "@builtin::shaderModules.shadows"`, and the light of the sky, the reflection probes and the light-probe volumes from `zero_pbr_surroundings_light` in `@builtin::shaderModules.pbr_shading`. This is how you light a surface **without** the prebuilt PBR — see "Engine state" and "Writing your own shading" below. 4. **Library functions** you `#include` (see "Library includes"). A shader and its property schema go together. The two files below are a complete surface shader: `properties.yaml` — declares the material inputs: ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } - { name: roughness, type: float, default: 0.5, min: 0, max: 1 } - { name: metallic, type: float, default: 0.0, min: 0, max: 1 } - { name: base_color_texture, type: texture, default: white } ``` `shader.wgsl`; those declarations are read as `material.base_color`, `material.roughness`, `material.metallic`, and the `base_color_texture` / `base_color_texture_sampler` pair: ```wgsl // @domain: surface #include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes" fn fragment(input: FragmentData) -> vec4<f32> { var s = zero_pbr_default_surface(input); s.albedo = material.base_color.rgb * textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb; s.perceptual_roughness = material.roughness; s.metallic = material.metallic; return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a); } ``` `fragment()` returns the final colour. The engine forces no lighting model on you — flat, toon, PS1, dithered, or PBR are all just different `fragment()` bodies. Calling `zero_pbr_shade` is opt-in. ### The two surface bodies, and what each gives up A surface shader exposes one of two entry points, and which one decides how much of the shader the engine can see: | Body | The engine gets | PBR debug passes and the G-buffer read | |---|---|---| | `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the surface behind it where the body hands one over: `zero_pbr_shade` hands over the `PbrSurface` it lights, and a body that lights itself hands over its own with `zero_publish_shaded_surface` | the surface the body handed over; where it handed none, the debug passes draw magenta, the "no data here" marker | | `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the surface | Both are first-class: `fragment()` is what you want when the shader owns its own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }` (and `roughness` / `metallic` / `ao` / `emissive`) answers about your material for either body wherever the engine has the surface — writing the same `PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives one answer per channel. `pbr.shader` exposes `surface()`. #### Handing the engine the surface a self-lit body draws A `fragment()` body that lights itself by its own math (toon, cel, flat, PS1, dithered) states the surface it draws with one call, always in scope in a surface shader: ```wgsl zero_publish_shaded_surface(albedo, normal, emissive, perceptual_roughness, metallic, occlusion); ``` | Argument | Type | What it states | |---|---|---| | `albedo` | `vec3<f32>` | the colour the surface reflects, linear, in [0, 1] | | `normal` | `vec3<f32>` | the world-space normal the body shades with (normal map applied) | | `emissive` | `vec3<f32>` | the light the surface gives off, linear | | `perceptual_roughness` | `f32` | 0 a mirror, 1 fully rough | | `metallic` | `f32` | 0 a dielectric, 1 a metal | | `occlusion` | `f32` | the material's own ambient occlusion, 1 none | The call changes nothing about the pixel the body returns; it states what that pixel is a picture of. The last call before `fragment()` returns is the one the engine reads, and it reads it into: - **The debug passes**: `albedo`, `roughness`, `metallic`, `ao`, `emissive` and `reflection` answer with the stated surface instead of magenta, and `normal`, `shadow` and `shadow_depth` read the stated normal. - **The G-buffer**, on the deferred render path: its normal (`@scene.normal`, `zero_scene_normal`) carries the stated normal, and its material (`@scene.material`, `zero_scene_material`) the stated albedo, metallic and roughness. Every screen-space feature and full-frame pass that reads the surfaces reads these, among them screen-space reflections, contact shadows, capsule occlusion, area lights, the environment lighting and radiance cache passes, surface weather, temporal antialiasing's surface restate, and a post-process effect or render feature reading the surface helpers. A `fragment()` body that hands over nothing leaves the G-buffer holding the triangle's interpolated normal, a base colour equal to the colour it returned brought into [0, 1] by its largest component, metallic 0 and roughness 1, so a pass that reads roughness takes it for a fully rough dielectric. The emissive argument reaches the `emissive` debug pass. The light a surface gives off is already in the colour its body returns, so it adds nothing to the frame; `@scene.emissive` holds the light a later pass stamps onto the surface. A cel-shaded body, its surface handed over: ```wgsl // @domain: surface #include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light fn fragment(input: FragmentData) -> vec4<f32> { let n = normalize(input.world_normal); let albedo = zero_take_scene_decal(material.base_color.rgb); let sun = normalize(-input.light_direction); // The sun's N·L rounded to the nearest third: 0 on a face turned from the sun. let band = round(max(dot(n, sun), 0.0) * 3.0) / 3.0; let lit = input.light_color * input.light_intensity * band / ZPBR_PI + zero_pbr_surroundings_light(input, n, albedo); zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0); return vec4<f32>(albedo * lit, material.base_color.a); } ``` `capture { pass = "normal" }` is a geometry read rather than a material one, so it answers for every shader: the normal of the surface where one was handed over, and the interpolated normal of the triangle where none was. It is the same normal the frame's normal buffer carries, which is what a screen-space pass reading `@scene.normal` sees. `shaderRef:shadingModel()` reports which one a shader ended up with — `"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`. #### Decals on a self-lit body A decal projector stamps its colour over the opaque surfaces before anything shades (`@scene.decal`). `zero_pbr_shade` lays it over the base colour it lights, so a `surface()` material and a `fragment()` body lighting through `zero_pbr_shade` show the decal lit and shadowed like the rest of the surface. A body that lights itself takes the decal the same way by passing its base colour through one call before its lighting: ```wgsl let albedo = zero_take_scene_decal(material.base_color.rgb); ``` A body that takes none gets the decal laid over the colour it returned, unlit, and over the albedo it published. ### Optional vertex hooks ```wgsl // Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the // already-skinned, morph-applied local position). Return the modified vertex. // The `v` parameter is immutable (WGSL function params are), so copy it into a // `var` first and modify that. fn vertex(v: VertexData) -> VertexData { var out = v; out.position += out.normal * sin(out.time) * 0.1; return out; } // Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two // things you can do here, separately or together: // * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering; // * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its // world_normal + the light context and the engine forwards the result into the // interpolated `vertex_color` the fragment reads. fn vertex_clip(v: ClipVertex) -> ClipVertex { var out = v; // Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading). let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0); let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l; out.color = vec4<f32>(v.color.rgb * lit, v.color.a); out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap return out; } ``` #### Geometry built per instance: grass, kelp, hair cards, debris `vertex()` knows which vertex of which instance it places: `VertexData.vertex_index` is the vertex's index in its mesh and `VertexData.instance_id` the instance's slot, whose lanes `zero_object_data(v.instance_id, lane)` reads. A hook can therefore build its geometry rather than displace it: a strip mesh drawn thousands of times by `renderer.mesh.drawInstanced`, each copy shaped, sized and bent from the lanes of its `instanceDataBuffer`, becomes a field of grass blades, kelp fronds or hair cards that sway with `v.time`. Being a surface shader, it is lit, shadowed (it casts the shape the hook built), motion-vectored and fogged like the rest of the scene. The rendering-instance-data guide (`guides { path = "topics/rendering-instance-data" }`) has a worked blade field; a render feature's raster pass (`types/rasterShader`) is the hand-written alternative, a vertex and fragment program with its own pipeline. #### Declaring how far a hook moves geometry: `vertexBoundsDilation` Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges: ```yaml properties: - { name: sway, type: float, default: 0.5, min: 0, max: 4 } # 0.4 x sway, at sway's largest value. - { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 } ``` Each material sets its own value (a material that sways less can set less, one moved farther sets more), and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; its geometry is frustum-culled against its undisplaced bounds, and occlusion culling keeps it in the frame wherever it stands. ### Structs the engine passes you `FragmentData` (input to `fragment()`): | Field | Type | Meaning | |---|---|---| | `world_position` | `vec3<f32>` | fragment world-space position | | `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) | | `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) | | `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) | | `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping | | `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) | | `view_position` | `vec3<f32>` | camera world position | | `view_direction` | `vec3<f32>` | normalized world-space direction the camera sees this point from: toward the camera's position under a perspective projection, against its forward axis (the same for every point) under an orthographic one | | `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down | | `light_color` | `vec3<f32>` | sun colour | | `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera | | `ambient_color` | `vec3<f32>` | the colour of the scene's flat ambient term, one colour for every direction. The light of the captured sky, the reflection probes and the light-probe volumes along a normal, which a PBR surface takes as well, is `zero_pbr_surroundings_light` (see "Engine state") | | `ambient_intensity` | `f32` | the flat ambient term's intensity as it reaches this pixel: the scene's ambient occlusion is already in it (times `ambient_visibility`), so a crease darkens under the ambient with no work in the shader | | `ambient_visibility` | `f32` | the share of the light of its surroundings that reaches this pixel: 1 minus the scene's ambient occlusion here, 1 where nothing occludes it. Multiply it into any light of the surroundings you gather yourself (a sky colour, a reflection-probe or environment sample); `ambient_intensity` already carries it. `zero_scene_bent_normal(input.frag_coord.xy, n)` names the direction the open part of the hemisphere faces, `n` where no pass wrote one | | `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither | | `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows | | `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name | | `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes | | `front_facing` | `bool` | true for front faces (double-sided shading) | | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | `shader_data` is the per-instance channel, and it is what lets ONE material serve many entities that differ in a value — a dissolve at its own progress per subject, a hit flash at its own age, a fill level per instance. The alternative is a material per entity, which is a separate pipeline binding and a separate row in the material table for every one of them. ```wgsl const DISSOLVE_LANE: u32 = 0u; fn fragment(input: FragmentData) -> vec4<f32> { let progress = input.shader_data[DISSOLVE_LANE].x; ... } ``` ```lua -- one material on twenty entities, each at its own progress renderer.instanceData.set(subject, 0, progress) renderer.instanceData.clear(subject) -- back to zero lanes ``` The engine attaches no meaning to a lane: a shader and whatever writes it agree what each one carries. Name the indices in the module that writes them. `renderer.instanceData.laneCount()` is how many there are. The same lanes reach a hardware-instanced population through `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, on slots no entity owns. `VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph applied), `normal`, `uv`, `color`, `time`, and which vertex of which instance it is: `instance_id` (`u32`, the instance's slot — `zero_object_data(v.instance_id, lane)` reads the lanes the fragment gets as `shader_data`) and `vertex_index` (`u32`, the vertex's index in its mesh). Both hold the same values in the colour pass, the depth views, every shadow page and the previous-frame evaluation, so geometry a hook builds from them — a blade placed and bent by its instance's lanes, a strip shaped by its vertex's index — lands in the same place in each. The rendering-instance-data guide has a worked blade field. `ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context: `clip_position`, `world_position`, `world_normal`, `uv`, `view_position`, `view_direction`, `light_direction`, `light_color`, `light_intensity`, `ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of the frame being evaluated), and where the vertex stands on its instance: `local_position` (its position in the mesh, after `vertex()` and before the instance's world transform), `object_origin` (the world position of the instance's origin), `object_scale` (the world length of the instance's x, y and z axes) and `object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) — what a camera-facing card, a shard grown about its own base, or anything placed per instance is built from. **Writable:** `clip_position` (snap / jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's own vertex colour passes through). `vertex()` and `vertex_clip()` run in the vertex stage, which reads the frame uniforms (`uniforms.*`, and the `ClipVertex` members built from them), the scene buffer (`zero_object_data`, `zero_object_visuals`, the node transforms), the material interface and a `read` buffer property. The point, spot and area lights (`zero_point_light`, `zero_punctual_projection`), the shadow maps, the environment and light probes, the feature textures, the scene depth, colour and reflection copies and a `@group(2)` buffer the shader declares `read_write` are visible to the fragment stage alone: read them in `fragment()` or `surface()`. A shader whose vertex hook reaches one fails to compile, and the error names the stage, the binding and the calls that reach it. ### Each hook runs twice: this frame and the one before it A vertex hook decides where the surface IS, so it also decides where the surface WAS. The engine runs every hook a shader declares a second time, over the same vertex standing one frame back — the previous-frame position stream, with `time` = the clock that frame was drawn at and (for `vertex_clip()`) `view_proj` = the view-projection it was drawn with. The motion vector the renderer publishes is taken between the two results, so a displacement that moves with time reports the velocity of the displaced surface, and a displacement that does not move reports the motion of the transform alone because the identical offset appears on both evaluations and cancels. What that asks of a hook: - **Take the frame from the argument.** `v.time` is the clock of the evaluation being run; `uniforms.time` is always this frame's. A displacement built on `uniforms.time` is identical on both evaluations, so its motion vector cancels to exactly zero. The same holds for `v.view_proj` against `uniforms.view_proj`: a clip hook that rebuilds its position from world space through `uniforms.view_proj` reprojects the previous frame with this frame's camera, and reports no camera motion at all. The wind helpers come in both shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)` inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one. - **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously — a falling drop that restarts at the top, a looping offset — differences its jump as velocity on whichever frame it wraps. Compute the wrap COUNT from `uniforms.time` and the position within the cycle from `v.time`, and both evaluations share the same cycle, so the surface reports the speed it fell at. `@builtin::shaders.rain_material` and `snow_material` do exactly that. The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and camera-position context are this frame's on both evaluations, so a hook that displaces along its normal reports the motion of the transform plus this frame's displacement. ## Engine state — point lights & shadows This is what the renderer binds for a **surface** shader. A post-process shader reads none of it: its engine state is `PostEngineData` (see "Post-process & screen shaders"), and a full-frame effect driven by the scene's lights takes the render-feature route that section names. The common lighting state — the sun (`input.light_direction` / `light_color` / `light_intensity`), the scene's flat ambient term (`input.ambient_color` / `ambient_intensity`), the camera (`input.view_position` / `view_direction`), and `input.time` — is already on `FragmentData`, so most shaders never touch the raw engine state. The flat ambient term is one colour for every direction; the light the captured sky, the reflection probes and the baked light-probe volumes hand a surface along its normal comes from `zero_pbr_surroundings_light(input, n, albedo)` (`@builtin::shaderModules.pbr_shading`), which holds the flat term as well and is the ambient light a PBR surface is lit by. The one thing not on `FragmentData` is the punctual-light array (its length varies), which is always in scope. A scene can hold up to 1024 lights, so a fragment walks the ones the light grid lists where it stands, which hold every light that can reach it: | Expression | Type | Meaning | |---|---|---| | `zero_lights_near(world_pos)` | `ZeroLightsNear` | the lights that can reach a fragment at `world_pos`; `.count` of them | | `zero_light_near(near, k)` | `u32` | the index of the `k`th of them, for `zero_point_light` | | `uniforms.point_light_count` | `u32` | number of lights the frame shades under, every one of them | | `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) | | `zero_punctual_projection(i)` | `PunctualProjection` | a spot or area light's projection: `view_proj`, the frustum its cookie and shadow are placed by, and `cookie_layer` | `PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`, `cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot). Shadows come from `#include "@builtin::shaderModules.shadows"`: - `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed. - `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each. - `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch. - `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing. ## Writing your own shading The engine forces no lighting model — `zero_pbr_shade` is just one option. You can light a surface yourself from the state above. Here is a complete custom-lit (Lambert diffuse) surface that takes the engine's lights and surroundings and no PBR BRDF: ```wgsl // @domain: surface #include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light; brings in the shadow functions fn fragment(input: FragmentData) -> vec4<f32> { let n = normalize(input.world_normal); let albedo = material.base_color.rgb; // Directional (sun) light: Lambert N·L, attenuated by its shadow. let sun = normalize(-input.light_direction); // surface -> sun let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction); var direct = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow; // Point + spot lights: the ones that can reach this fragment. let near = zero_lights_near(input.world_position); for (var k = 0u; k < near.count; k = k + 1u) { let pl = zero_point_light(zero_light_near(near, k)); let to_light = pl.position - input.world_position; let dist = length(to_light); let l = to_light / max(dist, 1e-4); let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0); direct += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten; } // A Lambert surface sends back albedo / π of the direct light on it, // the diffuse lobe of the PBR model. var lit = direct / ZPBR_PI; // The light of the surroundings: the flat ambient, the captured sky, the // reflection probes and the baked light-probe volumes, with the scene's // ambient occlusion in it — the ambient light a PBR surface takes. It is // irradiance already weighed for a diffuse surface, so it takes no π. lit += zero_pbr_surroundings_light(input, n, albedo); // The surface this pixel draws, for the debug passes and the G-buffer. zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0); return vec4<f32>(albedo * lit, material.base_color.a); } ``` The example declares `base_color` in its `properties.yaml`: ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } ``` - **Unlit:** skip the lights and return your colour directly. - **Toon / PS1 / custom:** start from the body above and band, quantize, or warp it however you like. Keep the direct light over π and `zero_pbr_surroundings_light` as the ambient term, and the surface stands at the brightness of the PBR materials around it; the flat ambient (`input.ambient_color * input.ambient_intensity`) alone leaves out the sky and the probes, and under a sky with no flat ambient a face turned away from the sun draws black. - **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes") instead of writing the BRDF by hand. It hands the engine the surface itself. ## Material properties — `properties.yaml` A surface shader declares its material properties in a sibling `properties.yaml`. The engine GENERATES the entire group(1) interface from it — the uniform struct (`material.<name>`) plus a texture/sampler pair per declared texture. You write no `@group`/`@binding` lines. ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } - { name: roughness, type: float, default: 0.5, min: 0, max: 1 } - { name: metallic, type: float, default: 0.0, min: 0, max: 1 } - { name: emissive, type: color, default: [0, 0, 0, 1] } - { name: base_color_texture, type: texture, default: white } - { name: normal_texture, type: texture, default: flat_normal } ``` | `type` | WGSL field type | Notes | |---|---|---| | `float` | `f32` | optional `min`/`max` for editor sliders | | `float2`/`float3`/`float4` | `vec2/3/4<f32>` | | | `color` | `vec4<f32>` | linear RGB colour and alpha, default is `[r,g,b,a]`; the shader reads it as written | | `int` | `i32` | | | `bool` | `u32` | | | `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) | A `color` holds linear RGB, the space lighting is computed in, the way `base_color` multiplies a colour texture's linear sample. A colour picked from a picture or written as a hex code is sRGB, and written as it is it reads paler and less saturated than picked: convert it first, `color.toLinear(assert(color.hex("#ff8800")))` (`{ r, g, b, a }`: `#ff8800` is `{ r = 1, g = 0.246, b = 0, a = 1 }`), and write that. In the shader you read scalars as `material.<name>` and sample textures as `textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture samples its default, so a shader can always sample — no presence flag needed. `vertex()` reads the same material interface, so a height or deformation map drives displacement from the slot it was bound to. A vertex stage has no implicit derivatives, so sample it at an explicit mip there: `textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`. ## Sky shaders A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only** `fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each pixel — and declare tunables in `properties.yaml` exactly like a surface shader (read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface, and reconstructs the world-space ray; there is no separate sky renderer — a sky material runs through the same material pipeline, just on a fullscreen triangle. A sky pipeline binds group(0) and the group(1) interface alone, so a sky that reads a `buffer` property or any other `@group(2)` binding fails to compile, and the error names the binding and the calls that reach it. `SkyInput` (the only argument) carries: | Field | Type | Meaning | |---|---|---| | `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel | | `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` | | `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) | | `camera_pos` | `vec3<f32>` | world-space camera position | | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | | `constants` | `SkyConstants` | what the shader's `sky_constants()` returned for this draw (zeros when it declares none) | ```wgsl // @domain: sky fn fragment(in: SkyInput) -> vec4<f32> { let up = max(in.ray_dir.y, 0.0); let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up); return vec4<f32>(col * material.exposure, 1.0); } ``` Day/night comes from `sun_direction.y` (the directional light's elevation), so a sky shader never needs a time-of-day uniform — orient the light and the sky follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`, `equirect_sky`) are all authored this way; author a custom sky material and point a `Skybox` component at it. `fragment()` runs once for every pixel of the view and every texel of each environment-capture face. A value that holds for the whole draw (a colour mixed from the material and the sun's elevation, a `cos` of an angular size, an exponent derived from a property) goes in an optional `fn sky_constants(in: SkyConstantsInput) -> SkyConstants`, which the generated vertex stage evaluates once per draw. `fragment()` reads its result as `in.constants`. `SkyConstantsInput` carries `sun_direction`, `camera_pos` and `time` (the same values `SkyInput` holds), `sky_constants()` reads the material as `material.<name>` like `fragment()`, and `SkyConstants` is eight `vec4<f32>` slots, `v0` to `v7`, packed however the sky likes: ```wgsl // @domain: sky fn sky_constants(in: SkyConstantsInput) -> SkyConstants { let day = clamp(in.sun_direction.y * 2.0, 0.0, 1.0); var c: SkyConstants; c.v0 = vec4<f32>(mix(vec3<f32>(0.02), material.zenith_color.rgb, day), day); c.v1 = vec4<f32>(mix(vec3<f32>(0.01), material.horizon_color.rgb, day), 0.0); return c; } fn fragment(in: SkyInput) -> vec4<f32> { let up = max(in.ray_dir.y, 0.0); return vec4<f32>(mix(in.constants.v1.rgb, in.constants.v0.rgb, up), 1.0); } ``` A branch on an `in.constants` value is taken or skipped by every pixel of the draw together, so a term that only contributes some of the time (stars at night) costs nothing while it is off. The vertex stage has no implicit derivatives, so a texture read in `sky_constants()` is `textureSampleLevel`. ## Post-process & screen shaders `// @domain: post-process` and `// @domain: screen` shaders are authored exactly like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>` (post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables in `properties.yaml` (read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) material interface. **There are no `uniforms.params[i]` slots** — that convention is retired; every input is a named property. A **post-process** shader's `properties.yaml` carries one further, top-level key beside `properties:` — `space`, either `light` (the default) or `display`: ```yaml space: display properties: - { name: amount, type: float, default: 1.0, min: 0, max: 1 } ``` `light` is the scene's linear radiance — what every surface, the sky and every `afterLighting` feature write, unbounded above 1.0. `display` is the code values the `__display__` pass leaves behind after applying exposure and its tone curve — the 0-1 range a colourist's tool and a dithered or quantized effect expect. `postprocess.add`'s `opts.space` overrides what the asset declares for one registration. The chain converts at both ends of an effect that runs on a segment in the other space, so a light-space vignette still darkens a frame graded after `__display__`, and a lookup table built from a `.cube` export always sees the code values it was authored against, wherever the chain runs it. `space` also decides which layer a registration that names none lands on: a `light` shader grades `scene`, the segment holding the scene's own light, and a `display` shader grades `display`, the picture after `__display__` and before the UI lands on it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom", "shader"))` thresholds highlights that still stand above 1.0, and a lookup table registered the same way reads the code values it was built for and leaves every screen in the colours it declares. `opts.layer` names one explicitly — `"all"`, after the UI, is what an effect that must grade the interface says. A post-process shader may also declare the post stage of the frame it runs in, `stage:` — `optics` (the `scene` layer), `display` (the `display` layer) or `ui` (the `all` layer); `renderer.post.stages()` lists every stage with the colour space and resolution its picture is held in. A registration takes the declared stage unless `opts.stage` or `opts.layer` names another seam, and a stage the frame does not have, or one only render features run in, is refused naming the stages there are: ```yaml space: display stage: display properties: - { name: amount, type: float, default: 1.0, min: 0, max: 1 } ``` A **post-process** shader's `properties.yaml` carries a further, optional top-level key — `passes:`, the pass list the frame draws through, in order: ```yaml space: light passes: - { name: bright, entry: bright, scale: 0.5, inputs: [scene] } - { name: down1, entry: downsample, scale: 0.25, inputs: [bright] } - { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] } - { name: composite, entry: composite, inputs: [scene, up0] } ``` Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the view a pass draws at; the LAST pass takes none, since it draws at the view's size and writes the chain's output. `inputs` names what a pass reads — `"scene"`, the chain's input for this effect, or the name of an EARLIER pass — and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body; every input, `inputs[0]` included, is also reachable by index through `zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place the two reads of `inputs[0]` disagree: in an effect whose declared space differs from the segment it draws on, `zero_sample_scene` converts a `scene` input into that space while `zero_pass_input(0, uv)` hands back the segment's own, unconverted value. A shader declaring no `passes:` is one pass whose entry is `fragment`, and its generated WGSL is byte-identical to what it is without the key. A pass that is not the last writes a scratch target the effect owns — in the space the shader declared, view-sized times its own `scale` — allocated on the first draw and replaced whenever the size changes. `engine.params`, below, carries the drawing pass's own index, its scale, and its first input's texel size, so one shader body serves every level of a chain built this way. The worked example is the bloom: `@builtin::shaders.post.bloom` declares twelve passes — a threshold pass, five downsamples, five tent upsamples and a composite — out of four entries, since the five downsamples share one and the five upsamples share another, each level reading the one below it through `zero_pass_input` and telling itself apart by `engine.params`. Its own README walks the declaration. A declaration is refused at compile time — reported through `compileStatus()`, `postprocess.add`'s second return value, or a live effect's `status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does not define; an input naming a later pass, or naming neither `scene` nor an earlier pass; a `scale` outside `(0, 1]`; a `scale` declared on the last pass; a `buffer` property (group(2) carries the pass inputs); or a shader whose group(0) plus declared texture slots plus widest pass's inputs ask for more than the 16 FRAGMENT sampled textures one shader stage has. A **post-process** shader runs as a full-screen pass over the already-rendered frame. Its `fragment` argument and framework helpers: `PostInput`: | Field | Type | Meaning | |---|---|---| | `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) | | `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right | Framework helpers (always in scope — no include needed): | Call | Returns | Meaning | |---|---|---| | `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) | | `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" | | `zero_linear_depth_through(d, near, far, engine.view_proj)` | `f32` | that sample as a distance in metres along the camera's view axis, under a perspective or an orthographic camera — the one inversion of the reversed range (`zero_linear_depth(d, near, far)` is its perspective case alone) | | `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` | | `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads | | `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain | | `zero_camera_position()` | `vec3<f32>` | the world position of the camera the render being drawn looks from — the camera `engine.view_proj` belongs to, so on a capture or a render-to-texture camera it is that camera's. With a world position reconstructed from `zero_scene_depth(uv)` and `engine.inv_view_proj`, `normalize(world - zero_camera_position())` is the view ray | | `zero_scene_surfaces_drawn()` | `bool` | whether the scene's surface channels (the helpers below) hold the surfaces of the render being drawn: true on the deferred path from `afterOpaque` on, false on the forward path, which draws no G-buffer | | `zero_scene_normal(uv)` | `vec3<f32>` | the world-space normal of the surface at `uv` (`@scene.normal`), unit length; +Z where no surface stands, (0, 0, 0) where `zero_scene_surfaces_drawn()` is false | | `zero_scene_surface_flags(uv)` | `u32` | the surface flags the geometry pass wrote at `uv` (`@builtin::shaderModules.surface_flags`' `ZERO_SURFACE_FLAG_*`, in scope with the helper); 0 where `zero_scene_surfaces_drawn()` is false | | `zero_scene_material(uv)` | `ZeroGbufferMaterial` | what the surface at `uv` IS (`@scene.material`): `.base_color`, `.metallic`, `.perceptual_roughness`, each in [0, 1], unpacked by `@builtin::shaderModules.gbuffer_material`, which the surface group includes | | `zero_scene_shaded(uv)` | `vec4<f32>` | what the surface at `uv` SENT (`@scene.shaded`): its shaded colour, linear, with its coverage in alpha | | `zero_scene_emissive(uv)` | `vec4<f32>` | the radiance passes stamped on the surface at `uv` (`@scene.emissive`) | | `zero_display_exposure()` | `f32` | the exposure in force: the gain `__display__` multiplies the scene's light by before its curve, the value this frame's display pass draws with (1 where the chain carries none). Light times it is light in the units the picture shows it at, so a threshold judged against `light * zero_display_exposure()` picks the same highlights at every exposure | | `zero_middle_grey()` | `f32` | for an effect in light: the light `zero_sample_scene` reads that the picture shows as middle grey, 0.18 over the exposure in force on a segment holding the scene's light and 0.18 on a segment `__display__` already drew. What a grade pivots its contrast on, so middle grey holds where the picture shows it at every exposure | | `zero_picture_white()` | `f32` | for an effect in light: the light the picture's white stands at, the peak a grade holds. 1 (the white an SDR picture peaks at) on a segment `__display__` already drew, and 0 on a segment holding the scene's light, which has no peak | Engine data uniform `engine` (a `PostEngineData`): | Field | Type | Meaning | |---|---|---| | `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height | | `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index | | `view_proj` | `mat4x4<f32>` | this frame's view-projection | | `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) | | `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) | | `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. | | `exposure` | `vec4<f32>` | `x`=the exposure in force (what `zero_display_exposure()` reads) | | `camera_position` | `vec4<f32>` | `xyz`=the world position of the camera being drawn (what `zero_camera_position()` reads) | | `surfaces` | `vec4<f32>` | `x`=1 where the surface helpers read the render's own surfaces (what `zero_scene_surfaces_drawn()` reads) | The engine fills all of it **per render target**. A registered effect runs over the live viewport's frame AND over every offscreen one — a `capture` from a world-space station or orbiting an entity, a capture of a named camera, a render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj` and `inv_view_proj` are the camera THAT render was drawn from, while `resolution` is that target's own pixel size. So a pass reconstructing world space from `zero_scene_depth(uv)` reconstructs against the station and lens the capture asked for, and an offscreen frame is a picture of the effect as it stands at that station. (A render feature's passes reach an offscreen render the same way, against the same camera — the `renderFeature` assetType README carries that half, including `@frame.camera`, its own per-target camera input.) **The scene's surfaces.** The surface helpers above read the deferred path's G-buffer, the same channels a render feature names as `@scene.normal`, `@scene.material`, `@scene.shaded` and `@scene.emissive`, by screen uv at the exact texel (the channels are at the scene's raster size, so a pass at a `scale`, or after an upscale, reads the surface that stands at that point of the picture). A shader that names any of them compiles with the surface group, `group(3)`, which spends four of the stage's sampled textures beside its own slots and pass inputs; the render keeps a channel only while a running effect, or a render-feature pass's shader, reads it; a channel counts as read when an entry point of the compiled shader reaches its helper, so a helper in an included function nothing calls reads nothing. They hold this frame's surfaces at every layer of the chain and at every render-feature phase from `afterOpaque` on. With temporal antialiasing running, every layer of the chain reads the normal and the material restated at each pixel's centre, with no sub-pixel offset, so an outline found in the normals holds still under a still camera; `zero_scene_shaded` and `zero_scene_emissive` read the raster's own, with its sub-pixel offset. The renderFeature type README states the whole contract by stage and path. The forward path draws no G-buffer, so there every helper reads zero and `zero_scene_surfaces_drawn()` false: a look that needs the surfaces draws a picture of its own there (from depth, say) instead of reading a wrong one, and `postprocess.status()` names the channels the effect `reads` and, after a frame it drew with the substitute, the `substituteReason`. ```wgsl // @domain: post-process fn fragment(in: PostInput) -> vec4<f32> { let c = zero_sample_scene(in.uv); if !zero_scene_surfaces_drawn() || zero_scene_depth(in.uv) <= 0.0 { return c; } let n = zero_scene_normal(in.uv); let m = zero_scene_material(in.uv); let rim = pow(1.0 - abs(n.y), 4.0); return vec4<f32>(mix(c.rgb, m.base_color, rim * material.amount), c.a); } ``` **Lights.** A post-process shader reads no light data: `uniforms`, `zero_point_light(i)` and the light grid are the surface framework's, and a post shader naming them does not compile. An effect driven by the scene's lights (light shafts, a glow around each lamp, a scatter through fog) is a render feature pass at a scene phase (`afterDepthPrepass` through `afterLighting`) that binds `@scene.lights`, the punctual-light buffer (the renderFeature type README states its layout), with `@frame.camera` for the camera; the beams lights throw through the air are already the built-in `VolumetricLighting` component, whose `lightScattering` render feature (`@builtin::systems.volumetrics`) marches the view rays through the scene's own lights. An offscreen render keeps no view history of its own, so `prev_view_proj` there holds that same matrix rather than the frame before it, and a pass taking camera motion from the two reads none. On the viewport the pair is a frame apart, so camera motion is the one reading a capture answers differently from the screen. `postProcessing = false` on a capture is the one control that takes the chain off the frame it returns; it names the camera property the ephemeral capture camera is built with, so it scopes to that one capture. What a capture opts out of is the registered effects; `__display__` still runs on it, so the exposure and tone curve that turn the scene's light into a picture are on what a capture returns. A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses `__display__` itself, since a channel like that is a reading of the scene rather than a graded picture of it. The environment-cube capture bypasses it too, and for the same reason: a probe face carries radiance into the cube array, and `__display__` would fit that radiance to a display's code values — a picture of it rather than the value the PBR indirect term multiplies into its lighting. A complete post-process effect — a vignette via `fragment()` + `properties.yaml`: `properties.yaml`: ```yaml properties: - { name: intensity, type: float, default: 0.5, min: 0, max: 1 } - { name: radius, type: float, default: 0.75, min: 0, max: 1 } - { name: softness, type: float, default: 0.45, min: 0, max: 1 } ``` `shader.wgsl`: ```wgsl // @domain: post-process fn fragment(in: PostInput) -> vec4<f32> { let color = zero_sample_scene(in.uv); let intensity = max(material.intensity, 0.01); let radius = max(material.radius, 0.01); let softness = max(material.softness, 0.01); let center = in.uv - vec2<f32>(0.5); let dist = length(center); let vignette = smoothstep(radius, radius - softness, dist); let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity); return vec4<f32>(darkened, color.a); } ``` The asset above **defines** the effect. It enters the frame when something registers it: ```luau postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 }) ``` The registration names no layer, so the effect grades the layer its `space` belongs to: this vignette reads light, so it runs on `scene`, over the picture before the UI reaches it. Registering it is the one step that makes it render, so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards recompiles every effect registered from it, in place — the pass keeps its enabled state, priority, layer, tuned property values and bound textures, and draws the new pixels on the next frame. `postprocess.remove(name)` takes it back out of the chain and leaves the asset alone. Drive the named properties at runtime with `postprocess.setProperty(name, prop, value)` and bind texture properties with `postprocess.setTexture(name, prop, path)` (both keyed by the **property name**, never a slot index — see the post-process section of `man shaders` / the `postprocess.*` API). Read them back with `postprocess.describe(name)`: it carries the chain state `postprocess.status()` lists for that effect, the `properties` schema it was registered with, and the `values` each of those properties currently holds. Before the effect exists, `shaderRef:getProperties()` on the asset names the same schema, so what a pass takes is answerable either side of the registration. A **screen** shader is a standalone full-screen visual (UI background, procedural pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a `ScreenEngineData`: | Field | Type | Meaning | |---|---|---| | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | | `scroll` | `f32` | UI scroll offset | | `resolution` | `vec2<f32>` | render-target size in pixels | | `mouse` | `vec2<f32>` | mouse position | | `velocity` | `f32` | scroll velocity | ```wgsl // @domain: screen fn fragment(in: ScreenInput) -> vec4<f32> { let t = engine.time * 0.5; let col = vec3<f32>( sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5, sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5, material.brightness ); return vec4<f32>(col, 1.0); } ``` ## Library includes A library module is a **`.shaderModule` asset**: it only EXPOSES functions and structs and does nothing on its own (exactly like a Unity `.cginc`). You must call what you include. Include one by its identity, the same string you would hand `asset.resolve`: | Include | Exposes | |---|---| | `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting); `zero_pbr_indirect_visibility(FragmentData, PbrSurface) -> ZpbrIndirectVisibility` (the share of the surroundings' light each indirect lobe takes from the scene's ambient occlusion: `diffuse` with the light a crease bounces back, `specular` from the open cone around the bent normal); `zero_pbr_shade_with_visibility(FragmentData, PbrSurface, ZpbrIndirectVisibility) -> vec3<f32>` (the same lighting with that share stated by the caller); `zero_pbr_surroundings_light(FragmentData, n, albedo) -> vec3<f32>` (the diffuse light the surroundings hand the surface along `n` as `zero_pbr_shade`'s diffuse lobe takes it — lightmap, flat ambient, sky, reflection probes, light-probe volumes, the scene's occlusion — for a self-lit body to multiply by its colour); `zero_pbr_sun_visibility(FragmentData, PbrSurface) -> vec4<f32>` (the sun as it reaches the surface: rgb what translucent casters and a medium leave of it, a the share its shadow maps leave, zero where it puts no light on the surface), which a surface scales on its own terms and hands back in `PbrSurface.sun_visibility` | | `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)`; each light's `_with_kernel` form takes a shared `ZShadowKernel` (`zshadow_kernel()`) so several lookups of one fragment derive its filter rotation once | | `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access | | `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions | | `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) | | `@builtin::shaderModules.periodic_noise` | Value noise that repeats along x, for a pattern laid around a circle (a sky over the azimuth, a ring): `zero_azimuth(dir)` (the azimuth about +Y as a fraction of a turn, wrapping along -X), `zero_periodic_noise(p, period)`, `zero_periodic_fbm(p, period, octaves, lacunarity)` (each octave fits a whole number of cells in `period`, so the sum repeats every `period` and a pattern whose x runs over one period per turn closes with no seam), `zero_wrap_cell(cell, period)` and `zero_hash21(p)` for a lattice of one's own | | `@builtin::shaderModules.parallax` | Parallax occlusion for any lit shader with a height map: `zero_parallax(depth, max_steps) -> ZeroParallax` (the relief's depth in UV units, its steps, its fade distances and whether R is height or depth); `zero_parallax_march(FragmentData, height_texture, height_sampler, uv, ZeroParallax) -> ZeroParallaxHit` (the UV to read every map at, with `ddx`/`ddy` for `textureSampleGrad`); `zero_parallax_sun_visibility(FragmentData, PbrSurface, height_texture, height_sampler, hit, ZeroParallax) -> vec4<f32>` (the sun with the relief's self-shadow, for `PbrSurface.sun_visibility`, marched only where the sun lights); `zero_parallax_self_shadow(...)` for any other light direction. Tiled UVs keep every tile; the relief flattens with distance and toward a grazing view | | `@builtin::shaderModules.depth` | `zero_linear_depth_through(depth, near, far, view_proj)` — the one reading of a stored depth, for the projection the view-projection states; `zero_linear_depth` and `zero_linear_depth_orthographic` are its two cases | | `@builtin::shaderModules.ambient_light` (`zero::ambient_light`) | `zpbr_surroundings_irradiance(world_pos, n, flat_ambient)` (the diffuse light the surroundings hand a surface with normal `n`: the flat ambient, the captured sky and reflection probes, and the baked light-probe volumes, as the PBR model reads it) and `zpbr_surroundings_in_scatter(world_pos, flat_ambient)` (that light averaged over every direction: what a participating medium scatters). A compute pass binds `environment_map`, `environment_sampler` and `zero_environment` to `@scene.environment`, `@scene.environmentSampler` and `@scene.reflectionProbes` | | `zero::sun_shadow` | `zero_sun_visibility(p) -> f32`, `zero_sun_visibility_at(p, footprint) -> f32` and `zero_sun_visibility_seen_from(p, eye) -> f32`: how much of the sun reaches the world point `p` past the occluders that shadow the surfaces from it (1 unobstructed, 0 blocked), read from the sun's shadow pages at the finest level holding `p`, at the finest whose texel is no smaller than `footprint`, or, for air a camera at `eye` looks through, at the level the frame keeps pages for that air. What a participating medium shadows the sun's light by: haze, fog, clouds, shafts. A compute pass binds `sun_shadow` (`element: ZeroVsmUniform, array: false`), `lights` and `shadow_pool` to `@scene.sunShadow`, `@scene.lights` and `@scene.shadowPool` | | `zero::sky_visibility` | `zpbr_sky_visibility(p, dir) -> f32`: the share of the world's sky the world point `p` sees around `dir`, from the sky-visibility field over the scene's static geometry (1 where no field is published). A compute pass binds `zero_environment` (`element: ZeroEnvironment, array: false`) to `@scene.reflectionProbes` | | `@builtin::shaderModules.light_shadows` | `zero_light_shadow(li, p, footprint) -> f32`: how much of the light at row `li` of `@scene.lights` reaches the world point `p` past the occluders that shadow the surfaces from it (1 unobstructed, 0 blocked), read from the shadow pages at the mip whose texel is no smaller than `footprint`. What a participating medium shadows a point, spot or area light's beam by. A compute pass binds `lights` and `shadow_pool` to `@scene.lights` and `@scene.shadowPool` | | `@builtin::shaderModules.gbuffer_material` (`zero::gbuffer_material`) | `struct ZeroGbufferMaterial { base_color, metallic, perceptual_roughness }`; `zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial`; `zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial`, `zero_gbuffer_base_color`/`zero_gbuffer_metallic`/`zero_gbuffer_roughness(t, coord)` — the one unpacking of `@scene.material`'s `Rgba8Uint` texel into what a surface reflects | | `zero::scene_depth` | `zero_scene_depth(px: vec2<f32>)`, `zero_scene_depth_uv(uv: vec2<f32>)`, `zero_scene_depth_texel(px: vec2<i32>)`, `zero_scene_depth_size()`, `zero_scene_depth_is_sky(d: f32)`, `zero_scene_world_position(px
▲ -1↑ born
backing path · systems/procgen.package/nodes/io.nodebox/engine.procNode/engine.module

Problems

Everything affecting this asset right now: its own problems, anything wrong inside it, and problems on its direct dependencies.

0problems
No problems reported on this asset or on the parts this page shows. Parts it leaves out are not counted here.
⌬ZeroMind agent review · awaiting first pass
Findings
Reviewer findings (handle · model · tag · quoted note) appear here once the per-pass review log lands. Today only the rolled-up agent_score is exposed.
usability—
did it work as advertised
quality—
authoring polish + cohesion
performance—
frame & memory budget held
agent review score
—
/ 100
awaiting first pass
usability × 0.40
+ quality × 0.35
+ performance × 0.25
± compat factor

Usability ratings

Did the part work as advertised when consumers tried to drop it in. Separate from upvotes: those are taste; this is "did it function".

—%no reports yet
Sign in to report whether this part worked for you.
Discussion

Scoped to this part · feeds back into the world's score.

0comments
Sign in to post.sign in
No comments yet. Be the first.