Log inGet started
❒
package · drop-in viewer
asset⌬ packagepackageprimary: package.yaml·originates fromworld 07158574-5…●1problem

sky

No description provided.

by◐lumi·posted 22h 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.

This asset doesn't declare a schema or structured payload.

Sub-parts

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

Showing up to 3 levels deep. Open a part to see what it holds further down.

103+items
·
renderfeature · born here
❒asset
# material The material sky backdrop: the sky drawn by any sky-domain material, named in `material`, with `exposure` and `rotation`. It enqueues no pass. It writes one `Sky` row (`skyType = "material"`) on a temporary entity, which the engine draws as the scene's sky while that row is in force. It draws the sky and orients no light; light from the drawn sky reaches the scene through a member that captures it, such as `skyLight`. Name it as a sky's `backdrop` member for a painted, photographed or shader-made sky. ## Parameters Its parameters are its own settings and the shader properties of the material it names, each with the Field descriptor of the property's kind and the material's value as its default (`asset.schema(backdrop, { material = ... })`, and in a sky or a setup `backdrop/<property>` and `sky/backdrop/<property>`). A shader property named like one of its own settings (`material`, `exposure`, `rotation`) stays the material's. While every property value stated for it is the material's own, it draws the material itself. Once one differs, it draws a runtime copy of the material with the stated values laid over the material's own; the material asset is not written. A texture property's value binds that texture in the copy. Two applications of the backdrop share its one live feature, the way every render feature's do: the settings of the newest application to state something new are in force, and dropping it brings back the settings of the one before it.
▲ 0↑ born
·
renderfeature · born here
❒asset
# procedural The procedural sky backdrop: a day/night gradient from `zenithColor` through `horizonColor` to `groundColor`, shaped by `horizonHeight` (how far up the horizon colour reaches, below), with a sun disc and glow, stars and a moon, drawn by the `procedural_sky` shader over a runtime material of its own. It enqueues no pass. It writes one `Sky` row (`skyType = "procedural"`) on a temporary entity, which the engine draws as the scene's sky while that row is in force. The lights that follow the sky (`lighting.followSky`, as a `sceneLight` with `followSky` states) take the sun's direction from `timeOfDay`. An applied light (a `sceneLight`) keeps its own colour and intensity as its noon peak and lands at them multiplied by the curve of the sun's elevation: (1, 1, 0.95) and 1 from 30° up, warmer and dimmer toward the horizon (about 0.3 at 7°), and intensity 0 below it. A plain light takes the curve's colour and daylight 10 x `sunPeakIntensity` x the daylight factor (twice the sun's elevation, clamped to 0..1), zero below the horizon. `sunIntensity` controls the drawn disc, not the light a plain follower casts. A `sceneLight` with `skyOffset` keeps that offset from the sun. ## The colours drawn Three colour sets make the gradient, and the sun's elevation at the hour drawn says which shows: | Sun | What is drawn (both strengths 1) | |---|---| | 30° up and higher (about 08:00 to 16:00) | `zenithColor`, `horizonColor`, `groundColor` | | 0° to 30° up | the base colours, falling toward the night set as the sun sinks | | about 1° to 16° up (about 06:05 to 07:05 and 16:55 to 17:55) | also leaning up to half way toward `dawnZenithColor` and `dawnHorizonColor` | | below the horizon (about 18:00 to 06:00) | `nightZenithColor`, `nightHorizonColor`, `nightGroundColor` | `nightStrength` and `dawnStrength` (0 to 1, default 1) say how far each set draws over the base colours. The tint sets serve a sky that runs through the day (`autoCycle`), where one set of base colours cannot be both noon and midnight. A sky that holds one hour states its look in the base colours with both strengths at 0, so `zenithColor`, `horizonColor` and `groundColor` are drawn as written at that hour. When the sets draw over more than a fifth of the authored zenith and horizon at the stated hour, the backdrop says so: its `ApplyState.notice` (and a sky's `describeSky().notice`) names the hour, the share of the authored colours drawn, the set and the strength that mask them. ## The gradient's shape Above the horizon the sky runs from `horizonColor` at the horizon to `zenithColor` overhead. `horizonHeight` (degrees, 0.5 to 80, default 7.933) is the elevation where it is halfway between the two. At the default the sky 10° up is still half horizon colour, so a frame looking level reads mostly horizon. A sky whose overhead colour should show at eye level, with the horizon colour a band along the horizon, lowers it: at 2 the sky 10° up is 77% zenith colour and 30° up 94%; at 1 the sky 5° up already is three quarters. Raising it spreads the horizon colour up the sky. ```yaml # <name>.sky / sky.yaml: a teal-violet sky over an orange band members: - id: backdrop source: "@builtin::systems.sky.backdrops.procedural" values: timeOfDay: 17.7 zenithColor: [0.16, 0.22, 0.42] horizonColor: [0.95, 0.45, 0.18] horizonHeight: 2 dawnStrength: 0 nightStrength: 0 ``` The backdrop draws the sky. The gradient as drawn at the hour drawn is readable through `sky.drawnGradient()`; light from the drawn sky reaches the scene through a member that captures it, such as `skyLight`. With `autoCycle` on, the hour runs from `timeOfDay` at `cycleSpeed` game-seconds per real second on the session clock, so every client of a session draws the same hour; it holds still while gameplay is paused. Name it as a sky's `backdrop` member.
▲ 0↑ born
▣
module · born here
❒asset
# looks The procedural sky's named looks (`clear_day`, `sunset`, `sunrise`, `overcast`, `night`), each the field values it states: the hour, the gradient colours, the sun disc and glow, the stars and moon, the turbidity and the sun's noon light. `ProceduralSky.preset` applies one to the component, and the lighting toolbox's `setSky` lands one on the procedural backdrop drawn now.
▲ 0↑ born
·
renderfeature · born here
❒asset
# skyLight The light the scene takes from what is drawn behind it. It captures that picture into a cube of six textures it owns, gathers the cube into a diffuse term and a set of reflection bands, and adds both to every lit surface in a pass of its own, at the strengths its parameters state. Whatever draws the backdrop (a gradient, a material, a photograph, clouds) is what it captures: the capture is a render of the `captureLayers`, with no knowledge of what draws them. Every step is a call in its `init.luau`: 1. **Capture.** Six cameras, one per cube face, each 90 degrees across, stand at `capturePosition` drawing only `captureLayers` and running only the render-feature passes `captureFeatures` names: by default the ones an environment capture runs, so a fog or a volumetric medium filling the air stays out of the light that lights it. Each is held disabled and rendered once into a `faceSize` x `faceSize` texture. 2. **Gather.** `skyLight_faces` folds the six faces into one equirectangular map, which `ibl_irradiance` convolves into the diffuse term and `ibl_specular` into five reflection bands of rising roughness. These run on the frames after a capture. 3. **Light.** Every frame `skyLight_apply` adds both terms to the lit G-buffer, the diffuse term scaled by `diffuse` and the reflection by `reflection`. 4. **Publish.** With `publishReflection` on, `environment.captureSky` puts the sky, drawn from `capturePosition`, into the environment's sky slot: the reflection every surface the reflection probes leave uncovered shows, water and transparent surfaces among them, which the G-buffer pass never reaches. Turned off, or with the feature torn down, the slot is switched off. A capture is taken when the feature is set up, when what it draws changes (`captureLayers`, `captureFeatures`, `capturePosition`, `faceSize`, or `recapture`, a count an author changes to ask for one), and, with `followSky` on, when the scene's sky row or the direction of its sun changes, at most once per `recaptureInterval` seconds. The diffuse term and the reflection bands are gathered from every capture whatever the strengths, so a strength changed relights from them. A render drawn while the renderer still held builds for the scene (pipelines, shader compiles; the `pipelinesPending` of the face camera's `lastRender` in `camera.observe()`) holds the scene as it looked before they landed. The six faces are rendered again, at growing intervals of drawn frames, until one is drawn with nothing pending; `redraws` counts those repeats. ## Parameters | name | default | what it is | |---|---|---| | `diffuse` | 0.15 | The strength of the captured surroundings' diffuse light on surfaces, 0 to 4. | | `reflection` | 0.25 | The strength of the captured surroundings in surfaces' reflections, 0 to 4. | | `captureLayers` | `sky` | The render layers the capture draws. | | `captureFeatures` | `environment` | Which render-feature passes the capture runs: `environment`, the ones an environment capture runs (the sky and what is drawn into it; the air and overlays stay out), or `all`. | | `capturePosition` | (0, 0, 0) | Where the six capture views are taken from. | | `faceSize` | 64 | The width and height of each capture view, in texels. | | `followSky` | true | Whether a change to the sky row or the sun's direction takes a capture. | | `recaptureInterval` | 0.5 | The fewest seconds between two captures `followSky` takes. | | `recapture` | 0 | A count; any change takes a capture. | | `publishReflection` | false | Whether the sky also fills the environment's sky slot, the reflection a surface no reflection probe covers shows. | | `occlusionSource` | empty | The member whose picture of how much of the sky each surface sees (`live.skyVisibility`) scales the diffuse and reflection terms, as its identity; empty, the terms are not scaled. | With both strengths at 0 it enqueues no lighting pass and still gathers the captured environment, which other members read. The textures it captured into and gathered (`faces`, `environment`, `irradiance`, `reflection`), the number of captures taken (`captures`), of repeated renders (`redraws`) and of gathers that have written the irradiance and reflection maps (`gatherCount`) are readable at `modules.state("@builtin::systems.sky.skyLight.live")`. ```yaml # a setup member - id: skyLight source: "@builtin::systems.sky.skyLight" values: diffuse: 0.15 reflection: 0.25 ```
▲ 0↑ born
▣
module · born here
❒asset
# skyLightSource `skyLightSource.read(source)` answers the irradiance map a sky light (`@builtin::systems.sky.skyLight`) gathers and the `diffuse` strength it lights surfaces at, for a pass outside the sky light's own that the sky light lights: a participating medium, a height fog, the air the volumetric light marches. Each of those names its sky light in a `skySource` setting. An empty source, or one naming no live sky light, answers no map and a strength of 0, so a medium that names none takes no light from the sky; the pass then binds another texture in the map's place, which it leaves unread. The pass binds the map and reads it with `@builtin::systems.sky.skyLight_read`.
▲ 0↑ born
·
computeshader · born here
❒asset
# skyLight_apply Adds the captured sky's light to every lit surface: the diffuse term from the irradiance map and the reflection from the prefiltered bands, each scaled by its strength and by the share of the sky the surface sees. The `sky_occlusion` picture holds that share per pixel, red over the surface's hemisphere and green along its mirror direction; a picture holding 1 everywhere leaves both terms as the sky states them.
▲ 0↑ born
·
computeshader · born here
❒asset
# skyLight_faces Gathers six square views, each 90 degrees across, into one equirectangular map of the whole sphere. Each output texel looks along its direction, takes the face that direction leans furthest toward, and reads the texel of that face the direction passes through. Face order and bases (forward, up; right is their cross product): | binding | forward | up | |---|---|---| | `face_px` | +X | +Y | | `face_nx` | -X | +Y | | `face_py` | +Y | +Z | | `face_ny` | -Y | -Z | | `face_pz` | +Z | +Y | | `face_nz` | -Z | +Y | ## Bindings | name | kind | |------|------| | `face_px` .. `face_nz` | `texture2d` | | `env_out` | `storage2d (rgba16f)` |
▲ 0↑ born
·
shadermodule · born here
❒asset
# skyLight_read Reads the irradiance map a sky light (`@builtin::systems.sky.skyLight`) gathers, for a pass that is lit by the sky light outside its own G-buffer pass: a participating medium, a height fog, the air the volumetric light marches. - `zero_sky_light_irradiance(map, d)`: the light arriving at a surface turned toward `d`. - `zero_sky_light_in_scatter(map, strength, open)`: the light a point of the air takes and scatters evenly, the mean over the six axis directions, scaled by the sky light's `diffuse` strength and the share of the sky the point sees. The pass binds the map; `@builtin::systems.sky.skyLightSource` resolves the map and the strength of the sky light a setting names, and a strength of 0 where none is named, which reads nothing from the map.
▲ 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
# 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` | Seconds since boot. | | `ctx.frame` | Monotonic frame index. | | `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. | | `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". | ## Settings A feature declares the knobs it takes as `settings`, each a Field descriptor with a default, the way a component declares its public fields. 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.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.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. **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 compute shader's `ref:dispatch` and `ref:dispatchEx`. **The camera.** `@frame.camera` bound to a read buffer gives `vs_main` the view being drawn: `cam[9..13)` is its view-projection, the matrix the scene rasterized with, `cam[5..9)` the previous render's, `cam[13].xy` the sub-pixel offset this render's matrix carries, and `cam[4].xyz` its position. A raster pass runs once per view — the viewport, every capture, every render-to-texture camera — each through its own camera. **When it runs.** A raster pass runs at the phase it states, in order with the fragment and compute passes of that phase (by `priority`, then the order they were enqueued), so a later pass reads what it drew. `@scene.depth` as a depth target and `@scene.motion` as an output are this view's from `afterDepthPrepass` to `afterLighting`; at `afterScenePost`, `afterUi` and `afterPost` a raster pass draws into the composite (`@scene.color`) and its own render targets, testing against a render target's depth. A field holding a value of the wrong shape raises from `ctx.enqueue`, naming the field; a pass whose shader failed to compile, or whose targets or bindings do not resolve, is skipped with the reason in the log, said once until the reason changes. **Another way to draw an instanced field.** The guide `topics/rendering-instance-data`, section "Instanced foliage built in the vertex shader — grass, kelp, hair cards, debris", draws the same kind of field through an engine material: a surface shader's `vertex()` reads each instance's record with `zero_object_data(v.instance_id, lane)` and its `v.vertex_index` on a mesh drawn with `renderer.mesh.drawInstanced`. That field is lit, casts and receives shadows, writes motion vectors and takes fog and post-processing as every material does. A raster pass is a hand-written vertex and fragment program with its own pipeline, depth and blend — the shape a hand-written renderer ports into. ### Splat passes A splat pass draws every record of an f32 buffer as a camera-facing billboard — the raster primitive behind screen-space particle surfaces (the `fluidSurface` system is built entirely on it): ```luau ctx.enqueue { kind = "splat", phase = "afterLighting", output = depthRt.guid, -- or `outputs` for the thickness+color MRT splat = { buffer = "my_particles", -- compute-buffer name stride = 12, -- floats per record posOffset = 0, -- float offset of the position count = 200000, -- records to draw radius = 0.3, -- world particle radius channel = "depth", -- "depth" | "thickness" | "sprite" | "gaussian" velOffset = 4, -- optional: velocity → screen-space stretch stretch = 0.04, -- seconds of motion elongating the billboard colorOffset = 8, -- optional (thickness): + per-particle RGB → MRT weightOffset = 7, -- optional (sprite): per-particle intensity minY = -60.0, -- records below this y collapse (parked/dead) maxRadiusPx = 120, -- optional: cap on the projected pixel radius }, } ``` The `"gaussian"` channel draws the engine's packed splat records — what `renderer.splat.components` decodes a `.spz` or `.ply` capture into — as elliptical-weighted-average Gaussians, and takes fields of its own: ```luau splat = { buffer = "cloud_records", stride = 6, -- the packed record is six u32 words posOffset = 0, count = 1200000, radius = 1.0, -- multiplies each splat's stored scale channel = "gaussian", orderBuffer = "cloud_order", -- back-to-front permutation; "over" needs one shBuffer = "cloud_sh", -- optional: quantized higher-order SH shStride = 24, -- u32 words of SH per record shDegree = 3, transform = model, -- object -> world, column-major, 16 floats prevTransform = prevModel, -- where `transform` stood last frame opacityScale = 1.0, } ``` `transform` places the cloud: each Gaussian's covariance is conjugated by its upper-left 3×3, so a non-uniform scale shears the cloud the way it shears a mesh. `prevTransform` plus a second entry in `outputs` makes the channel write an MRT pair — the colour into the first target, and the screen-space displacement each splat underwent between the two placements into the second, premultiplied by the same alpha the colour composites under. That second target therefore resolves to `(coverage-weighted
▲ 0↑ born
·
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
# 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
·
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
·
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
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# lighting Scene-lighting base capability: ambient + directional ("sun") light and procedural-sky setup with modify-or-spawn, read-merge-write semantics, plus clear color, and the per-frame reads of the resolved lights. Identity is the component, never the entity name: the sun is the `Light` the renderer's snapshot names as the directional holder, the ambient is the light-role component of kind "ambient", and the sky is the entity carrying a sky-role component. Name-based lookup, word resolution, and sky-material orchestration (presets, material swap) live in the `lighting` toolbox. `sun` and `ambient` configuration patch the scene's resolved sun / ambient light components, spawning a carrying entity when the scene has none. A partial update (e.g. only `intensity`) reads the component's current fields first and merges the given fields on top, so unspecified fields keep their authored values instead of resetting to a default. `sky` writes the sky entity's ProceduralSky component the same way — any of its fields, plus `enabled = false` to remove the sky component. ## Types - `SunOpts` — `{ direction?, color?, intensity?, castsShadows? }`. - `AmbientOpts` — `{ color?, intensity? }`. - `ProceduralSkyOpts` — ProceduralSky component fields, plus `enabled = false` to remove the sky. - `SetupOpts` — `{ sun?, ambient?, sky?, clearColor? }`. - `SetupResult` — `{ sun?, ambient?, sky? }`, the entity ids each provided section resolved to. - `Sun` — `{ direction, color, intensity, castsShadows, entityId? }`. - `Ambient` — `{ color, intensity, entityId? }`. - `LightRow` — one punctual light as the renderer resolved it. ## Exports Writes — each takes the opts above and answers with the entity the light resolved to: - `M.setSun(opts: SunOpts) -> string` — set the scene's sun, returning its entity id. - `M.setAmbient(opts: AmbientOpts) -> string` — set the scene's ambient term, returning its entity id. - `M.applySetup(opts: SetupOpts) -> SetupResult` — apply a lighting setup in one call. All fields optional — only provided fields change. `clearColor` is `{r, g, b}`. - `M.setProbeVolume(key: string, volume)` / `M.removeProbeVolume(key: string)` — publish or retract a baked irradiance probe volume. Reads — each takes no arguments, and answers from the resolved lighting state at a cost independent of scene size: - `M.sun() -> Sun` — the sun the frame is shaded by. - `M.ambient() -> Ambient` — the ambient term the frame is shaded by. - `M.lightRows() -> { LightRow }` — every punctual light the renderer resolved this frame. Identity: - `M.lightKind(componentType: string, component: any?) -> string?` — the kind a light-role component names. - `M.lightOfKind(entityId: string, kind: string) -> any` — the light-role component of that kind on one entity. ## Usage ```luau local lighting = require("@builtin::modules.api.engine.lighting") lighting.setSun({ direction = { 0.3, -1, 0.2 }, intensity = 2.0 }) lighting.setAmbient({ intensity = 0.3 }) lighting.applySetup({ sun = { direction = { 0.3, -1, 0.2 }, intensity = 2.0 }, ambient = { intensity = 0.3 }, sky = { timeOfDay = 14 }, }) local sun = lighting.sun() print(sun.intensity, sun.entityId) ``` A reader takes no arguments and a setter takes the opts table, so `lighting.sun(opts)` is refused with the name of the call that applies it.
▲ 0↑ born
✦
shader · born here
❒asset
# procedural_sky The editable atmospheric sky: a day/night gradient with a sun disc and glow, a procedural star field, and a moon opposite the sun, authored entirely from material properties — no texture backs it. Day, night and the dawn/dusk blend all derive from the directional light's elevation, so the sky follows whatever drives the scene's sun; there is no time-of-day uniform. The gradient's zenith, horizon and ground colours, the sun's size and intensity, the stars, the moon, turbidity and exposure come from `properties.yaml`. The star field holds still unless `stars_twinkle` is above 0, which compiles in the `SKY_TWINKLE` program: each star's brightness then swings by that amount on the frame clock. A twinkling sky changes the picture on every frame the clock runs, so a renderer that draws only what changes keeps drawing under it; a still one leaves an idle screen idle. Output is radiance scaled by `exposure` — the scene's own tone-mapping does the range compression, the same contract as every sky-domain shader. The `ProceduralSky` component owns the runtime material over this shader (`__procedural_sky`) and pushes its fields here; `sky.get()` reports the resulting configuration.
▲ 0↑ born
·
computeshader · born here
❒asset
# ibl_apply Applies the filtered environment to the scene: diffuse from the irradiance map, specular from the prefiltered mips. ## Includes - `ibl_common` ## Bindings | name | kind | |------|------| | `scene_color` | `texture2d` | | `scene_depth` | `texture_depth` | | `scene_normal` | `texture2d` | | `scene_material` | `texture2d` (`sample: uint`) | | `frame_cam` | `buffer` | | `ibl_params` | `buffer` | | `irradiance_map` | `texture2d` | | `specular_map` | `texture2d` | | `ibl_out` | `storage2d (rgba16f)` | `ibl_out` holds linear light, which the diffuse and specular IBL terms can carry past 1.0 — an 8-bit target would clamp it.
▲ 0↑ born
▣
module · born here
❒asset
# environment Module Environment / reflection capture — bake the scene into reflection-probe cube slots from world positions, persist them as `faces6` `.texture` assets, set per-probe blend data so surfaces reflect the probes covering them, and capture the sky into its own slot as the fallback under them. Public Luau surface over the `__environment` Internal FFI namespace, auto-injected as `_G.environment` via the prelude. ## Purpose The generic "render the scene into a cubemap from a point" capability the reflection-probe system is built on. Captures are queued for the render system (which owns the live scene); `captureSlotToAsset` additionally yields a few frames while the GPU readback completes. Persisted cubes are `faces6` `.texture` assets (px/nx/py/ny/pz/nz PNGs + a `cube.yaml` sidecar — see `docs/specs/cubemap-textures.md` §4 for the face convention). For probe authoring use the higher-level `reflectionProbe` module; reach for `environment` when you need the raw per-slot primitives. ## Usage ```luau -- Register probe blend data: index i maps to cube slot i. environment.setProbes({ { x = 0, y = 2, z = 0, radius = 12 } }) -- Bake slot 0 from a point (queued, next frame). environment.captureSlot(0, 0, 2, 0) -- Bake + persist to /source/probe_lobby.texture/ (yields; call from a -- task/coroutine/execute context). local path, err = environment.captureSlotToAsset("probe_lobby", 0, 0, 2, 0) -- Restore a persisted cube into a slot WITHOUT re-rendering. environment.loadSlotFromAsset("probe_lobby", 0) -- Capture the sky alone into the fallback slot: a surface no probe covers -- reflects the sky rather than black. environment.captureSky() ``` ## Exports - `environment.setProbes(probes) -> boolean` — set active probes' blend data; array of `{ x, y, z, radius, priority? }`, index i → cube slot i, gathered highest `priority` first - `environment.captureSky(x?, y?, z?) -> boolean` — render the sky alone into the fallback slot and arm it (queued) - `environment.setSkyFallback(active) -> boolean` — arm/disarm the fallback against the sky already captured (arming is refused while the slot holds none) - `environment.captureSlot(slot, x, y, z) -> boolean` — bake the scene into a slot from a point (queued) - `environment.captureSlotToAsset(name, slot, x, y, z, timeoutFrames?) -> (string?, string?)` — bake + persist as a `faces6` `.texture`; yields - `environment.loadSlotFromAsset(name, slot) -> (boolean, string?)` — upload a persisted cube into a slot without re-rendering Back-compat single-global-reflection helpers (slot 0 + one full-coverage probe): - `environment.capture(x, y, z) -> boolean` - `environment.captureToAsset(name, x, y, z) -> (string?, string?)` - `environment.loadFromAsset(name) -> (boolean, string?)`
▲ 0↑ born
·
computeshader · born here
❒asset
# ibl_irradiance Convolves the environment into a diffuse irradiance map: what a matte surface receives from every direction. ## Includes - `ibl_common` ## Bindings | name | kind | |------|------| | `ibl_params` | `buffer` | | `env_map` | `texture2d` | | `irradiance_out` | `storage2d (rgba16f)` |
▲ 0↑ born
◇
component · born here
❒asset
# Camera Manages viewport priority, render-to-texture, and capture. State is stored in the native `Camera` ECS component; the Rust camera system handles render scheduling and render targets. Public fields: `fov`, `near`, `far`, `priority`, `textureHandle` (the guid of the texture the camera renders into; empty = main viewport), `renderLayers` (which render layers this camera draws — a space-separated spec of names, e.g. `"all"`, `"all !ui"`, or `"default sky"`; `ui`/`sky`/`debug`/`EditorUI` are built-in layers), `postProcessing` (whether this camera runs the post-process chain), `debugChannel`, plus the behavior slot below. Methods: `:lookAt(target)` (entity id string OR `{x, y, z}` table), `:render()`, `:capture()`, `:setTargetTexture(tex?)` (a `renderer.texture.create` handle to render into, or nil for the viewport). ```luau entity(id).component.add("Camera", { fov = 90, priority = 10 }) entity(id).component.get("Camera"):capture() ``` The scene's play-mode camera is reached as `layers.active.camera`, a handle that reads and writes the fields above on whichever entity currently carries them. `layers.active.camera.entity` is the entity ref for that camera and `layers.active.camera.entityId` its id string, so a script that needs to attach something to the camera — an `AudioListener`, a child entity — goes through the ref: ```luau local cam = layers.active.camera cam.fov = 70 -- the camera's settings cam.entity.component.add("AudioListener") -- the entity carrying them ``` ## How the camera moves: `behavior` and `follow` A `Camera` does not move itself. `behavior` names a component that does, and setting it attaches that component to this entity. Clearing it detaches whatever was attached. ```luau local cam = entity(id).component.get("Camera") cam.behavior = asset.ref("@builtin::controller.orbital_follow", "component") cam.follow = playerBody ``` The attached behavior is an ordinary component on the camera's entity, so it is tuned the way any component is: read it with `component.get` and set its fields there. A `component.add` of the same type configures the instance the slot attached instead of adding a second one: the values it passes are written onto that instance and its proxy is returned. That add is the form a scene `build.luau` tunes the behavior with, because its values are saved with the scene and the loaded Camera's behavior takes them back. A key the component reads only as it is created (one of its `initKeys`, a private field) refuses the add and names the key. ```luau cam.behavior = asset.ref("@builtin::controller.third_person_follow", "component") local rig = entity(id).component.get("third_person_follow") rig.cameraDistance = 6 -- the same, as an add of the type the slot attached entity(id).component.add("third_person_follow", { cameraDistance = 6 }) ``` `follow` is the standard slot every shipped behavior reads. Set the follow target on the **Camera**, not on the behavior, so swapping behaviors keeps it. A behavior that finds its own `follow` field empty falls back to this one, which is what lets a rig keep tracking the player across a behavior swap. `followResolves` answers whether that slot names an entity that is live — `true` while it names a live one or names nothing at all, `false` once the target is despawned or the id names no entity. A rig whose target does not resolve holds its last pose, and this is the field that tells it from a rig posed correctly on a subject that has not moved. `camera.get` carries the same value beside `follow`, and a write naming an id with no entity behind it draws a warning where it lands. ```luau cam.followResolves -- false once the followed entity is gone tools.use("camera", "get", id).followResolves -- the same answer off the tool ``` The shipped behaviors live under `@builtin::controller.*`: `orbital_follow`, `third_person_follow`, `first_person`, `free`, `orbit`, `chase`, `isometric`, `rts`, `birds_eye`, `side_scroller`, `cinematic`, `menu`. ## Writing your own Any component can be a camera behavior. Write one that moves its own entity and attach it the same way: ```luau cam.behavior = asset.ref("MyChaseCam", "component") ``` `follow` lives on the Camera, so a behavior gets no property notification of its own when the target changes. Declare `onFollowChanged(newFollow, oldFollow)` to be told the moment it does — the Camera calls it on the component it attached, which is what lets a rig re-pose on the new subject at once. A behavior that reads `Camera.follow` on its own schedule declares nothing and is attached the same way. ```luau typed function public:onFollowChanged(newFollow: any, oldFollow: any) -- pose this entity against the new target end ``` To make it appear in the discovery catalog alongside the shipped ones, declare the `cameraBehavior` tag in the component's `.metadata`: ```json { "tags": ["cameraBehavior"] } ``` The tag governs **discovery**, not attachment. A tagged component is listed by `layers.active.camera.behaviors` and is what tooling offers when something asks "which camera behaviors exist"; an untagged component attaches just as well and simply stays out of that list. Tag the ones you want other people (and agents) to find. ```luau for name, ref in pairs(layers.active.camera.behaviors) do print(name, ref.identity) end ``` ## Texture colour space `textureColorSpace = "display"` applies the display transform when rendering into a texture. `"linear"` writes scene-linear values instead. `postProcessing` independently controls the effects chain in either mode. Floating-point targets retain values above one; normalized targets clamp to their representable range. The main viewport uses display encoding.
▲ 0↑ born
·
computeshader · born here
❒asset
# ibl_specular Prefilters the environment per roughness level, so a glossy surface reads one mip instead of sampling the whole environment. ## Includes - `ibl_common` ## Bindings | name | kind | |------|------| | `ibl_params` | `buffer` | | `env_map` | `texture2d` | | `specular_out` | `storage2d (rgba16f)` |
▲ 0↑ born
·
shadermodule · born here
❒asset
# ibl_common The image-based lighting shared ground: the octahedral mapping between a direction and a texture cell, the importance-sampling helpers, and the roughness-to-mip relation every IBL pass uses. Included with `#include "@builtin::systems.imageBasedLighting.ibl_common"`.
▲ 0↑ born
·
shadermodule · born here
❒asset
# gbuffer_material The G-buffer's surface description, and the one encoding of it. `@scene.shaded` carries what a surface sent — the light the geometry pass shaded it to, scene-referred and unbounded above 1. `@scene.material` carries what the surface is: the base colour it reflects, how metallic it is, and how rough. A screen-space pass that multiplies incoming light by a reflectance — a bounce multiplier, a Fresnel tint, an ambient floor — reads the second. The channel is `Rgba8Uint`. The pass that fills the G-buffer holds 128 bits of colour a pixel, the storage a tile-based GPU keeps on chip at its full tile size: the shaded colour takes 64, the normal 32, and this channel the 32 left, so 32 bits is the entire budget: | Lane | Content | |---|---| | `.r` | base colour, RGB565 low byte | | `.g` | base colour, RGB565 high byte | | `.b` | metallic | | `.a` | perceptual roughness | Base colour lands at 5/6/5 — steps of about 3% per channel. Metallic and roughness keep a full byte each. The geometry pass packs through `zero_gbuffer_pack_material`; every reader unpacks through this module, so the layout is stated once. Pure math, no bindings. ```wgsl #include "@builtin::shaderModules.gbuffer_material" // bindings.yaml: - { name: scene_material, kind: texture2d, sample: uint } let m = zero_gbuffer_material(scene_material, coord); let bounce = incoming * m.base_color; ``` One value at a time: ```wgsl let base = zero_gbuffer_base_color(scene_material, coord); let metallic = zero_gbuffer_metallic(scene_material, coord); let roughness = zero_gbuffer_roughness(scene_material, coord); ``` A `.computeShader` reading the channel declares its slot `kind: texture2d` with `sample: uint`, because an `Rgba8Uint` texture binds as `texture_2d<u32>`. The engine refuses the pass when the declared sample type and the bound texture's format disagree, and names both. ## Signatures ```wgsl struct ZeroGbufferMaterial { base_color: vec3<f32>, metallic: f32, perceptual_roughness: f32, } fn zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial fn zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial fn zero_gbuffer_base_color(t: texture_2d<u32>, coord: vec2<i32>) -> vec3<f32> fn zero_gbuffer_metallic(t: texture_2d<u32>, coord: vec2<i32>) -> f32 fn zero_gbuffer_roughness(t: texture_2d<u32>, coord: vec2<i32>) -> f32 ``` `texel` is one `textureLoad` result off `@scene.material` — the four raw `u32` lanes before this module gives them meaning. `t` is the bound `@scene.material` slot itself (`texture_2d<u32>`, declared `sample: uint`); `coord` is the pixel to read, an integer texel coordinate (`vec2<i32>`) — the same `textureLoad`-shaped argument every accessor and `zero_gbuffer_material` take. The three single-value accessors are `zero_gbuffer_material` narrowed to one field, for a caller that wants only one of the three. The channel is a G-buffer channel, so the deferred G-buffer fragment entry is what writes it: an opaque draw on the deferred path. A pixel no geometry wrote reads a black surface at metallic 0 and mid roughness.
▲ 0↑ born
·
shadermodule · born here
❒asset
# indirect_visibility How much of the light of its surroundings reaches a surface, from the scene's occlusion channel (`@scene.ao`): the open share of the hemisphere, the bent normal and the cone the open part makes against a reflection lobe. The material's own indirect term and every composite that adds light a surface takes from around it (a probe field, a sky light, an environment) read the channel through these functions, so one occlusion answer shades all of that light. A texel of the channel carries in `r` how much of the hemisphere is blocked, in `g` and `b` the bent normal laid flat on the octahedron, and in `a` whether a pass wrote one. Where none did, the visibility is exactly 1. The module is engine-owned (`zero::indirect_visibility`): the PBR model includes it, so every program composes the engine's own copy, and a copy a world holds is set aside. It binds nothing; the functions that read the channel take it as an argument, so a surface shader and a compute pass call the same code. ```wgsl #include "@builtin::shaderModules.indirect_visibility" // In a compute pass that binds the channel as `scene_ao` (`@scene.ao`): let texel = zpbr_occlusion_texel(scene_ao, vec2<f32>(coord)); let visibility = 1.0 - clamp(texel.r, 0.0, 1.0); let bent = zpbr_decode_bent_normal(texel, n); let diffuse = incoming * zpbr_multibounce(visibility, albedo); let reflected = incoming_spec * zpbr_specular_occlusion(visibility, bent, n, r, roughness); ``` - `zpbr_multibounce(visibility, albedo)`: the visible share raised, per channel, by the light a crease of that colour bounces back into itself. - `zpbr_specular_occlusion(visibility, bent, n, r, roughness)`: the share of the reflection lobe around `r` that the open cone holds, measured against the unoccluded lobe. - `zpbr_cap_overlap(cos_a, cos_b, cos_d)`: the solid angle two spherical caps share. - `zpbr_occlusion_texel(channel, px)`: the channel's texel at a pixel, clamped to the frame. - `zpbr_decode_bent_normal(texel, fallback)`: the world-space bent normal a texel carries, `fallback` where no pass wrote one. - `zpbr_open_share(channel, px)`: the open share at a pixel, 1 where no pass wrote the channel.
▲ 0↑ born
▣
module · born here
❒asset
# yaml.module YAML decode + encode for authored engine content. Pure Luau, no engine dependencies — a general parsing library, not data-system plumbing. ```luau local Yaml = require("@builtin::modules.yaml") local doc = Yaml.decode(vfs.read(path)) vfs.write(path, Yaml.encode(doc)) ``` ## Supported subset - Block mappings (`key: value`) and block sequences (`- item`), nested to any depth. - Compact sequence-of-mapping entries (`- path: x` / ` kind: y`). - Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line. - Plain scalars with type inference: `~` / `null` → nil, `true` / `false` → boolean, numeric literals → number, everything else → string. - Single- and double-quoted strings (`''` escapes a literal quote inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a double-quoted one). A quote opens a quoted scalar where a scalar begins — after `key:`, after a `- ` entry marker, or inside a flow collection — so a plain scalar carries an apostrophe as data (`note: the world's rules`). Quoted keys are read in flow mappings. - `#` comments — honored outside quotes, so a `#` inside a quoted string is kept as data. - Literal (`|`) and folded (`>`) block scalars, with a chomping indicator (`-` strips the final newline, `+` keeps every trailing blank line, none keeps one newline) and an indentation indicator (`1`-`9`: the content's indent past the parent's), in either order (`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text: quotes (balanced or not), `#`, `key: value` and `---` inside it are data. - An optional leading `---` document marker. ## Loud-error contract Constructs outside the subset above raise instead of misparsing: anchors/aliases (`&`, `*`), tags (`!`), directives (`%`), multi-document streams (a second `---`), a block-scalar header it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and block-scalar bodies). Every error carries the offending line number (`yaml: line N: ...`), so a bad config points straight at the line to fix. Tab indentation is rejected everywhere — including block-scalar body lines whose leading whitespace contains a tab. A tab after the first non-space character of a line is content and passes through. ## API - `Yaml.decode(text: string): any` — decode a YAML document into a Luau value (table, scalar, or nil for an empty document). Raises on malformed input or an unsupported construct. - `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as `decode` does, and report whether the text carries a comment by the decoder's own rule: a `#` at a line's start or after whitespace, outside a quoted scalar and outside a block scalar. Re-encoding the value drops such comments, so an editor that writes a document back reads this first. - `Yaml.encode(value: table): string` — encode a Luau table as YAML (block style, two-space indent, alphabetically sorted keys). Raises on values YAML can't represent (functions, userdata, non-string mapping keys). A top-level empty table encodes to an empty document, which decodes back to `nil` (the YAML empty-document ambiguity).
▲ 0↑ born
❒
package · born here
❒asset
# areaLights system Lights that emit from a surface rather than from a point. Every screen, neon sign, glowing window, ceiling panel and lantern face is an area emitter. Standing a point light in the middle of one gets the brightness roughly right and the character completely wrong: a point puts a pinpoint reflection on the floor and a radial falloff on the wall, where the real thing puts the shape of the emitter and a falloff that follows its extent. ## Using it An emitter that should follow an entity's face is a component: ```lua local id = entity.spawn("tv").id entity(id).component.add("SurfaceLight", { width = 2.0, height = 1.2, face = "front", -- front | back | up | down | left | right intensity = 6.0, range = 12, }) ``` The rectangle turns with the entity, so a tilted screen lights the direction it actually points. Every field is live, and an `intensity` of 0 removes the light. For code placing emitters directly: ```lua local surfaceLight = require("@builtin::systems.areaLights.surfaceLight") surfaceLight.set("strip", { position = { 0, 5, -12 }, right = { 1, 0, 0 }, up = { 0, 1, 0 }, width = 0.6, height = 7, color = { 1, 0.72, 0.35 }, intensity = 5, }) surfaceLight.remove("strip") surfaceLight.configure({ diffuse = 1, specular = 0.5 }) surfaceLight.clear() ``` ## What the knobs do | field | effect | |---|---| | `width` / `height` | Size of the emitting rectangle, world units. The shape of the light is the shape of this. | | `face` | Which way the entity emits. | | `range` | How far the light carries, with a smooth cutoff at the end. | | `intensity` | Brightness. 0 removes the light. | | `colorR` / `colorG` / `colorB` | Emitter colour. | | `offset` | Distance the rectangle sits proud of the entity's origin, along the face's normal. | | `diffuse` / `specular` | Scales on the two terms — the wash across a surface, and the reflected shape of the emitter. | Shape is the point. A wide panel puts a broad pool on the floor; a narrow strip puts a narrow elongated one. That difference is not reachable with a point light at any brightness. At most 32 emitters are held at once, because the shader loops every light for every pixel. ## How it renders `areaLighting.renderFeature` runs one compute pass after lighting. Diffuse is the exact irradiance of the quad — Lambert's formula over its four edges — which matters where a point approximation fails hardest: a wide emitter close to a wall. Specular uses the representative point on the rectangle nearest the reflection ray, with the lobe widened to cover the emitter's solid angle and its peak scaled down to match, so a large emitter reads broader rather than brighter. ## Files ``` areaLights.package/ SurfaceLight.component/ -- an emitter on an entity's face surfaceLight.module/ -- the emitter registry and scales areaLighting.renderFeature/ -- the compute pass ```
▲ 0↑ born
❒
package · born here
❒asset
# ambientOcclusion system Ambient occlusion: the contact darkening of indirect light in corners, creases and where objects meet. Without it, every concave region takes as much ambient and environment light as a flat one: a box resting on a floor has no seam, a corner is as bright as the wall, and an untextured scene reads as plastic. One effect answers one question: what fraction of the hemisphere above this pixel is open. Its answer goes into the scene's occlusion channel before anything shades, and PBR shading (`zero_pbr_shade`, which the `pbr` shader and the materials built on it run) multiplies it into the indirect term alone (ambient, irradiance, environment reflection). Direct light, emissive surfaces and transparents keep the light they carry. ## Using it The scene's occlusion is a component; author it once and it persists with the scene: ```lua local id = entity.spawn("ambient_occlusion").id entity(id).component.add("AmbientOcclusion", { intensity = 0.9, -- how far the darkening goes, 0..1 radius = 1.5, -- world-space reach quality = "high", -- low | medium | high | ultra }) ``` Every field is live: edit one in the inspector and the shading follows. Setting `intensity` to 0 turns it off without losing the rest. For code that adjusts occlusion at runtime (a quality slider, a cutscene), reach for the module directly, with the same options: ```lua local ao = require("@builtin::systems.ambientOcclusion.ao") ao.set({ intensity = 0.9 }) -- any subset; the rest is kept ao.get() -- the settings in force ao.qualityLevels() -- the cost each level pays ao.active() -- is the pass running ao.stats() -- what the pass built and ran this frame ao.clear() -- off, settings kept ``` ## What the knobs do | field | effect | |---|---| | `intensity` | How far the darkening goes, in [0, 1]. 0 turns it off and releases the pass. | | `radius` | World-space reach, roughly "how big is a crease worth darkening". Constant in world space, so it does not swell as the camera approaches. | | `power` | Contrast curve on the visibility term. Above 1 deepens the dark end. | | `thickness` | World-space thickness assumed for an occluder, so a thin foreground object stops occluding everything behind it out to the full radius. | | `bias` | How far a neighbour must rise above the tangent plane before it raises a horizon, in [0, 1]. Raise it if a flat surface shades itself in patches; lower it if fine creases disappear. | | `quality` | The cost of the estimate. See the table below. | | `traced` | Trace the hemisphere against the scene acceleration structure while the scene's ray tracing is on (`renderer.setRaytrace(true)`). A frame drawn without ray tracing takes the screen-space estimate. | | quality | screen-space slices x steps | depth taps per texel | traced rays per texel | resolution | |---|---|---|---|---| | `low` | 2 x 3 | 12 | 3 | half | | `medium` | 3 x 4 | 24 | 6 | half | | `high` | 4 x 6 | 48 | 6 | full | | `ultra` | 6 x 8 | 96 | 12 | full | The lower two levels compute occlusion on a half-resolution grid: a quarter of the texels, each still costing its level's work. Occlusion is low-frequency almost everywhere, and the filter that removes the sampling noise lifts the coarse grid back to the frame in the same pass, weighting each texel by the depth where it sits so silhouettes survive the upsample. What a half-resolution grid loses is the innermost pixel of a sharp crease. ## How it renders The pass runs at `afterDepthPrepass`, where this frame's opaque depth is complete and nothing has shaded yet, in the `lighting` post stage: 1. The estimate. Screen-space, it is ground-truth ambient occlusion: a few slices are walked through the texel, the steepest horizon is found in both directions along each, and the visible arc between the two is integrated against the cosine lobe around the normal in closed form. Traced, it is a cosine-weighted hemisphere of short rays, and the fraction that reaches nothing within `radius` is the visible fraction. Both reconstruct the surface's normal from this frame's depth and store through one function. 2. The filter. Each tap is weighted by how close its depth is to the centre pixel's, so the sampling noise goes without bleeding occlusion across a silhouette. It writes the occlusion into the scene's occlusion channel (`@scene.ao`). PBR shading reads the channel at its own pixel the same frame, on the forward and deferred paths alike. Depth and camera come from the render target being drawn (`@scene.depth`, `@frame.camera`), so the result is correct in offscreen captures and render-to-texture cameras at their own resolutions. Sky pixels have no surface to occlude. ## Seeing the occlusion on its own While occlusion is running, `ambientOcclusion` is a capture view: the filtered visibility with no scene colour, white where the hemisphere is open and dark where it is closed. ``` capture { pass = "ambientOcclusion" } ``` It is the fastest way to tell a shading problem from an occlusion one, and to compare two `radius` values or quality levels without the lighting in the way. ## Files ``` ambientOcclusion.package/ AmbientOcclusion.component/ -- the scene's occlusion, authored and persisted ao.module/ -- ao.set / .get / .qualityLevels / .active / .stats / .clear ambientOcclusion.renderFeature/ -- the pass: estimate, filter, occlusion channel, capture view ao_common.shaderModule/ -- the prelude both estimators are written against ao_pass.computeShader/ -- the screen-space estimate ao_trace.computeShader/ -- the traced estimate ao_filter.computeShader/ -- the depth-aware filter that writes the channel ```
▲ 0↑ born
▣
module · born here
❒asset
# assetType runtime The machinery that reads a `<typename>.assetType/behavior.luau` and turns its declarations into live behaviour. A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` / `onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` / `settingsCorrections` hooks. None of it runs itself. This is the code that runs it, and it lives here because reading a type's declarations is the **assetType type's own behaviour** — the same way `material.assetType` owns what a `.material` does. ## Sub-modules | Module | Reads | Responsibility | |---|---|---| | `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. | | `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. | | `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. | | `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. | | `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. | | `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. | | `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. | | `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. | | `events.module` | `events` | The per-asset event runtime behind `ref.events`. | | `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. | | `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. | | `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. | ## Reaching it ```luau local rt = require("@builtin::assetTypes.assetType.shared") rt.ref.loadTypeBehavior("material") ``` Fields resolve lazily. The prelude requires the sub-modules directly, in dependency order (`ref`, then `changeDispatch`, `onRegister.install()`, `refShapes.install()`) — a table that required all six on load would take that ordering away from it.
▲ 0↑ born
backing path · systems/sky.package

Problems

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

These counts cover only the parts this page shows. Problems on the parts it leaves out are not counted here.

1+problem

Inside

1 problem across 1 item
●
dep.unresolved · L85
could not resolve `@builtin::systems.sky.skyLight.live`
⌬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.