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

sceneLighting

Scene setups that light a whole scene with the engine's real-time lighting in one placement, and a scene that shows them.

by◐lumi·posted 1d ago
What it does

sceneLighting

Scene setups that light a whole scene with the engine's real-time lighting in one placement, and a scene that shows them.

  • dynamicLighting.sceneSetup: a sky whose hour drives a sun and a moon, the sky light, ray-traced probe global illumination, ambient occlusion, contact shadows, height fog, exposure that adapts from day to night, temporal anti-aliasing and screen-space reflections. Its sky, sun and moon are the assets beside it: dynamicSky.sky, dynamicSun.sceneLight and dynamicMoon.sceneLight.
  • dynamicLightingShowcase.scene: a cottage in a garden lit by dynamicLighting, with a room lit through its windows, lamps inside and out, trees and bushes, a glossy terrace and a mirror ball.

Place the setup in any scene:

asset.resolve("@builtin::systems.sceneLighting.dynamicLighting", "sceneSetup")
    :instantiate(nil, { name = "lighting" })

and set sky/backdrop/timeOfDay on the placement to move the scene between day and night.

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.
⌬ Metadata
descriptionScene setups that light a whole scene with the engine's real-time lighting in one placement, with a sample scene that shows them.

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.

114+items
·
scenesetup · born here
❒asset
# dynamicLighting A scene setup that lights a scene with the engine's real-time lighting in one placement: a sky whose hour drives a sun and a moon, the sky's light, ray-traced probe global illumination, ambient occlusion, contact shadows, height fog, exposure that adapts between day and night, temporal anti-aliasing and screen-space reflections. Every light the scene receives comes from a member listed here, with the values it is placed at, so each contribution is a row of the placement's card that an author reads and edits. ## Placing it Drag it into the viewport, or place it from a scene's `build.luau`: ```lua asset.resolve("@builtin::systems.sceneLighting.dynamicLighting", "sceneSetup") :instantiate(nil, { name = "lighting" }) ``` A scene that already places a setup takes this one by naming it on its `lighting` line, or by pointing the `lighting` entity's `Asset` source at it. Selecting `lighting` shows every member and every value below; an edit there is that scene's own override. A scene that holds `Light` entities of its own for the sun or the ambient term keeps them beside the setup's and ties with its sun, so the setup lights a scene alone once those entities are removed. ## Day and night The sky's hour, `sky/backdrop/timeOfDay`, is the one value that moves a scene between day and night. The sun and the moon follow the sky, the backdrop draws its night colours, stars and moon once the sun is below the horizon, the sky light captures what it draws, the probe field carries that light, and the exposure follows the frame. At 16:00 the sun stands 30° up; at 22:00 the moon lights the scene and the scene's own lamps carry the rest. ## Members | id | source | what it puts on the scene | |---|---|---| | `sky` | `./dynamicSky.sky` | The procedural backdrop at 16:00, a clear blue day over a grey-green ground, with dark blue-black night colours, stars and a moon. | | `sun` | `./dynamicSun.sceneLight` | A shadow-casting directional light that follows the sky: a warm white at 4 from 30° up, dimmer and warmer toward the horizon, out after dark. | | `moon` | `./dynamicMoon.sceneLight` | A shadow-casting distant light that follows the sky and keeps its 0.05: after dark it stands at the moon the sky draws and lights the scene a cool blue-white, an eightieth of the sun, which the exposure's 2 stops lift to a dark moonlit night. While the sun is up it stands with the sun and adds its 0.05 to the sun's 4. | | `skyLight` | `@builtin::systems.sky.skyLight` | Captures the drawn sky. `diffuse` 0, because the probe field carries the sky's diffuse light; `reflection` 0.5, the sky every surface reflects, scaled by how much of the sky the field finds each surface sees (`occlusionSource`). | | `gi` | `@builtin::systems.probeGI.probeGI` | Ray-traced probe global illumination: three cascades of 16 x 8 x 16 probes, the finest 1.5 m apart, 48 rays a probe, its updates held to 1 ms of GPU time a frame (`updateBudgetMs`), each probe aiming rays at up to 4 small emitters near it (`aimedEmitters`). Its rays return the sky light's capture (`skySource`) where they leave the scene, and at a surface the sun's, the moon's, every lamp's and every emissive surface's light, so the bounce of each reaches the rooms and the shade. | | `ao` | `@builtin::systems.ambientOcclusion.ambientOcclusion` | Screen-space ambient occlusion with a 0.6 m radius, under half of the field's finest spacing, so the field and the occlusion each darken their own scale of contact. The field takes it through its `contactOcclusion` of 1. | | `contactShadows` | `@builtin::systems.contactShadows.contactShadows` | Short screen-space shadows (0.35 m) where the sun's shadow map is too coarse: under feet, legs and the edges of things standing on a floor. They follow the sun. | | `fog` | `@builtin::systems.atmosphere.heightFog` | A thin haze, 0.004 per metre at the ground thinning with height, lit by the sun and by the sky light's capture, so distance reads by day and the night air stays dark. Its colour, (0.92, 0.95, 1.0), meets the horizon of the drawn sky. | | `exposure` | `@builtin::systems.exposure.exposure` | Automatic exposure metering the centre of the frame at photographic middle grey. It may open the picture by up to 2 stops (`maxEV`), so a sunlit room reads and a night stays dark, and close it by up to 4 (`minEV`). | | `taa` | `@builtin::systems.antiAliasing.taa` | Temporal anti-aliasing, which also steadies the field's light and the reflections over frames. | | `reflections` | `@builtin::systems.reflections.ssr` | Screen-space reflections on glossy surfaces, roughness 0.45 and under. Rougher surfaces reflect the sky light's capture alone. | ## Cost The probe field holds its passes to its 1 ms GPU budget: the probes it leaves out of a frame update on a later one, so its cost stays flat as the scene changes. Every member scales with the device's quality level (`guides { path = "topics/graphics-quality" }`): the values above are the high level, and lower levels derive from them. The scene `@builtin::systems.sceneLighting.dynamicLightingShowcase` places this setup over a cottage and its garden.
▲ 0↑ born
·
scene · born here
❒asset
# dynamicLightingShowcase A cottage in a garden, lit by the `dynamicLighting` scene setup (`@builtin::systems.sceneLighting.dynamicLighting`). Load it to see the engine's real-time lighting at work, by day and by night. - **The room.** The cottage's west wall opens on a wide window and its south wall on a window and a door. At the setup's 16:00 the sun lands on the red rug and the floor inside, and the walls, the ceiling and the furniture are lit by the light that patch sends on, carried by the probe field. - **The lamps.** A pendant over the table, a floor lamp by the sofa, a lantern beside the door and two lamp posts along the path, each a bulb drawn round a point light. After dark they light the room and the garden, and the field carries their bounce. - **The garden.** Broadleaf trees, conifers and bushes, rocks, a gravel path, a glossy tiled terrace that takes screen-space reflections, and a mirror ball on a plinth that reflects the sky and the cottage. - **The view.** A camera from the south-west onto the sunlit west window, the door and the garden. Select `lighting` and set `sky/backdrop/timeOfDay` (22 for night, 16 for the afternoon) to move the scene between day and night; every other value the lighting holds is on the same card. The scene has no player: play shows the garden through its camera. ## Entry point - `entrypoint.luau` holds the scene's load and per-frame hooks, all commented out.
▲ 0↑ born
·
scenelight · born here
❒asset
# dynamicMoon The moon of `dynamicLighting.sceneSetup`: a shadow-casting distant light, a cool blue-white (0.62, 0.74, 1.0), that follows the sky and keeps the intensity it states (`followSkyIntensity: false`). After dark it stands at the moon the sky draws, opposite the sun, and lights the scene at 0.05, an eightieth of the sun. While the sun is up it stands with the sun and adds its 0.05 to the sun's light.
▲ 0↑ born
·
sky · born here
❒asset
# dynamicSky The sky of `dynamicLighting.sceneSetup`: the procedural backdrop (`@builtin::systems.sky.backdrops.procedural`) at 16:00, a clear blue day over a grey-green ground, with blue-black night colours, stars and a moon. Its hour (`backdrop/timeOfDay`) is the one value that moves the scene between day and night: the sun and the moon that follow the sky take their direction from it, the backdrop leans to its dawn colours as the sun nears the horizon and draws its night colours, its stars and its moon once the sun is below it, and the sky light captures what it draws.
▲ 0↑ born
·
scenelight · born here
❒asset
# dynamicSun The sun of `dynamicLighting.sceneSetup`: the scene's directional light, a warm white (1, 0.88, 0.74). It follows the sky (`followSky`), so the sky's hour aims it, and lands at its stated intensity of 4 with the sun 30° up or higher, dimmer and warmer toward the horizon and out below it. It casts the scene's sun shadow.
▲ 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
# Scene setup (asset type) A scene setup configures a scene as a whole in one asset: its sun and ambient light, its fog, its render features and post effects, or any other effect that applies to a scene. It is an ordered list of **members**, each an asset whose type implements `applicable`, with the values the setup states for them. Placed in a scene, it applies every member; selecting the placement shows every parameter of every member, and an edit made there is that placement's own. ## Where it lives - Source: `<name>.sceneSetup/` - Identity: `<name>` (the `.sceneSetup` suffix strips from the identity) - Folder shape: - `sceneSetup.yaml`: the definition. **Required.** - `README.md`: what the setup puts on a scene. **Required.** - `.metadata`: `description` and `tags`. **Required.** - `preview.png`: its picture. Optional. ## The definition ```yaml members: - id: sun # required, ^[a-z][A-Za-z0-9_]*$, unique source: "./sun.sceneLight" # any asset that implements applicable - id: ambient source: "./fill.sceneLight" values: { intensity: 0.12 } # values for the member's parameters - id: fog source: "<a fog render feature>" enabled: false # optional, default true - id: grade source: "./grade.postEffect" values: { saturation: 0.82, contrast: 1.12 } ``` A member's `values` are the values this setup states for that member; the member asset keeps its own, and another holder of it states its own. A member's `source` is one of: - an identity: `lighting.harbour_fill`, `@builtin::<library>.<name>`. It resolves among the assets that can be members, so a name another kind of asset also answers to reaches the member; - a path with its type suffix: absolute (`/source/lighting/harbour_fill.sceneLight`), from the folder holding this setup (`harbour_fill.sceneLight`, `./harbour_fill.sceneLight`, `../shared/fill.sceneLight`), or from the world's source folder (`lighting/harbour_fill.sceneLight`). A path starting `./` or `../` is read from the setup's folder alone. An identity drops the type suffix, so `harbour_dusk.sky` and `harbour_dusk.sceneSetup` in one folder share `lighting.harbour_dusk`; a member naming that identity is skipped as `sceneSetup.member.ambiguous`, which names both assets, and its path names the one meant. A source that names nothing is `sceneSetup.member.missing`, and its values and overrides are kept until it resolves. A member whose type does not implement `applicable` is refused by name (`sceneSetup.member.unsupported`). A key the engine does not read is a warning. ## Parameters and paths A setup's parameters are its members': `<member id>/<name>` (`fog/density`), a nested member's under its path (`look/reflections/intensity`), and `<member id>/@enabled` for every member. `@lit` (true by default) says whether the scene renders lit; off, every surface shows its own colour with no light on it, for a stylised game or a menu. `asset.schema(setupRef)` lists every path with the member's own Field descriptor. A setup that nests another names its parameters through the member id it gives the nested setup: a setup whose member `base` is another setup has `base/fog/density` for that setup's `fog/density`, and a placement sets `base/fog/density`. A path that is no parameter is refused naming the paths that end in it. The value a member receives, for each parameter, first present wins: the placement's override, the outermost setup's `values`, each inner setup's `values`, the member asset's live value, then its saved value. ## Placing and tuning ```lua -- A world's setup by its identity (`lighting/harbour_dusk.sceneSetup` is -- `lighting.harbour_dusk`), or by its absolute path, `/source/lighting/harbour_dusk.sceneSetup`. local root = asset.resolve("lighting.harbour_dusk", "sceneSetup"):instantiate(nil, { name = "lighting" }) local setup = root.component.get("SceneSetup") setup:set("fog/density", 0.05) -- this placement's override setup:set("fog/density", { scale = 3.75 }) -- relative: the setup's density times 3.75 setup:set("fog/heightFalloff", { offset = -0.06 }) -- relative: the setup's value plus -0.06 setup:set("ao/@enabled", true) -- turns a member on for this placement setup:reset("fog/density") -- back to what the setup says for path, m in pairs(setup:members()) do print(path, m.state.status) end ``` The placed root holds the `Asset` component (its `source` is the setup) and the `SceneSetup` component (this placement's `overrides`); the scene stores nothing of any member. Removing the `Asset` removes the `SceneSetup`, and every member's application goes with it. A relative override (`{ scale = n }` or `{ offset = n }`, numeric parameters only) lands at the value the setup supplies times `scale` or plus `offset`, checked against the parameter's descriptor, and follows that value: edit the setup's fog density and every placement scaling it moves with it. It is saved and synced like any override, and the Inspector shows it as relative. **Where each value comes from.** `setup:get(path)` and each member's `values` in `setup:members()` say it: `origin` is `override` (this placement's, with `relative` and `supplied` for a relative one), `definition` (with `definedBy`, the setup stating it, and `definedAt`, the path it states it at there, so a value inherited through a nested setup names that setup), `live` (the member asset's live value) or `saved`. One line proves what a placement shares: ```lua for name, v in pairs(setup:members()["fog"].values) do print(name, v.value, v.origin, v.definedBy) end ``` **A light that follows the sky lands at what the sky makes of it.** A sun, a fill or a rim that follows the sky (`followSky`) states its intensity as its noon peak: the sky gives it that intensity with the sun 30° up or higher and dims it toward the horizon, to about a third at 7° and 0 below it. So a dusk sun stated at 3.2 at 17:51 lands near 0.4. `setup:get(path).landed` (and `setup:set(path, value)`, which returns the same read) is what it lands at now, beside `value`, what it states; the card shows `3.2 → lands at 0.4 at 17:51` on the row. The member's `state.notice` in `setup:members()` names a light the sky dims to under a third of what it states, a distant fill that lands brighter than the sun it is meant to support, and an ambient term at half the sun or more. Raise the stated intensity, move the hour, or, for a fill or a rim, set `followSkyIntensity` to `false` so it keeps what it states. **`set` in edit mode is a scene edit.** In edit mode on a world scene, a `set` is an authored edit of the scene, recorded and saved: it holds over what `build.luau` states until it is reset or released (`sceneAuthoring` `releaseAuthored`). A `reset` that leaves the placement with no override records nothing and releases the edit an earlier `set` recorded. Overrides stated in `build.luau` are the build's own. ## Auditioning another setup Two placements, or a placement and an application from code, each apply their own sun, ambient term and fog; the effect decides which is in force (the light-tie rule for lights), so an application beside a placed setup reports the members another application holds as `held`, with `heldBy`, and its `ApplyState.notice` names each held member, its asset and its holder. To see a setup in place of the placed one: - audition it on the placement, a preview for the session: `setup:audition(asset.resolve("lighting.harbour_night", "sceneSetup"))` applies it in the placed setup's place and records nothing; `setup:endAudition()` (or the card's End audition, a flip, a reload) puts the placement's own setup back. `set` and `reset` are refused while it lasts; - apply it from code (below): it holds over the placement across flips until it is dropped; - read its preview: `preview.png` lights the reference subject `@builtin::preview.subjects.lookdev` with the setup alone, its exposure fit so a night setup reads (below); - point the placement's `Asset` source at it (a scene edit that stays; `releaseAuthored` returns the placement to `build.luau`'s setup); - or apply it in a scene with no setup placed, such as a scratch scene. ## Applying it from code A setup implements `applicable` itself, so it can be applied for an owner like any member: `setupRef:as("applicable"):apply(owner, values)` starts an application and `setupRef:as("applicable"):drop(owner)` ends it. Each member is applied with the owner `"<owner>/<member id>"`. - **It takes the effects that hold one at a time.** The scene's sun, its ambient term, its sky and each render feature's settings are held by one application at a time: of the applications standing, the newest to state something holds it, so an application made over a placed setup holds them while it stands, and the placement's members report `held` by it. - **It stays in force until it is dropped,** across edit/play flips and device rebuilds. - **Its drop hands every effect back** to the application before it: the placement's own, or the scene's own lights. Which of two suns or two fogs is in force is the effect's own to decide; the setup decides nothing about its members. An audition (above) is a preview for the session that a flip ends; an application from code stands until it is dropped. ```lua local night = asset.resolve("lighting.harbour_night", "sceneSetup") night:as("applicable"):apply("myGame:time", {}) -- night holds over the placement -- … flips, rebuilds … night:as("applicable"):drop("myGame:time") -- the placement's lighting is back ``` ## Checking one `asset.validate(setupRef)` (an engine API function) reads the definition and every value and returns `{ ok, problems }`: each diagnostic (`sceneSetup.member.missing` and the rest) with its code, severity, path and message. A problem of severity `error` refuses a push. ## Its picture A setup's `preview.png` shows its own lighting on a fixed reference subject, `@builtin::preview.subjects.lookdev` (a grey ground, a white diffuse sphere, a chrome sphere and a grey card). The preview studio stands the subject and applies the setup to the world with the owner `preview` for the shot, so its sun, sky and effects are the ones in force, then drops it, which hands every effect back to the scene's own holder. A frame that reads darker than mid grey (a night setup) is shot with its exposure opened up for the picture alone, by up to eight stops, so the night look reads without the setup changing. For those frames the world shows the setup's lighting, so the picture renders only on an explicit request (`preview.writePreview`, `assets.generatePreviews`, staging) and never from the preview queue or a live preview; the last picture stands otherwise. ## Make one ```lua asset.create("sceneSetup", "dusk", { members = { { id = "sun", source = "./sun.sceneLight" }, { id = "ambient", source = "./fill.sceneLight", values = { intensity = 0.1 } }, } }) ```
▲ 0↑ born
·
assettype · born here
❒asset
# Scene (asset type) A scene is a saved, loadable snapshot of an entity scenegraph inside a world: the entity hierarchy, transforms, components, lighting, and a declared `player` intent, plus an auto-discovered startup script. A scene is the unit of "level" or "screen" — a title screen, a lobby, a gameplay area, and an end-of-game summary each get their own scene. Scenes load as **layers**. One root scene is active at a time; additional scenes can load additively as overlays on top of it. Each scene owns its own multiplayer relay room. Switching scenes is a local call: the client that makes it leaves the old scene's room and joins the new scene's room. ## When to use one - You want a savable, re-loadable snapshot of an entity scenegraph plus its lighting and player setup. - You want a runnable starting state for a level or screen. - You want a scenes-as-data flow: `layers.load("lobby")`, edit live, then `layers.active:save()` to publish the edits back to the scene. For a reusable entity assembly (a prop, a vehicle, a UI panel) that many scenes spawn into themselves, use a `.bundle`. A scene is a whole-world snapshot; a bundle is one prefab that lives inside scenes. ## Folder shape A scene asset is a folder ending in `.scene`. Its identity is the folder name with the suffix stripped (`Lobby.scene` → `Lobby`). - `scene.json` — the scenegraph: `entities[]`, lighting, and the top-level `player` intent. **Required.** Written by the engine — a build, a save, a human dragging something in. Not hand-edited. - `build.luau` — what the scene is made of, written as code. Runs while you author; saving bakes its result into `scene.json` (see Building a scene). - `entrypoint.luau`: the startup script. **Required.** Auto-discovered as a sibling of `scene.json`; define lifecycle callbacks here (see The entrypoint). - `<name>.<type>/` — an asset the build makes, authored here by `build.asset` (see The assets a build makes), alongside `.build.assets`, which records which `build.luau` produced each of them. - `prefabs/` — optional subfolder for scene-local bundles. - `scripts/` — optional subfolder for scene-local Luau helpers, required from `entrypoint.luau`. - `README.md`: notes about THIS scene: what it shows or plays and what it is for. **Required.** The general scene model lives here, in `guides { path: "types/scene" }`. - `.metadata`: **Required.** `scene.json` is version 7. It carries `"format": "scene"`, `"version": 7`, an `entities[]` array, and a top-level `"player"` string intent. ## The `player` intent Every scene declares how it handles players with a top-level `player` field in `scene.json`: - `"spawns"` — the scene carries an authored player setup, and the engine spawns a player for each connecting user from it. This is the default for a freshly created scene. - `"none"` — the scene spawns no player and authors no camera. Author your own Camera entity for the view (menus, UI-only screens, cinematics). ### How `"spawns"` works A `"spawns"` scene authors two things in `scene.json`: 1. A **PlayerPrototype** — an entity carrying the `PlayerPrototype` component, whose `body` field names a child entity (the body). The body carries an avatar (an `Asset` pointing at an avatar, e.g. `@builtin::avatars.humanoid`). A `CameraRig` child carries a `Camera` with a camera behavior (e.g. `orbital_follow`). The prototype root is authored `PrototypeOnly` so it exists as a clonable template. 2. A **PlayerSpawn** — an entity carrying the `PlayerSpawn` component, whose `prototype` field names the PlayerPrototype to instantiate and whose transform is where players appear. The scaffolded scene groups these under two organizing entities, `PlayerSetups` (holding the prototype) and `Spawns` (holding the spawn), so the authoring tree stays legible. On each user join — entering play, and each subsequent connect — the engine runs the spawn for that user: - It clones the PlayerPrototype subtree. - The clone root becomes the user's **internal identity** — a registry-only entity named `user` carrying the `UserIdentity` component. The identity is the anchor for who the player is; it has no world presence. - The body named by `PlayerPrototype.body` is adopted as the user's **avatar** — their visible presence in the world — and placed at the PlayerSpawn's world transform. Move the PlayerSpawn (or drag it in the editor) to set where players appear. - The `CameraRig`'s Camera follows the bound avatar. The player prototype is live in edit mode so you can see and adjust it. In play mode it is deactivated and marked internal — it stays a clonable source while each user gets their own clone. ### Reaching the live player The player surface lives on the root scene's registry, `layers.active.players`: - `players.localPlayer` — this client's player, a curated handle. - `players.localReady` — `true` once the local player's avatar is bound (or the scene opted its avatar out). - `players:list()` / `players:count()` — the players connected in this scene's room. - `players:get(userId)` — a connected player by account id. - `players:ownerOf(avatar)` — the player whose body is a given avatar. A player handle is a data record about who the player is, plus a link to their body: - `player.avatar` — the body's entity ref. Act on the body through it (`player.avatar.position`, raycasts, rig access). - `player.isLocal` — whether this client owns the player. - `player.ready` — whether a live avatar is bound. - `player.userId` / `player.identity` / `player.displayName` — the player's account identity. - `player.avatar = ref` — bind a live body entity as the player's body (assign nil to clear). To use a `.bundle` / `.avatar` asset, spawn it into the world first, then bind the resulting entity. The player's identity entity is the internal anchor; the handle exposes the body (`player.avatar`) and the player's data, and reaching for `.entity` / `.id` / `.component` raises with a redirect to `player.avatar`. ## Building a scene `build.luau` declares what the scene holds. It is ordinary engine code — `entity.spawn`, `component.add`, transform writes, `for` loops, a `require` of a module that computes a layout — and what it creates is what ends up in the scene. ```lua function content() for i = 0, 4 do local crate = entity.spawn("crate") crate.localPosition = { i * 2, 0.5, 0 } crate.component.add("Model", { model = asset.resolve("cube", "mesh") }) end end ``` The build runs while you author, in **edit** mode, and what it created lands in the live scene. Saving the scene bakes it into `scene.json`, which is what makes the entities durable content: a human can select and inspect them, they replicate, and they are there when the world opens without `build.luau` running at all. Play mode never runs it — in play the entities load from `scene.json` like anything else the scene holds. **Editing the file rebuilds the scene in place.** Writing `build.luau` is the signal; there is nothing to reload, and the rebuild saves. An entity keeps the id it had, so a reference to it — a spawn naming a prototype, another entity's component naming this one — survives every rebuild. Add a crate to the loop and the other four do not move. A write through `write_file`, `edit_file` or the engine's `bash` answers once the rebuild it started has finished, so what the rebuild landed and kept comes back on that answer as a notice, whose `message` is the report's summary line: ``` [info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main", editorOnly="1", kept="1", message="build.luau against the scene: kept 1 value on 1 entity (crate_3); ..." } ``` A rebuild still running when the write's wait ends is named under the answer's `startedWork`, and its notice arrives on a later call. An edit saved while a rebuild is still running is an edit to code that rebuild has already read, so it gets a rebuild of its own once that one finishes, and says which it was: ``` [info] a write to build.luau arrived during a rebuild and was rebuilt after it { content="7", scene="scenes.main", editorOnly="1" } ``` Several edits saved during the same rebuild get the one run after it, which reads the file as it stands then. A scene that declares a build also runs it when it **loads** in edit, so the scene shows what the code says now, including an edit made while the world was closed. A load whose `.build.state` records the current script reads `scene.json` as the build and runs nothing. When the load does run it, a world's own scene saves the result, unless the scene holds unsaved edits: those stay the author's to keep or discard, and the file write waits for their save. A library scene (one under `/libs/`, the `@builtin` library included) is read by its load: the build lands in the live scene and its files stay as the library states them. Play reads `scene.json`, so it comes up without that build until `:build()` saves it. ### The two surfaces - `content()` — the scene's own entities. Present in play. - `editorOnly()` — entities present while authoring and absent in play. They carry the `EditorOnly` participation the runtime deactivates and hides when play begins, and they are baked too, so a collaborator opening the world sees the same ones. Anything an author needs to see and a player does not goes here — an alignment guide, a spacing marker, a debug volume. Both are optional. A scene with neither has no build. ### What a rebuild touches Only the entities the build itself placed. Anything a human dragged in, or a tool placed directly, is invisible to a rebuild and never moved or removed. Within what it owns, the build is authoritative: an entity the code stopped emitting is despawned, a component it stopped adding is removed. A plain rebuild keeps a hand edit to an entity the build placed: a value `build.luau` states the way the last build stated it is left as the scene holds it, so a move, a rename, an attribute, the active flag, the lifecycle mode, the replication scope or a component field changed since survives the rebuild, the one a write starts included. To see every such edit, ask the build for its report: ```lua local report = layers.active.asset:build({ save = false }) print(report.message) -- opens with one line counting all four lists ``` On a scene already holding what the build states it leaves nothing to save, and it answers `kept` (hand edits to entities the build placed), `driven` (fields another component writes at runtime, such as a sky orienting the sun), `handAdded` (components and attributes added by hand to built entities) and `handPlaced` (entities no build placed). An entity's render layer and its `hide()` switch are runtime state no build sets, so the lists leave them out; the answer states what the scene holds on both for the entities a build placed instead, in `renderLayers` (`{ entity, name, layer }`) and `hidden` (`{ entity, name }`), and its message counts them ("render layer set on 3 (...); hidden by hide() 0"). It also names the scene it compared: `client` is the client of the world it ran in (`user`, or a sub-client's id), since every client holds its own live scene, and `unsaved` lists the edits that scene held beyond the saved `scene.json` (the entries `sceneAuthoring.changes` lists), so an empty `unsaved` makes the report a statement about `scene.json`. To land `build.luau`'s values over the kept ones: ```lua layers.active.asset:build({ restate = true }) ``` A restate writes exactly the values `kept` names, so the scene's diff after one is the report. To bring a `handPlaced` entity into the build, delete the hand-made one and save the scene, then write it into `build.luau`: the write rebuilds at once in every client and the writing client saves its rebuild, so a delete left unsaved in another client can come back. A hand-made entity still standing under a name the build now places is reported with `builtTwin`, a second copy beside the build's, and the message names the calls that settle it. The message also compares the report against `scene.json` as saved: it names each unsaved edit and what it changed, and any entity whose live state differs from the scene's files with no unsaved edit behind it (a write this client has not taken), with the calls that take that client back to `scene.json` before anything saves from it. `guides { path: "core/scenes-as-code" }`, "What a rebuild touches", gives the shape of every entry and how `driven` and `restate` meet. The build writes its own name and each entity's place in the hierarchy onto the entity, and `scene.json` records that pair beside the entity's name and transform — which is why a rebuild after a reload, in a later session, lands on exactly the entities it placed the first time without anything having been remembered. ### When the file did not change `:build()` runs the build against what it resolves right now — for the case where something the builder *reads* changed and the file did not: a module it requires, an asset it resolves. After a write it is unnecessary; the write has already run it. ```lua layers.active.asset:build() -- rebuild and save layers.active.asset:build({ save = false }) ``` It answers with how many entities each surface placed — `{ content = 6, editorOnly = 1 }` — and with nil for a scene that has no `build.luau`. Called while a build for that scene is already running, it returns at once with `{ inFlight = true, scene, trigger, startedBy, message }` naming that build instead of starting a second one; `inFlight` is what tells the two answers apart. An operation the bake cannot hold is **refused** rather than applied. A build accepts what its records carry: entity lifecycle, transforms, hierarchy, names, visibility, active state, participation mode, network scope, attributes, and components with their public data. Anything else raises while the build runs, naming the operation and the build it answered to, instead of leaving the scene depending on something no reload brings back. When that happens the previous build stays exactly as it was. A runtime resource a build needs — a mesh it generates, a texture it writes — is made as an asset instead, below. Everything else a refusal names goes outside the builder, or into a component the builder attaches, which runs at play. ### The assets a build makes `build.asset(type, name, produce)` makes an asset the build's content names — a mesh a lathe produces, a texture a pattern writes. `produce` takes nothing and returns the creation parameters `asset.create` takes for that type; the call returns the asset's `AssetRef`, which is what a component field holds. ```lua function content() local tower = build.asset("mesh", "tower", function() local positions, indices = lathe(profile, 16) return { positions = positions, indices = indices } end) entity.spawn("tower").component.add("Model", { model = tower }) end ``` The asset is authored inside the scene's own folder — `Lobby.scene/tower.mesh` — and the scene records which `build.luau` produced it in `.build.assets`. So `produce` runs when the build script changed and never otherwise: a reload re-runs the build and reuses the asset, while editing the profile re-authors `tower.mesh` **in place**, keeping its path and its guid. That is what holds the reference — `scene.json` names assets by guid. For a part of a scene that several scenes place — or that one scene places many times with different settings — see `guides { path: "types/sceneModule" }`, which is the same idea with declared `inputs` a placement sets. `guides { path: "core/scenes-as-code" }` covers both. ## The entrypoint `entrypoint.luau` is the scene's **runtime** — what happens while the game is being played. What the scene *is* comes from `build.luau` above; nothing here has to construct it. `entrypoint.luau` is auto-discovered as a sibling of `scene.json`. The loader runs it in a fresh environment and folds its top-level `function name(...)` declarations into the matching scene lifecycle event. Define the callbacks the scene needs — the recognised set: - `onLoad()` — the scene loaded in **play** mode. Gameplay-start hook, runs on every connected client. - `onHostLoad()` — the scene loaded in **play** mode, on the client that owns the scene's synced content (the relay room creator; offline and single-player count as host). Fires once. Entities spawned here — and anywhere downstream — become synced automatically, so this is where shared world content is spawned: it runs on exactly one peer, and every other peer receives the entities from the relay snapshot. - `onEditLoad()` — the scene loaded in **edit** mode. Custom per-scene authoring tools. Writing this file while the scene is loaded in edit mode reloads its layer, so the new `onEditLoad` runs after the previous load's `onUnload`. - `onUnload()` — before the scene's entities are torn down. Extra cleanup; engine-managed teardown (entity despawn, resource release) runs separately. - `update(dt)` — per frame in play mode, while the gameplay clock runs. - `editorUpdate(dt)` — per frame in edit mode, running or paused. Play-paused ticks neither hook. The scene loader partitions these strictly on mode; a component's hooks of the same name read `engine.paused` instead, so the two rules differ — `man components` has that table. - `localPlayerReady(player)` — once the local player's avatar is ready. Gameplay wiring for the local player: attach state, bind UI, swap the avatar. The avatar is already placed at the PlayerSpawn, so this is for behavior, not positioning. - `playerJoined(player)` — a remote player joined this scene's room. Use for per-player UI (nameplates, greetings). The local player arrives through `localPlayerReady`. - `playerLeft(eid)` — a remote player left this scene's room. Receives the departed entity's id (the entity is already despawned). Each scene's entrypoint runs in its own environment, so two scenes can declare the same top-level names without clashing. Keep each callback short; push per-scene logic into `scripts/` modules and `require` them. ## Layers Scenes load through the `layers` namespace. - `layers.load(ref, opts?)` — load a scene. `ref` is a scene AssetRef or identity string. Without `opts.additive`, this is a **root** load: it replaces the current root scene. `opts`: - `additive` — load as an overlay alongside the current root instead of replacing it. - `persistent` — keep an additive overlay mounted across mode flips and root swaps. - `origin` — a `{x, y, z}` world offset for the overlay's entities. - `deferred` — spread the entity spawn across frames (for thousand-entity scenes); the load signals complete only once the scene has settled. - `layers.active` — the current root scene proxy (nil before any load). - `layers.list()` — every loaded layer (root + additive overlays). - `layers.find(ref)` / `layers.is_loaded(ref)` — look up a loaded layer by ref. - `layers.onLoad(cb)` / `layers.onUnload(cb)` / `layers.onBeforeLoad(cb)` — subscribe to every scene load / unload (distinct from a scene proxy's own `:on_load` / `:on_unload`, which fire only for that scene). A root scene carries the `players`, `camera`, and `settings` surfaces; additive overlays inherit the root's players and lighting and do not carry their own. ### The scene proxy `layers.active` (and `layers.find` / `layers.list` entries) returns a scene proxy: - Fields: `.guid` (canonical identity), `.name`, `.path`, `.asset`, `.additive`, `.visible`, `.state` (`"loading"` → `"loaded"` → `"ready"` → `"unloading"`), `.ready`, `.players`, `.camera`, `.settings`, `.entrypoint`. - `.camera` — a proxy over the scene's primary camera entity; read and write the live Camera component through it, and `.camera.behaviors._list()` enumerates the available camera behaviors. - `:save(opts?)` — publish the live scenegraph to canonical `scene.json` (see Saving). A convenience that forwards to the scene ASSET's `save` (`self.asset:save(opts)`): the proxy is the runtime view and owns nothing on disk, so persistence lives on the asset. - `:reload()`: unload and reload the same scene (a runtime respawn). A scene with a `build.luau` runs its build again and saves the scene, so `scene.json` holds what the reload built and the next play loads it; a library scene's rebuild lands in the live scene alone. - `:clearDirty()` — discard unsaved edits and respawn from canonical. Forwards to the scene asset's `discard` (`self.asset:discard(opts)`). - `:sceneAsset()` — the durable `AssetRef<scene>` this live layer maps to. - `:promoteDirty()` / `:writeDirty()` / `:hasDirty()` — manage the dirty overlay directly. - `:unload()` — despawn the layer and free its slot. - `:onReady(cb)` — fire once the scene reaches `ready` (latched: a late subscriber fires immediately). ## Multiplayer & relay rooms Every scene has its own relay room, keyed by the world guid, the boot profile, the mode, and the scene guid. Switching scenes with `layers.load` runs a room transition — leave the old room, tear down, join the destination scene's room — all on the client that made the call. Teardown of the old scene never leaks to peers in the new one. In play mode connected to a relay, the scene's entities are host-authoritative: only the room creator instantiates them (marked synced), and every joiner receives them from the relay snapshot rather than spawning their own. This is why shared world content belongs in `onHostLoad` — spawning it in `onLoad` would run on every peer and duplicate it. Each player's own avatar spawns per-user from the PlayerSpawn on every client. Edit mode and offline boots spawn locally and never auto-sync. ## Loading and saving **Loading** — `layers.load(ref)` for a root scene: 1. Despawns the current root scene's non-persistent entities. 2. Instantiates the entities from `scene.json` (including the player prototype and spawn for a `"spawns"` scene). 3. Applies lighting and sky. 4. Runs `entrypoint.luau` and fires lifecycle callbacks as their events occur. **Saving** — persistence lives on the scene ASSET. `sceneRef:save()` writes the scene's current state back to canonical `scene.json`; when the scene is loaded it captures the live scenegraph, and when it is not loaded it promotes the pending dirty overlay. `layers.active:save()` is the convenience form — it forwards to the active layer's mapped asset (`layers.active.asset:save()`). Writing canonical is the only path that does so: edit ↔ play cycles never save, so hitting play to test never overwrites the scene. Between saves, live edits accumulate in a per-scene dirty overlay that the loader merges on top of canonical. `sceneRef:discard()` throws the overlay away and restores the saved state — deleting the overlay, and respawning the live layer when the scene is loaded. It works whether or not the scene is loaded, because the overlay belongs to the asset, not the runtime layer. `layers.active:clearDirty()` forwards here. Saves capture entity data, not the entrypoint script — edits to `entrypoint.luau` and `scripts/` are always preserved. `opts.to` on `save`/`discard` targets a different scene ("save as"), taking either a bare name (`"level_2"`) or a full VFS path. **What a record states.** A component's record in `scene.json` holds the fields that instance's configuration states: the keys of the table it was added with (a `build.luau` call's own init table, or the record it was loaded from) and every field written since, through code, a tool or the inspector. A field nothing set stays out of the record and takes the component's declared default each time the scene loads, so changing that default reaches every entity that left the field to it. To have an entity follow the default again, remove the field from its record. A field set on a live entity after its record was made is a change the scene review names (`sceneAuthoring.changes` lists it as `+ Type.field = value`), and accepting it writes the field into the record. A stored value cannot be told apart from one an author chose, so a stored value loads and saves as it is, and a hot reload that changes a default one of them shadows names it. A stored field the component no longer declares is named by a `[component.add]` warning when the record loads and left out of the next save. ## Lighting Lights are ordinary entities: a directional light, an ambient light, and a sky are entities carrying `Light` / `ProceduralSky` components in `scene.json`. Author, move, and tune them like any other entity. If a scene is missing any of {directional light, ambient light, sky}, the loader adds a temporary default for the absent one so a scene never loads dark or skyless; the defaults are never saved into the scene. Scene-level lighting state that is not an entity — clear color and sky descriptor — lives under `layers.active.settings.lighting` (`clear_color`, `sky`); writing those fields updates the engine live. ## Modes Scenes load in both edit and play mode (see `man modes`). The mode governs behavior: - An entrypoint's `update(dt)` runs in play while the gameplay clock runs, and its `editorUpdate(dt)` runs in edit. A component's hooks of the same name follow the clock rather than the mode — `man components` has the four states that produces. - Player prototypes are live in edit and deactivated + internal in play, where each user instead gets a clone. `EditorOnly` entities follow the same edit-live / play-internal toggle. - `onLoad` / `onHostLoad` fire on a play-mode load; `onEditLoad` fires on an edit-mode load. ## How to create one ```luau asset.create("scene", "<Name>") -- Creates /zero/source/<Name>.scene/ with: -- build.luau where this scene's content is written. A new one starts -- with the sun / ambient / sky lighting and the "spawns" -- player setup, commented for editing — everything else the -- scene comes to hold is written here too. -- scene.json what that code produces, baked. -- entrypoint.luau commented lifecycle-callback stubs. ``` A freshly created scene has a player with a following camera on the first press of play. It carries no ground, so the first thing to author is what the player stands on — a `content()` line away in `build.luau`. ## Discovery - `asset.list("scene")` — every registered scene. - `asset.inspect("<name>")` — entity count, lighting summary, source path, and this type README. ## Authoring conventions - Keep static layout in `scene.json` — geometry, lights, props, the player prototype and spawn. - Keep dynamic setup in `entrypoint.luau` lifecycle callbacks — event listeners, gameplay state, services attached to spawned entities. - Spawn shared, synced world content from `onHostLoad`; spawn each player's own gameplay wiring from `localPlayerReady`. - Set the world's startup scene in `/.world_settings` — that is the scene the world boots into. - Y is up; -Z is forward. - Renaming the folder changes the scene's identity. References to the scene are recorded against the scene itself, so renaming or moving it does not break them. ## Related types - `.bundle` — reusable entity hierarchies that scenes spawn into themselves. - `.service`: a declarative content generator a scene can draw on. - `.world_settings` — picks the startup scene and world-level renderer / physics options. ## In the Inspector Selecting a scene opens its **Scene** section, read from `scene.json` without loading the scene: how many entities it holds, how many of them are roots (and their names), how players join and the file's format version when it states them, and whether the scene has edits not yet saved.
▲ 0↑ born
·
assettype · born here
❒asset
# Scene light (asset type) A scene light is one light that reaches the whole scene alike, as an asset. It is one position-independent `Light` (`directional`, `ambient` or `distant`, the kinds `lighting.isPositionIndependent` answers for) described in `sceneLight.yaml`, and it implements `applicable`: applying it puts that light in force for the applier. ## Where it lives - Source: `<name>.sceneLight/` - Identity: `<name>` (the `.sceneLight` suffix strips from the identity) - Folder shape: - `sceneLight.yaml`: the light. **Required.** - `README.md`: what light it puts on a scene. **Required.** - `.metadata`: `description` and `tags`. **Required.** ```yaml # moonFill.sceneLight / sceneLight.yaml kind: distant direction: [0.3, -0.5, 0.4] color: [0.6, 0.7, 1.0] intensity: 0.3 ``` ## Parameters Its parameters are the `Light` component's own fields for the light, with their descriptors (`intensity`, `colorR`/`colorG`/`colorB`, `directionX`/`Y`/`Z`, `castsShadows`, `lightChannels`, `mobility`), defaulting to what `sceneLight.yaml` states, and three of its own: - `followSky`: whether the sky orients this light (a `directional` or `distant` one). A sky that drives the sun (a procedural backdrop) then writes the light's direction from its hour, and its colour and intensity as the stated ones multiplied by the curve of the sun's elevation: the stated `intensity` is the noon peak, reached from 30° up; toward the horizon the light dims and warms (about 0.3 of the peak at 7°), and below it the intensity is 0. A sun that should follow the sky states `followSky: true` and no direction. - `skyOffset`: where a following light stands from the sun, `[yaw, pitch]` in degrees. Yaw turns it about the vertical, so `[180, 0]` is a fill from the side opposite the sun at the sun's elevation; pitch raises it above the sun. The curve is the sun's, so a fill dims with the sun and is out at night. - `followSkyIntensity` (default `true`): whether a following light takes its intensity from the sky as well as its direction and colour. `true` puts the sun's curve on the stated intensity, as above. `false` keeps the stated intensity while the light stands above the horizon (its own elevation, after `skyOffset`) and 0 below it; the direction and the colour still come from the sky. A sun follows with it `true`; a fill or a rim that should hold its strength through dusk states it `false`. After dark a following light stands at the moon the sky draws, opposite the sun: with `true` it is out, with `false` it is moonlight at the intensity it states. A cool fill for a dusk scene: it stands opposite the sun, a little higher, takes the sky's direction and its warm-to-cool colour, and lands at the 0.9 it states at 17:42, where with `followSkyIntensity` true it would land near 0.18. ```yaml # harbourFill.sceneLight / sceneLight.yaml kind: distant color: [0.5, 0.6, 1.0] intensity: 0.9 castsShadows: false followSky: true followSkyIntensity: false skyOffset: [180, 12] ``` What a following light lands at is not what it states. A placed setup's `SceneSetup:members()` reports, for such a member, `landed` (its intensity, colour and direction now) beside `stated`, and `SceneSetup:get(path)` carries `landed` beside `value` for each of those parameters; `SceneSetup:set(path, value)` returns that read, so setting `fill/intensity` answers what it lands at straight away, and the setup's card shows it on the row (`0.9 → lands at 0.18 at 17:42`). `ref:landed(owner)` is the same answer for one application. ## Applying it Each application spawns a temporary entity of its own (`ref:entityOf(owner)`) and puts a `Light` of the asset's kind on it; it publishes itself as the sun or the ambient term the way every `Light` does, and the last to publish holds it. Dropping the application removes the `Light` and the entity. The `ApplyState` reports `held` while another light holds its kind (`heldBy` names that application's owner, or the holding entity), and a notice when an ambient term is as bright as half the sun or more, which flattens the scene's shading. A write the lighting API makes to the light (`lighting.setSun`, `lighting.setAmbient`, `sky.setSunDirection`) lands on the application, through its owner's writer when it handed one. A kind that lights from where its entity stands (`point`, `spot`) is refused by name (`sceneLight.kind`).
▲ 0↑ born
·
assettype · born here
❒asset
# Sky (asset type) A sky is the sky of a scene in one asset: a composition of **members**, each an asset whose type implements `applicable`, with the values the sky states for them. One of them is a **backdrop**, a render feature that writes the scene's `Sky` row (`@builtin::systems.sky.backdrops.procedural`, `@builtin::systems.sky.backdrops.material`, or a creator's own); the others are whatever else belongs to the sky, such as clouds. A sky has no parameter of its own: its parameters are its members', by path (`backdrop/timeOfDay`, `clouds/coverage`, `clouds/@enabled`). A member whose parameters follow from content its values name has those too: a material backdrop's parameters are its own (`material`, `exposure`, `rotation`) and the shader properties of the material it names (`backdrop/zenith`, `backdrop/glow_size`), each with the material's value as its default. ## Where it lives - Source: `<name>.sky/` - Identity: `<name>` (the `.sky` suffix strips from the identity) - Folder shape: - `sky.yaml`: the definition. **Required.** - `README.md`: what the sky draws. **Required.** - `.metadata`: `description` and `tags`. **Required.** - `preview.png`: its picture. Optional. ## The definition ```yaml members: - id: backdrop source: "@builtin::systems.sky.backdrops.procedural" values: { timeOfDay: 18.5, zenithColor: [0.2, 0.1, 0.3], horizonColor: [0.9, 0.4, 0.2], horizonHeight: 2 } - id: clouds source: "@builtin::systems.volumetrics.volumetricSky" # Omitted values use the package's complete default weather preset. ``` It is read the way a scene setup's is: the same member grammar, the same diagnostics, nested compositions under their member id. A member's `source` is an identity (`skies.parts.haze`, `@builtin::systems.sky.backdrops.procedural`) or a path with its type suffix: absolute (`/source/skies/parts/haze.renderFeature`), from the folder holding this sky (`haze.renderFeature`, `./haze.renderFeature`, `../parts/haze.renderFeature`) or from the world's source folder (`skies/parts/haze.renderFeature`). An identity drops the type suffix, so a sky and a scene setup of one name in one folder share it; their paths name each apart. The scene setup type's README has the whole grammar. A volumetric cloud member's weather is its `preset` table, and a value for it states the whole table. ## Using one A sky implements `applicable`: applied, it applies every member for the owner: ```lua local dusk = asset.resolve("my-dusk", "sky") dusk:as("applicable"):apply("myEntity:sky", { ["backdrop/timeOfDay"] = 19 }) local drawn = sky.drawn() -- { entity, source = dusk, description } dusk:as("applicable"):drop("myEntity:sky") ``` `sky.drawn().description` (the sky's own `describeSky`) is `{ material, timeOfDay, sunDirection, members, notice? }`, built from what is drawn; `notice` is what a member states about the settings it runs, by member path. A procedural backdrop draws its base colours (`zenithColor`, `horizonColor`, `groundColor`) in the shape `horizonHeight` gives them: the elevation in degrees where the sky is halfway from the horizon colour to the zenith colour (default 7.933). A palette whose horizon colour is a band, such as a sunset's orange under a violet sky, lowers it (to 2, say) so the zenith colour shows at eye level. The backdrop draws them while the sun is high and its night and dawn tint sets as the sun sinks, as far as `nightStrength` and `dawnStrength` say; a sky that holds one hour states its look in the base colours with both strengths at 0, and the notice names a set that masks the base colours at the hour drawn. The backdrop's README has the table of which set shows at which hour. A light that follows the sky (`lighting.followSky`) is oriented by a procedural backdrop's hour. **Moon and moonlight.** A procedural backdrop draws its moon opposite its sun, at the hour it draws. After dark a light that follows the sky stands at that moon: a sun that takes its intensity from the sky is out, and a light that keeps its own (`followSkyIntensity: false`) is moonlight at the intensity it states, from where the moon is drawn. A night setup keeps the two together by giving its moonlight `followSky: true`, `followSkyIntensity: false` and a moonlight intensity and colour (a setup nesting a day setup sets its sun's `followSkyIntensity` to `false` and its intensity to the moon's), so the light stands where the moon is drawn. ## A material sky's shader values A sky drawn by a material takes that material's shader properties as parameters, so a sky, a setup nesting it, or a placement states them by path like any other value, and a setup's card lists them: ```yaml # night_variant.sceneSetup/sceneSetup.yaml: the base setup, its sky's glow raised members: - id: base source: "./base.sceneSetup" values: "sky/backdrop/glow_intensity": 2.5 "sky/backdrop/zenith": [0.02, 0.01, 0.08, 1] ``` The backdrop draws the material itself while every value stated for it is the material's own, and a runtime copy of the material with the stated values laid over its own once one differs; the material asset is not written. Two applications of one backdrop are arbitrated the way every render feature's are: the newest that states something new is in force, and dropping it brings back the values of the one before it. ## Making one ```lua asset.create("sky", "aurora", { members = { { id = "backdrop", source = "@builtin::systems.sky.backdrops.material", values = { material = "my-aurora-material", exposure = 1.2 } }, } }) ```
▲ 0↑ born
·
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
·
renderfeature · born here
❒asset
# ambientOcclusion The render pass behind the `AmbientOcclusion` component and the `ao` module. It stands in the `lighting` post stage and runs at `afterDepthPrepass`, where this frame's opaque depth is complete and nothing has shaded yet: 1. An estimator writes, per texel of a grid at the quality level's `scale` of the frame, the occlusion of the hemisphere above the surface and its bent normal (the mean open direction): `ao_pass`, the screen-space horizon integral over a visibility bitmask, or `ao_trace`, rays traced against the scene acceleration structure while `traced` is set and the scene's ray tracing is on. 2. `ao_temporal` carries the estimate across the renders of each view, reprojecting the view's previous accumulation through its previous view-projection and taking it only where the depth says the surface is the same one. The accumulation is a history target (`history = true`), so the viewport, every render-to-texture camera and every capture read and write their own, and its state says when a view's previous image is there to read. 3. `ao_filter` lifts the grid to the frame's resolution, weighing each tap by depth, and writes the scene's occlusion channel (`@scene.ao`): occlusion in r, the bent normal laid flat on the octahedron in g and b, and in a whether a bent normal was written. 4. With the `ao` module's `indirect` on, the estimate is `ao_pass_indirect`: the same walk (`ao_walk`), which also gathers, over each run of sectors a tap closes first, the light that occluder sent toward the camera in the view's previous render (`@scene.colorHistory`), where that render drew the same surface there and its face turns toward the surface. `ao_light_temporal` carries the gathered light across the view's renders like step 2, and `ao_light_filter` lifts it into the scene's indirect channel (`@scene.indirect`): the light in rgb and the share of the closed hemisphere it answers for in a. A traced estimate runs that walk beside it for the light. The light passes stay out of a reflection probe's cube faces, which continue no render of their own. Every lit material reads the channel at its own pixel the same frame, on its indirect light alone: `FragmentData.ambient_visibility` carries the open share, and PBR shading (`zero_pbr_shade`) takes it on the diffuse lobe with the light the surface's colour bounces back into a crease, and on the reflection lobe as the share of that lobe the open cone around the bent normal holds (`zero_scene_bent_normal`, `zero_pbr_indirect_visibility`). The gathered light reaches the diffuse lobe in place of the surroundings' light the occlusion took from the closed part (`zero_scene_indirect_here`), and the crease-return estimate stands only for the share the gather did not answer. Direct light, emissive surfaces and transparents keep the light they carry. Both estimators reconstruct the surface normal from this frame's depth. Depth and camera come from the render target being drawn, so the pass is correct in offscreen captures and render-to-texture cameras at their own resolutions. Sky pixels have no surface to occlude and write none. The `ambientOcclusion` capture view is drawn into a target the pass makes when a capture of the view asks for it and releases once captures stop asking; its passes run on that capture's channel alone. Settings arrive through the `ao_params` buffer, packed by the `ao` module, which also reports what the pass built through `ao.stats()`.
▲ 0↑ born
·
renderfeature · born here
❒asset
# probeGI Indirect diffuse light from a field of probes traced against the scene. The field is up to four nested grids of probes (cascades), each centred on the camera and each with `cascadeSpacingRatio` times the spacing of the one before, so the finest holds the nearest surfaces in detail and the coarsest reaches far. Every frame each probe shoots `raysPerProbe` rays through the scene's acceleration structure and records what comes back: the sky where a ray leaves the scene, and at a surface the sun's light (with a shadow ray toward the sun), the light of the scene's point, spot, area and distant lights (with a shadow ray toward each), the surface's emission, and the light that surface takes from the field as the previous frame left it. That last term carries light from surface to surface, one bounce per frame. The scene those rays walk holds every entity's model and every drawn copy of each population `renderer.mesh.drawInstanced` registers as `traced` (which follows `castsShadows` unless the registration says otherwise), so plants and props block the sky and the sun from the probes under and around them and send their own colour back. A population whose matrices only a compute pass writes cannot be placed and reports `traced = "noCpuTransforms"` from `renderer.mesh.instanceInfo`. Each probe keeps two small octahedral maps of the sphere around it, blended over frames by a hysteresis: the irradiance arriving from each direction (and, in the alpha, the share of the sky it sees that way), and the mean and mean-squared distance its rays travel in each direction, each ray counted at most a cell diagonal of its cascade far (and, in the blue, the share of rays that left the scene). A surface reads the eight probes around it, weighted by trilinear share, by how squarely it faces each probe, and by the Chebyshev bound on how much of the way to the surface each probe sees clear, so a probe on the far side of a wall carries no weight. What a surface reads is stable under camera motion because the maps live in probe space and each grid is anchored to the world. ## Holding still, and following a change A probe's rays leave in new directions every update, so each update of one direction's texel differs from the last by the sampling noise of its rays: a few rays that find a small emitter, a random point across an area light, the light the surfaces they hit pass on. Whether the probe's light changed is read over the whole probe: where the mean of its tile moved by no more than `changeSigmas` standard errors of the mean of its rays (the noise its recent updates carried), its recent updates do not lean to one side of what it holds, and the share of the sky it sees did not move past its own noise, the update is noise and every texel keeps `stillHysteresis`, so a still scene settles to a still field. Past that, the light changed and the texels keep `irradianceHysteresis`; past `changeThreshold` of the smaller of the new and held means as well, up or down, they take `hysteresisFloor`, so a sun that steps or a lamp that switches on shows within a few frames. The distance moments read their probe's mean distance the same way, between `stillHysteresis` and `visibilityHysteresis`, and follow the irradiance where it found a change. Each blend rounds to half precision at random in proportion, so a blend that keeps most of the past still moves the stored value by what it should on average. A probe whose cell enters its grid, or whose field has just started, is young for a dozen updates: it updates every frame, whatever its cascade's turn, and takes the mean of the updates it has had, so a new field reaches its light in a few frames. A probe whose cell entered takes the plain mean of its first dozen updates. A probe that started with its field (the field started, or its cascade's grid moved by its whole extent at once) reads a field that climbs bounce by bounce as every probe in it starts, so its earlier updates hold less of the light than its later ones: its irradiance takes a mean of its first two dozen updates in which the k-th, counted from 0, weighs (k + 1)(k + 2). Until four dozen updates it blends by the hysteresis, never the still one, while the light the field passes on climbs bounce by bounce. A young probe outside geometry may move away from a nearby surface; after that it keeps its place, so where it stands does not wander with each update's rays. A probe inside geometry moves out on any update that finds it inside. A probe the store holds inside stays inside until fewer than half of `insideShare` of its rays hit the back of a surface. ## Where each probe stands Each probe also keeps an offset from its lattice position and whether it stands inside geometry, which a pass of its own works out from the probe's rays every frame. A probe more than `insideShare` of whose rays hit the back of a surface stands inside geometry and carries no weight wherever the field is read. One on a solid's boundary (some of its rays left the solid: it stands on a surface, or in a wall where a corner opens) moves toward the side its rays open onto, `probeClearance` of a spacing a frame; one buried in a solid stays put, inside. A probe outside geometry nearer than `probeClearance` to a surface facing it moves away from it. A probe moves at most 0.45 of a spacing from its lattice position along any axis, and one whose cell enters its grid starts on its lattice position. A pass of its own reads the field at every surface in view, multiplies by the surface's diffuse colour and the field's gain and tint, and adds the result to the frame. It reads the G-buffer, so it runs on the deferred path, and it turns scene ray tracing on when it starts. A closed room of walls 0.3 m thick holds the field's light out at a finest spacing of 1 m or 2 m. The reads are taken on a grid of one read per `applyScale` x `applyScale` pixels, and go through the denoiser `denoiser` names (`denoise`): an asset implementing the `denoiser` interface, `@builtin::systems.denoising.svgf` by default. It filters the light arriving at each surface, before the surface's colour: each read is carried from frame to frame through the frame's motion (the camera's, each moving entity's and each animated pose's), let go where the surface under it changed, held to a fast estimate so a change of light shows within a few frames, and smoothed across reads of matching surfaces, most where its history is short. Another pass lifts the reads to every pixel, weighing each by how well the surface it was read at matches the pixel's. Naming another denoiser in `denoiser` swaps the filter; `denoise` off takes the field as each frame reads it. Within `edgeFade` cells of a cascade's edge a point is read partly from the next coarser cascade, whose probes stand farther apart. A coarser probe and the finer probe that weighs in most at the point must see each other, so a coarser probe past a wall the finer probes resolve carries no weight there, and the coarser cascade takes its share only as far as its probes see the point as clear as the finer cascade's do; the rest stays with the finer cascade. A room of walls 0.3 m thick in a field only eight probes tall, most of it inside the fade band of its finest cascade, holds the coarser cascades' light out too. The field's sky is the captured sky of a sky light member: `skySource` names it and its captured environment is what a ray that leaves the scene returns. The field is where the sky's diffuse light is occluded, so a scene that places it gives the sky light a `diffuse` of 0. ## The scene's lights A ray's surface takes the light of the lights the light grid lists where it stands, with the falloff, spot cone and rect integral the surfaces are shaded with (`@builtin::shaderModules.scene_lights`), so the bounce a lamp sends is in the units of its direct light: the lamp that lights a red floor directly lights, through the field, the wall that floor faces. The surface counts as one on the default light channel. Of the lights that reach it, it takes the `maxLocalLights` that put the most light on it unshadowed and traces one shadow ray toward each, as long as the way to the light, so a lamp behind a wall adds nothing on the far side of it. A rect light's ray goes to a point drawn across its face for each ray and frame, so the field, which blends its rays over frames, reads the share of the rect a surface sees. Each light a ray's surface takes costs one shadow ray, so the trace costs at most `raysPerProbe` x probes x `maxLocalLights` shadow rays a frame for the scene's lights, on top of its own rays and the sun's. A light out of reach of a surface (past its radius, outside a spot's cone, behind a single-sided rect) costs a few compares there and no ray. A surface reached by more lights than `maxLocalLights` takes is stated: the field reads its stats store back every 60 drawn frames, and while a ray hit since the read before was reached by more, the sentence naming how many reached it stands in the feature's log, in `live.droppedLights` and in the member's notice. ## What it publishes `modules.state("@builtin::systems.probeGI.probeGI.live")` holds the field's parameter buffer (`params`), the two atlas pairs (`irradiance`, `visibility`), the ray store (`rays`), which of each pair the last frame wrote (`current`), `droppedLights` (the sentence stating that ray hits are reached by more of the scene's lights than `maxLocalLights` takes, nil while none are), and `skyVisibility`: a screen-sized picture with, per surface in view, the share of the sky it sees over its hemisphere in red and along its mirror direction in green (widened toward the hemisphere's by roughness). A sky light member whose `occlusionSource` names this member scales its diffuse and reflection terms by that picture. ## Parameters | name | default | what it is | |---|---|---| | `probesPerAxis` | (16, 8, 16) | Probes each cascade holds along x, y and z, each 2 to 64; every cascade holds that many, and the whole field holds at most 65536 probes. A setting past that limit is stated in the feature's log, in `live.clamped` and in the notice of the member's application, with what the field holds. | | `cascades` | 3 | Nested grids, 1 to 4. | | `baseSpacing` | 1.5 | Distance between neighbouring probes of the finest cascade, in world units. | | `cascadeSpacingRatio` | 2 | How many times a cascade's spacing the next coarser has. | | `followCamera` | true | Whether the field is centred on the camera. | | `anchor` | (0, 0, 0) | The field's centre when `followCamera` is off. | | `belowShare` | 0.6 | The share of each cascade's height that lies below the camera. | | `edgeFade` | 3 | How many cells inside a cascade's edge its light fades over into the next coarser cascade. A point no cascade holds reads the coarsest cascade at its nearest cell. | | `gridOffset` | (0.5, 0.5, 0.5) | Where the lattice sits relative to the world's whole multiples of the spacing, in spacings. | | `raysPerProbe` | 48 | Rays each probe shoots every frame, 8 to 256. | | `irradianceHysteresis` | 0.97 | Share of a probe's irradiance carried over per sixtieth of a second: a slower frame carries over proportionally less. | | `hysteresisFloor` | 0.8 | The share carried over where a probe's light changed (`changeThreshold`, `changeSigmas`). | | `changeThreshold` | 1 | How far a probe's mean luminance must move, up or down, as a share of the smaller of its new and held values, before the probe takes `hysteresisFloor`. | | `stillHysteresis` | 0.995 | Share of a probe's irradiance and distances carried over per sixtieth of a second while what its rays find stays within `changeSigmas` of their noise. | | `changeSigmas` | 4 | How many standard errors of the mean of the probe's rays a move must pass to count as a change: within it, the move is the noise of one update's rays. | | `maxCatchUp` | 2 | The most sixtieths of a second one drawn frame advances the field, 1 to 12. A frame after a longer gap (an editor that idles and wakes, a slow frame) blends as if only this many had passed, so one frame keeps at least `irradianceHysteresis^maxCatchUp` of the history (0.94 at the defaults, `hysteresisFloor^maxCatchUp` = 0.64 where a texel changed past `changeThreshold`) and the field follows a lasting change within a few dozen drawn frames. At 12, a frame after a long gap keeps 0.69 of the history. | | `visibilityHysteresis` | 0.97 | Share of a probe's distance moments carried over per sixtieth of a second. | | `visibilitySharpness` | 50 | Cosine power a ray weighs in by when it joins the distance moments. | | `irradiancePower` | 1 | Cosine power a ray weighs in by when it joins the irradiance. | | `bounceGain` | 1 | How much of the light a surface takes from the field is sent on again. | | `maxBounceLuminance` | 16 | The most luminance a ray carries back; 0 sets no limit. | | `skySource` | empty | The sky light member whose capture rays that leave the scene return; empty, black. | | `skyIntensity` | 1 | Gain on the sky's light. | | `skyBelowHorizon` | 0 | Share of the sky's light kept by a ray that leaves the scene below the horizon. | | `sunIntensity` | 1 | Gain on the sun's light at a ray's surface. | | `localLightIntensity` | 1 | Gain on the light of the scene's point, spot, area and distant lights at a ray's surface. | | `maxLocalLights` | 8 | The most of the scene's lights one ray's surface takes, 0 to 16, each with a shadow ray: the ones that put the most light on it. 0 takes none. A surface reached by more is stated (above). | | `emissiveGain` | 1 | Gain on emitted light. | | `maxRayDistance` | 200 | How far a ray looks, in world units. | | `normalBias` | 0.25 | How far, in spacings, a read point moves along its normal. | | `viewBias` | 0.1 | How far, in spacings, a read point moves toward the viewer. | | `weightCrush` | 0.2 | Probe weights under this fall off by their cube. | | `intensity` | 1 | How much of the field's light reaches the frame; 0 draws nothing. | | `tint` | (1, 1, 1) | A colour the field's light is multiplied by. | | `minimumIrradiance` | 0 | A floor under the irradiance over pi any surface receives. | | `probeClearance` | 0.1 | How far, in spacings, a probe keeps from the surfaces around it: a probe on a solid's boundary moves out by this much a frame, and one outside geometry nearer a surface than this moves away from it to this far. | | `insideShare` | 0.25 | The share of a probe's rays that hit the back of a surface past which the probe stands inside geometry, where no surface reads it. | | `update` | true | Whether the probes trace and blend every frame. Off, the field keeps the light, distances and probe places it holds, its grids stay where they stand, and every surface reads it as it stands, so two frames drawn apart read the same field: what changes between them is what else changed. On again, the field goes on from what it holds. | | `denoise` | true | Whether the reads at the surfaces in view go through `denoiser`. | | `denoiser` | `@builtin::systems.denoising.svgf` | The denoiser the reads go through: any asset implementing the `denoiser` interface. | ```yaml # a setup member - id: probeGI source: "@builtin::systems.probeGI.probeGI" values: skySource: "@builtin::systems.sky.skyLight" raysPerProbe: 48 ``` ## At lower quality levels The settings that carry its cost scale with the device's quality level (`Field.scaled`): the values a setup authors are the high look, and `renderer.feature.resolved(handle)` states what each level draws. The `graphics-quality` guide lists the rules.
▲ 0↑ born
·
renderfeature · born here
❒asset
# heightFog The render pass behind the `HeightFog` component and the `fog` module. Fog over a scene comes from adding that component to an entity; this feature runs while its density is above 0. Two compute passes in the `medium` stage: 1. `height_fog_light` reads the light of the surroundings at the camera of the view being drawn (the scene's ambient term, the captured sky and reflection probes, the light-probe volumes, averaged over every direction) into one texel. 2. `height_fog` reconstructs each pixel's world position from `@scene.depth` and the drawn camera's inverse view-projection (`@frame.camera`), integrates the height-falloff density along the view ray analytically from `start` to the surface, and composes `surface * exp(-tau) + light * (1 - exp(-tau))`. `light` is the fog's colour times the scene's sun (`@frame.light`, through a Henyey-Greenstein lobe) plus the surroundings' light from the first pass, so with every light dark the fog only dims what is behind it. Working in world space is what lets density vary with altitude and what lets the medium respond to view direction — neither is expressible from screen depth alone. Parameters arrive through the `heightfog_params` buffer, which the feature packs from its settings. The fog is drawn over everything in view, the sky included: a sky pixel takes the fog of its whole view ray, the lit medium where the fog never thins and the column the ray climbs through where it does. Because the camera rides `@frame.camera`, the fog is correct in offscreen captures and render-to-texture cameras at their own resolutions, not only in the live viewport. The passes declare `environmentCapture = false`: the sky fallback and the reflection probes the fog is lit by are captured without it, so each capture holds the light of the scene as it stands, and a reflecting surface is seen through the fog in front of it.
▲ 0↑ born
·
renderfeature · born here
❒asset
# ssr The render feature behind `ScreenSpaceReflections` and `@builtin::systems.reflections.ssr`. Two compute passes run at the `afterDepthPrepass` seam, once the visibility raster has laid the frame's depth and before anything shades: | order | pass | output | |---|---|---| | 60 | `ssr_trace` | one ray per pixel, drawn from the pixel's GGX lobe: where it hit and how confident the hit is, or the direction it travelled when it found nothing, into the feature's `ssr_rays` target | | 61 | `ssr_resolve` | each pixel's lobe gathered over its own ray and its neighbours' rays, accumulated over frames in the feature's history target, into `@scene.reflection` | That channel is what a material's environment term reads the same frame, at its own pixel: the traced light, mixed over the probes and the sky by the share of the surface's lobe the screen answered, with the material's own Fresnel, roughness and tint weighing it into the pixel the way they weigh any environment. Nothing here touches the lit picture. The trace marches against this frame's depth, which the visibility raster has just written, so the reflection stands where the camera is now. What it reads about the surfaces (the reflecting surface's normal and roughness, the hit's normal) comes from the previous frame: the G-buffer as that frame left it (`readsPrevious`), reprojected through the previous view-projection `@frame.camera` carries in its rows `[5..9)`. The resolve reads the light at each hit from `@scene.colorHistory`, the light the previous frame ended with, at the pixel the hit stood at then. A point the previous frame did not show reflects its environment alone. ## The rays Every pixel draws one ray from the lobe its roughness describes. A mirror (below perceptual roughness 0.1) takes the reflection vector. A rougher pixel samples a half vector from the distribution of normals visible from the camera (Heitz 2018) at `alpha = roughness²`, and reflects the view ray about it, from noise that depends on the pixel and the frame. Each ray carries the density it was drawn with, as `log2(pdf)`, so the resolve can weigh it against another pixel's lobe. The ray texel is `rgba16f`: for a hit, `xy` is the hit pixel minus this pixel (in whole pixels), `z` is `log2(pdf)` and `w` the confidence in (0, 1]; for a ray that found nothing, `xy` is the octahedral encoding of the direction, `z` the same `log2(pdf)` and `w` is -1; a pixel that traced no ray holds zero. A mirror ray carries 15 in `z` in place of a density. ## The march `ssr_trace` walks the ray through the depth buffer. Steps are uniform in **screen** space, not world space. A ray heading toward the horizon covers enormous world distance across a few pixels, so stepping in world units there means either missing every thin occluder near the camera or spending the whole budget on distance nothing can be seen at. The world parameter is recovered from the screen parameter through `1/w`, which is what interpolates linearly under perspective. At each step the ray's world position is compared against the world position reconstructed from the depth sample under it. Comparing in world space is what lets `thickness` mean a distance in world units rather than a depth-buffer epsilon whose meaning changes with range. The march looks only for the **crossing**, where the ray first passes behind the depth buffer. Thickness is tested after bisecting that crossing, not during the march: one march step covers roughly as much depth as a surface is thick, so a ray tested during the march can jump from in front of a surface to well behind it without ever landing inside it. Bisection runs for whichever is larger, the quality tier's budget or however many halvings bring one march step under `thickness`. A coarse march that stopped bisecting early would leave the crossing bracketed more loosely than a surface is thick, and every hit would then fail the thickness test, so long-range reflections would vanish outright instead of thinning. A rough pixel's ray marches fewer steps and refinements (down to 0.35 of the tier's, reached 0.65 of roughness above a mirror), because the resolve blurs what the rays find. A hit on a surface that faces along the ray (what is on screen there is that surface's far side) is trusted at half the confidence. ## The resolve For each pixel the resolve gathers its own ray and up to `taps` neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`) on a disk of up to 6 px that turns with the pixel and the frame and grows with roughness. A neighbour counts only where its normal is within 0.9 of the pixel's and its depth within 5 percent. Each ray is weighed by the pixel's own lobe: `D · Vis · cos / pdf`. A pixel's result is the light of the rays that hit and the share of the lobe they cover. A ray that found nothing counts toward the lobe and carries no light. The history accumulates that result, premultiplied, at up to 0.9 of the previous frame for a rough surface and none for a mirror, with the history's light and coverage both held to the mean plus or minus 1.25 standard deviations of the rays gathered: a reflection whose rays now find nothing keeps nothing. ## What the channel holds `@scene.reflection` holds linear radiance in `.rgb` and in `.a` the share of the lobe the screen answered, multiplied by `intensity` and by the hand-over above `roughnessCutoff`. A surface at or below the cutoff keeps the full share, one 0.1 above it holds zero, and between the two the share fades. A miss is a zero the material reads as "the environment alone". The channel is cleared at the top of every scene render this feature does not run for, so such a frame reflects the environment alone too. The passes read the light the previous frame ended with, so they run on the lit channel alone (`debugChannel = 0`); a camera drawing a diagnostic pass is drawn lit first, unpresented, so the passes run for where that camera stands, and the diagnostic reads the channel gathered for it. ## Memory Each view that draws the feature holds three screen-sized `rgba16f` images: the rays and the history pair. At 1080p that is about 16.6 MB each, about 50 MB for the viewport.
▲ 0↑ born
·
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. What a render feature draws into the capture (an atmosphere's sky, a layer over the sky) is part of the picture. A capture, and the sky slot the sky light publishes, is taken once every live render feature has drawn with the settings it holds, so a setup applied in one step is captured as it stands once all its members are in force; the wait ends after 120 drawn frames at most. With `followSky` on, a change of value in the settings of a render feature that runs in environment captures (its `contentRevision` in `renderer.feature.list`) takes a capture and, with `publishReflection` on, publishes the sky into the slot again, at most once per `recaptureInterval` seconds. The sky light's own settings do not count. 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, the sun's direction or the settings of a render feature that runs in environment captures 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
·
renderfeature · born here
❒asset
# taa.renderFeature One compute pass in the `temporal` stage and the depth it restates for the passes after it, its sharpening in the `display` stage after the debanding and the edge antialiasing, and a per-frame offset to where the projection samples. ## What it does A pixel is one sample of a continuous image. Which point inside the pixel that sample is taken at is normally fixed forever, and that is what makes an edge resolve to the same staircase in every frame — the frames agree because they all ask the same question. This pass moves the sample. Each render the projection is offset by a sub-pixel amount (`renderer.setProjectionJitter`), so consecutive renders are different estimates of the same image, and the pass keeps a running result across them. After a handful of frames that result holds detail no single frame contains: a silhouette becomes a gradient, a specular highlight stops flashing on and off as it crosses the sample point, fine texture stops crawling. Where the samples go matters. The offsets come from a Halton sequence in bases 2 and 3 — successive points of a low-discrepancy sequence avoid each other, so a short run of frames covers the pixel evenly, where independent random points clump and leave gaps and a regular grid repeats as a visible texture. The two bases are coprime, so the axes do not fall into step. Eight offsets is enough to resolve an edge and short enough that the result refreshes before anything drifts. ## Carrying the result forward The accumulated result is only usable at a pixel where it describes the same surface. These tests decide that, in order. **Where to look.** `@scene.motion` gives the screen-space velocity of the surface under each pixel — where it was in the previous frame. The velocity is read from the closest-depth pixel of the 3x3 neighbourhood rather than from the pixel itself: along a moving silhouette the pixel's own velocity belongs to whichever of the two surfaces won the depth test, and the nearer surface is the one whose edge is sweeping across the pixel. The history is read there through a Catmull-Rom spline rather than bilinearly: a bilinear read averages the four texels around the point, so a history reprojected a fraction of a pixel every frame softens a little more each frame, and a slow pan blurs thin lines away. **Whether to look at all.** A reprojection landing outside the frame has nothing recorded there. That pixel starts its own accumulation from the current frame rather than inventing one. **Whether something used to stand in front.** Each render also records how far from the camera every pixel's surface stood (a second history target). Where the previous render held a surface well in front of the one here now, what reprojects onto the pixel is whatever used to cover it, and the pixel starts over from the current frame. The farthest of the four recorded texels around the reprojected point is the one compared, so a thin object whose edge falls on a different side of a texel each render does not read as having moved away. **Whether the answer is still about this surface.** Something newly uncovered reprojects to wherever the thing that was covering it went, and reads as a perfectly valid sample of the wrong surface. That is the smear temporal antialiasing is known for. The neighbourhood's own colour statistics bound it: the 3x3 block around the pixel describes what colours belong there now, so the carried sample is clipped into the range the mean and standard deviation of that block describe before it is trusted. Mean and spread rather than min and max, because a single bright texel stretches the extremes far enough to admit a sample that is nothing like the pixel, while the standard deviation stays honest about how much the block actually varies. The clip runs in YCoCg and along the line from the neighbourhood mean. Luminance is one axis there, so the box tracks a neighbourhood that varies mostly in brightness far more tightly than an RGB box, whose corners admit colours the neighbourhood never contained. Moving the sample along a line rather than clamping three channels independently keeps its hue, so the result is a colour between two the frame actually holds. ## How much of each frame goes in Every colour is weighed in a reversible tonemapped space (each divided by one plus its luminance, and the result expanded again after), so a highlight many times brighter than its surroundings counts in proportion to how it looks rather than to how much light it carries, and the pixel holds steady as the jitter crosses one bright sample. The frame's sample is not the pixel's own raster sample alone. Each render's projection moves every sample by the same sub-pixel offset, so the pass knows where each of the 3x3 samples around the pixel landed, and weights each by its distance from the pixel's centre (`temporal_reconstruct`). The pixel's own sample flips between the two sides of every edge the jitter crosses; the weighted estimate moves little as the offset changes. Every pixel's history records how many renders it holds (a third history target, which also carries the spread below). This render's estimate takes its share as one sample among them, so a history a few renders long settles in as many renders as it holds, from a cut, from a disocclusion and from a camera stop alike. How many a history may hold depends on whether its surface moves: - **Still** (its surface moved under a quarter of a pixel since the previous render): `stillSamples` of them, several whole passes through the jitter sequence, so the accumulation settles on the average of the renders the sequence draws instead of rippling as the samples visit the pixel. - **Moving**: as many as `historyWeight` keeps, fewer as `motionRejection` shortens the memory for fast motion; twice that where the history passes the clip untouched (it then differs from the estimate only by where the jitter put it), and the weight's own count where the clip moved it, so real change is followed. A still pixel also carries how far the jitter moves its estimates: their variance about the history, kept over about one pass through the jitter sequence. An edge thinner than the 3x3 samples, a blade of grass or a frond seen from a distance, drops out of some renders' neighbourhood altogether, so the box those samples span says nothing of it and the clip would pull the history to whichever side the jitter landed on. An estimate within two standard deviations of that spread is the jitter, and the history stands unclipped; one past three is a change, and the clip follows it. The spread is trusted once it has seen two passes through the sequence, and a pixel that moves or is disoccluded starts it over. ## Sharpening the shown picture `sharpness` runs `rcas`, a contrast-adaptive sharpening of the picture after the display transform, in the display stage. It reads what the accumulation produced and writes only what is shown, so it is applied once per frame and never compounds through the history. Its lobe is limited per pixel and its result held inside the range the pixel and its four neighbours span, so an edge gets steeper without a bright halo along a dark line or a dark one along a bright line. ## Velocity and the offset The offset is folded into the projection, so it would otherwise show up in velocity as a sub-pixel wobble on a scene that is not moving. The engine publishes the offset alongside the matrix and the vertex stage subtracts it back out, so `@scene.motion` describes the surfaces and a still scene reports no motion however the samples are placed. ## What the passes after it read The resolved picture samples every pixel at its centre; the raster under it sampled this render's offset. An effect after the resolve that draws from the scene's depth (an outline found where the depth steps, a pattern laid on the surfaces through the world position the depth reconstructs) would draw from the raster and move by up to half a pixel on every frame of a still view, over a picture that holds still. So the resolve is followed by two passes in the same stage. `stable_depth` keeps, for every pixel, the depth sample taken nearest the pixel centre for as long as no surface around the pixel moves and the sample still lies among the depths its neighbourhood holds; over one pass through the offsets a still pixel settles on one sample and keeps it. A fragment pass whose output is `@scene.depth` (`restates = true`) then restates the frame's depth from it: every pass after it reads that depth through `@scene.depth`, the post framework's `scene_depth` and `zero::scene_depth`, and reads the camera with no sub-pixel offset through `@frame.camera` and `engine.view_proj` / `engine.inv_view_proj`. Those two passes name `@scene.depth` and the kept depth in `whenRead`: on a frame where nothing after them reads the depth (a pass binding `@scene.depth` or drawing with a shader that samples it, or an effect of the post-process chain that samples it) they are left out, and the first render that has such a reader again starts the kept depth over from its own. A third pass, whose output is `@frame.camera` (`restates = true`), restates the camera on every frame, so a pass after the resolve that reads the camera and no depth reads it with no sub-pixel offset as well. A pass ahead of them reads the raster's own depth, which every render lays again before its first phase, and keeps neither. On the deferred path `stable_surface` keeps the G-buffer normal and material of the same sample, and two more passes restate `@scene.normal` and `@scene.material` from them, so the passes after the resolve that read the G-buffer (the rest of the `afterLighting` phase) see the surface the restated depth describes. Those three passes name the two channels in `whenRead`: on a frame where no pass reads what they leave in `@scene.normal` or `@scene.material` (a pass after them, or one ahead of the shading reading the G-buffer the previous frame left, such as screen-space reflections) they are left out, and the first render that has such a reader again starts the kept surface over from its own. Lines and patterns an effect draws there hold still on a still view and move with the surfaces on a moving one. A pass ahead of the resolve (occlusion, reflections, fog, depth of field) reads the raster's own depth and surface, which describe the same scene, and `__renderpass.schedule()` reports no such read. ## Every view keeps its own result A frame draws several views: the viewport, every render-to-texture camera, every capture. Each runs this pass against its own picture, at its own size, so each keeps its own running result. The result lives in a history target (`renderer.texture.create { history = true }`), which holds one pair of images per view: for the length of a view's render the pass resolves into the target's `guid` and reads `previous`, the image that view's previous render resolved. A minimap or a capture drawn beside the viewport neither reads the viewport's result nor disturbs it. Each view also walks the sample sequence on its own count of renders. Its first render, and its first after a cut, samples the pixel centre and starts the result from that render alone, which is all a one-shot capture ever draws. The colour images are `rgba16f`, so an accumulated highlight brighter than white keeps its value instead of clipping on the way through. The distance images are `r32f`, the temporal images `rgba16f` (how many renders each pixel's history holds and the spread of its estimates), and the stable depth images `rgba32f` (the kept depth and how far from the pixel centre it was sampled). ## Parameters `taa_params` carries the tuning and `rcas_params` the sharpness, both written by `@builtin::systems.antiAliasing.temporalAntiAliasing`. `taa_state` is the history target's state, written by the engine before each render of a view: whether `previous` holds that view's previous result, how many renders in a row have carried it, and the render's sub-pixel offset. A render with no result to carry begins from its own sample.
▲ 0↑ born
·
renderfeature · born here
❒asset
# contactShadows The render passes behind the `ContactShadows` component and the module. Its settings (`strength`, `length`, `steps`, `bias`, `thickness`, `followSun`, `lightDirection`, `localLights`, `maxTracedLights`) are its fields, so it can stand as a placed member with every value stated. The sun, at the depth seam before anything shades: a jittered depth-buffer march from each surface toward the sun, its normal read off the depth, writes the share of the sun's light it finds taken; a depth-aware blur smooths it; a fragment pass composes it into the scene's sun occlusion channel (`@scene.sunOcclusion`) with the `union` blend. The sun's term alone takes it, so the sky, the probes, the emissive surfaces and the other lights keep their light, and it stands with a participating medium's share as `a + b - ab`. With `localLights`, after lighting: a march toward each of the `maxTracedLights` point, spot and distant lights putting the most light on the pixel, each result weighted by the share of the pixel's light that light supplied, then a depth-aware blur that composites the result scaled by how lit the pixel already is, so contact shadows and shadow-map shadows do not stack. Those lights arrive through `contact_lights`, packed by the module once a frame, so the traces follow lights that move. The forward view-projection is the frame's own, so captures and RTT cameras project through their own matrix.
▲ 0↑ born
·
renderfeature · born here
❒asset
# exposure The render feature behind `AutoExposure` and `@builtin::systems.exposure.exposure`. Two compute passes run in the `meter` stage, on the picture the temporal resolve reconstructed: | local order | pass | output | |---|---|---| | 0 | `exposure_meter` | 32x32 grid of tile log-luminances, weighted by the metering mask | | 2 | `exposure_adapt` | the live exposure, moved toward the scene's reading | ## Metering `exposure_meter` gives each tile a slice of the frame and averages the log-luminance across it, sampling every fourth pixel in each axis — a tile covers hundreds of pixels and the result is an average, so sampling all of them buys precision the eye cannot see at sixteen times the cost. Averaging happens in **log** space. The eye's response is logarithmic and so is the quantity being averaged, which is why a few very dark pixels do not drag the whole frame's exposure up the way a linear average would. The metering mask weights that average. Full metering reads everything; centre-weighted tapers to a floor at the frame edge; spot reads only the middle. ## Adaptation `exposure_adapt` runs as a single invocation, so there is one writer to the state buffer and no ordering to arrange between workgroups. It reduces the tile grid, works out the exposure that would land the average on `targetGrey`, and moves the live value toward it. The approach is exponential in `dt`, so the rate is independent of frame rate. Rising and falling use different speeds on purpose: the eye adjusts to brightness far faster than it adjusts to darkness. The live exposure lives in the `exposure_state` buffer, written by the GPU and read back the next frame — that persistence across frames is the whole mechanism behind an image that settles rather than snaps. The buffer starts zeroed, and a zero in its "initialised" slot tells the first frame to settle on its reading immediately instead of adapting up from an exposure the scene never had. `exposure_state[0]` is `(currentEV, initialised, targetEV, compensation)`, and `exposure_adapt` also writes the live and target stops to its single-texel output. ## Reaching the picture `exposure.module` reads `exposure_state` back to the CPU each `tick`, adds `compensation` (already held there) to the adapted stop, and writes `exp2(adapted + compensation)` to the chain's display pass as `__display__`'s `exposure` property — the one place in the frame a stop turns into a change on screen. Parameters arrive through the `exposure_params` buffer, packed by `@builtin::systems.exposure.exposure`, which also supplies the frame's `dt`.
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
◇
component · born here
❒asset
# Model Loads and displays a 3D mesh on an entity. Disabling the component hides the mesh. Supports procedural meshes (`cube`, `sphere`, ...), model files, and remote URLs. Tint and outline are shader effects applied to the mesh. **Material lives on this component.** There is no standalone `Material` component — a material only renders where there is a mesh to render it on, so the `material` field is part of Model (and SkinnedModel). Set it at add time or assign the field later; properties are registry-wide. Public fields: `model`, `material` (`AssetRef<material>`), `tintR/G/B`, `tintBlend`, `outlineR/G/B`, `outlineIntensity`, `outlineOccluded` (`"hide"`, the default, hides the rim where geometry stands in front of the mesh; `"dashed"` draws it there in dashes, the `occluded` choice of `@builtin::modules.outline`). Methods: `:setTint(color, blend?)` (color: `{r, g, b}` array or `{r=, g=, b=}` map), `:clearTint()`, `:setOutline(color, intensity?)`, `:clearOutline()`, `:setMaterialProperty(prop, value)`, `:getMaterialProperty(prop)`, `:getMaterialPropertyNames()`. ```luau entity(id).component.add("Model", { model = "cube", material = "gold" }) entity(id).component.get("Model").material = "checkerboard" -- swap material entity(id).component.get("Model"):setTint({1, 0, 0}, 0.5) entity(id).component.get("Model"):setMaterialProperty("roughness", 0.2) ``` **Tint is synced.** Every `tint*` field replicates, so `:setTint` is the colour every participant sees. A colour that changes every frame on many entities (a stress map, a heat map, a damage flash, per instance colour) belongs in an instance-data lane instead: wear `@builtin::materials.instance_color` (or `instance_color_unlit`) and write `renderer.instanceData.set(id, 2, r, g, b, coverage)`, which replicates nothing and costs about a twentieth of a tint write. `guides { path = "topics/rendering-instance-data" }` has the lane layout.
▲ 0↑ born
◐
material · born here
❒asset
# Emissive White A bright white light-emitting PBR surface built on the `pbr` shader with the `_EMISSION` keyword enabled. A white base colour (`1.0, 1.0, 1.0`) paired with a strong `emissive` (`20.0`) makes it glow and drive bloom — well suited to light fixtures, emitters, and glowing accents. Non-metallic (`metallic 0.0`) at mid roughness (`0.5`). ## Inputs - `floats.emissive` (`20.0`) — high emission strength that produces the glow. - `keywords: _EMISSION` — enables the emissive path in the PBR shader. - `colors.base_color` — the white surface and emission colour. - `floats.roughness` (`0.5`) — diffuse spread on the lit surface.
▲ 0↑ born
◇
component · born here
❒asset
# Light Adds a light source to an entity. The entity's world transform determines the light's position, and a spot's aim: the cone axis is the entity's world rotation applied to `face`. A directional or distant light travels along `direction`. Point light positions are auto-synced from that world transform, so a light on a child entity burns where the entity stands — the position `entity.position` reports. A point light's `intensity` is on one scale with the `SpotLight` component's `intensity`/`brightness`: the same number at the same `radius`/`range` puts the same light on a surface either kind faces from the same place, and a spot spends it on the cone it opens on rather than all around itself. Distances are in metres and a point or spot light falls off by the inverse-square law: a surface facing the light 1 m away takes `intensity`, one at `d` metres takes `intensity / d^2`, so the same light gives 4 times as much at 0.5 m and a quarter as much at 2 m, and `radius` windows it smoothly to zero at the light's reach. Kinds: `"point"`, `"spot"`, `"directional"` (the scene's sun), `"ambient"`, `"distant"` (a parallel light beside the sun). Public fields: `kind`, `colorR/G/B`, `intensity`, `radius`, `directionX/Y/Z`, `face`, `angle`, `innerAngle`, `castsShadows`, `angularDiameter` (the disc size, in degrees, that sets how wide the sun's shadow penumbra grows with the distance from caster to receiver; 0.53 is the sun's and 0 draws a hard edge), `lightChannels`, `mobility`. `range`, `color` and `direction` are aliases accepting the composite/renamed forms. Methods: `:setColor(color)` (color: `{r, g, b}` array or `{r=, g=, b=}` map), `:setIntensity(i)`, `:setRadius(r)`, `:setDirection(dir)`, `:setFace(face)`, `:setAngle(deg)`, `:setInnerAngle(deg)`, `:setKind(lightKind)`. `kind = "spot"` opens a cone from the entity's position along its `face` (`"Front"` by default: the entity-local -Z that `transform.forward` reports and `entity:lookAt` aims; also `Back`, `Left`, `Right`, `Top`, `Bottom`), to the `angle` (outer, default 30) and `innerAngle` (inner, default 20) half-angles in degrees. These are the `SpotLight` component's fields, under the same names and with the same meanings. A spot aims by `face` and its entity's rotation, so a `direction` written to one is refused: `:setDirection` raises, an assigned `direction` keeps the value it held, and both name `face`. `"directional"` and `"distant"` are parallel lights: they arrive from the same direction at every point in the world and no distance attenuates them, so their `intensity` reads against the sun's rather than against a point light's. The `SpotLight` README carries the rest of how to balance a mixed point-and-spot rig. ```luau entity(id).component.add("Light", { kind = "point", intensity = 2, radius = 10 }) entity(id).component.add("Light", { kind = "directional", direction = {-0.5, -1, -0.3} }) entity(id).component.add("Light", { kind = "spot", face = "Bottom", angle = 35, innerAngle = 25 }) ```
▲ 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
❒
bundle · born here
❒asset
# lamp_post (bundle) A lamp post: a slim post, a lit head sitting on top of it, and the point light it casts. Four entities under one root — `post`, `head` and `glow` — built from builtin meshes and materials, so the bundle carries no geometry of its own. Its foot sits at `y = 0` and it stands 2.53 units tall, so placing it at a position on the ground puts it on the ground. ```lua asset.resolve("@builtin::bundles.lamp_post", "bundle"):instantiate(nil, { position = { 4, 0, 2 }, rotation = { 0, 30, 0 }, scale = 1.2, }) ``` ## What it is for It is the prop a starting scene places to show what placing an asset does: one call brings a whole hierarchy in as the scene's own entities, and the `Light` riding along shows that a bundle carries behaviour and not only shape. Reach for it whenever a scene needs a light source that reads as an object rather than as a floating value.
▲ 0↑ born
◇
component · born here
❒asset
# BoxCollider (component) A box collision shape. Works with or without a `Physics` component: on its own it is static collision geometry, and alongside one it moves with the body. ## Sizing `half` is the box's half-extents in the entity's local space, multiplied by the entity's world scale. Leave it unset and the box derives from the entity's model bounds, so a bare `BoxCollider` matches what is rendered at any scale, and follows the mesh when `renderer.mesh.setVertices` or `renderer.mesh.update` changes it: by the next physics step the box takes the new geometry's size and centre. ```lua entity.find("crate").component.add("BoxCollider", {}) -- fits the mesh entity.find("wall").component.add("BoxCollider", { half = { 2, 4, 0.2 } }) -- authored ``` ## Fields | Field | Meaning | |-------|---------| | `half` | Half-extents. Unset derives from model bounds. | | `isTrigger` | Report overlaps without blocking. | | `friction` | Surface friction. | | `restitution` | Bounciness. | | `rollingResistance` | How strongly the surface resists a body rolling on it: a rolling body slows at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81). 0 rolls on. | | `spinningResistance` | The same for a body spinning on the surface about the contact normal. 0 spins on. | | `surface` | The surface the collider is made of, by name: one `Physics.defineSurface` defined gives it its friction, restitution and resistances in place of the fields above, and contacts, contact events and ray and shape casts report the name either way. Empty names none. | | `oneWay` | The direction, in the collider's own frame, bodies pass through it along: a body moving that way goes through, and a body meeting it from the side the direction points to stands on it (a jump-through platform is `{0, 1, 0}`). `Physics.passThrough(entity)` drops a standing body through. Unset blocks from every side. | | `surfaceVelocity` | The velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put: friction carries what rests on it (a conveyor belt, a treadmill, an escalator). Write it at runtime to change the speed or direction. Unset holds the surface still. | | `contactTag` | The tag the world's contact filter reads this collider by: `Physics.setContactFilter(tagA, tagB, mode)` makes two tags pass through each other (`"ignore"`), report contacts and push nothing (`"sensor"`) or collide (`"solid"`). Empty names none. | ## Composing A collider on a child entity attaches to the nearest ancestor carrying a `Physics` component, so a body made of several shapes puts each on its own entity and each keeps its own material and trigger flag. Past a few dozen boxes sharing one material, `CompoundCollider` is cheaper: it is a single broadphase volume where separate components are one each.
▲ 0↑ born
·
procgraph · born here
❒asset
# ModelGraph The graph a scene's parts are drawn by. The nouns record a scene's tree; at the end of the build one `Generator` is spawned on this graph, and the tree is its two plain inputs: - `objects`: the objects of the tree, parents before their children. Each is `{ name, parent, pose or channel and values, components?, leaves }`: `parent` is the number of its parent object (0 for the first), `pose` is its position, rotation quaternion and scale as ten numbers (an object that stands still), `channel` and `values` name a formula of `channels` and the constants it puts in it (an object whose pose follows the clock), and each leaf is `{ shape, material, matrix }`: `shape` is `{ op, args, ops? }`, where `op` names a `g.shape` node, `args` are its inputs and `ops` are the modifiers applied in order (bevel, subdivide, taper, twist, bend, boolean), `material` is `{ color, metallic, roughness, emissive, opacity?, doubleSided? }` and `matrix` places the leaf in its object (row-major 4x4). A shape whose `op` is `loft` carries its cross-sections in `args.sections`. - `channels`: the formulas of the poses that follow the clock, each `{ nodes, out, width }`. The graph composes the tree into the parts that stay where they are, each an entity with its parent and local pose, and the parts that move, grouped by formula and shape and drawn as instances, one population per group, the formula running on the device every frame. A graph that states a program (`g:program`) is stood by that program where it takes the tree, and cooked as this graph where it does not. The graph's clock runs forward and loops. A material is one node per distinct colour, metalness, roughness, emissive, opacity and sidedness, shared by the parts that state it. Opacity below 1 or a double-sided material is made from the pbr shader with a transparent blend. Modifiers run through procgen's own nodes: `geometry.bevel`, `geometry.subdivide` (points joined first), `geometry.boolean` and `geometry.loft`; taper, twist and bend are field arithmetic on the point positions.
▲ 0↑ born
◇
component · born here
❒asset
# Generator A live procedural generator: it binds a `.procGraph`, plays the graph's timeline and stands each of the graph's outputs in the scene as children of the entity it is on. Change a param and the output is made again in place; in edit and in play alike, nothing it makes is written to the world's source. ```lua local graph = asset.create("procGraph", "crate") -- a box with a `size` input; edit its init.luau local e = entity.spawn("crate") e.component.add("Generator", { graph = graph }) e.component.get("Generator").params = { size = 2 } ``` ## Fields | Field | What it does | |---|---| | `graph` | The `.procGraph` it plays. | | `params` | Overrides for the graph's declared inputs, by name. | | `output` | One declared output to stand; empty, the default, stands every output, one root each. | | `playOn` | What starts its clock in play mode: `"auto"` (default) plays a timeline with no end as soon as it binds and holds any other on its first frame; `"load"` plays on bind; `"manual"` waits for `play()`. In edit mode a Generator is not set to play, whatever `playOn` says: it shows the frame it is on until it is played. | | `ending` | `"graph"` (default) does what the timeline declares; `"loop"` plays the range round and round; `"hold"` plays it once and stays on its last frame. | | `speed` | How fast its clock runs: 1 its own rate, 0 still, negative plays a timeline with an end backwards. | | `diskCache` | Whether the outputs the graph caches load from, and are written to, the world's disk cache. On by default. | | `cookBudgetMs` | Milliseconds of cook work a frame before a cook yields to the next frame. 5 by default. | ## Methods `play()`, `pause()`, `seek(seconds)`, `seekFrame(frame)`, `loop()`, `hold()`, `setFps(fps)`, `setRange(first, last)` and `setWallTime(on)` drive its clock, on every peer. `getFrame()`, `getTime()`, `describeGraph()` and `playback()` read it; `playback()` also says what running the graph costs and how each output is drawn. `cancelCook()` stops a cook in flight and leaves the last output standing. `apply()` swaps the generator for the asset it makes: the frame being presented becomes a bundle, and an `Asset` component standing it takes the Generator's place. The `onFinished` event fires when a range played once reaches its end. A timeline that runs in real time (`realTime = true`) has an end when its graph states `frames` beside it (`g:timeline({ realTime = true, fps = 60, frames = 180 })`) or when `setRange` gives it one; with neither it runs on and never finishes. When the playhead of one with an end reaches its last frame, `ending` applies as it does to any timeline: `"graph"` loops where the graph declares `loop` and otherwise holds on the last frame and fires `onFinished` once; `"loop"` plays it again from the start, a fresh simulation each time, without firing it; `"hold"` stays on the last frame. `play()` plays a held one again from its start. `playback().ends` is whether the timeline has an end, and `last` is its last frame. A real-time timeline begins again, by `seek(0)`, a loop or `play()`, in the runs its solvers hold on the device: a restart costs a rewrite like any other present, and opens no cook. ## Under an effect An effect's play runs each graph of its entry on a Generator, a child of the play's entity. `effectRef:play(entry, opts)` and the `Effect` component make them and drive their clocks together, so a shot, an impact or a cast is a play of an effect (`guides { path = "systems/effects/documentation/visual-effects" }`). The play's own `playback()` adds its Generators' costs together. Every play of one graph with the same params plays the frames the first one cooked. A Generator of a graph with `playOn = "manual"` cooks every frame of the timeline while it waits, and `playback().cookedThrough` reaching `playback().last` says every frame is cooked. ## Related - `guides { path = "systems/procgen/documentation/procgen" }`: graphs, ops, timelines, effects and the live generator in full. - The `procgen` toolbox: `spawn`, `adjust`, `apply`, `generators`, `cooks`, `frames` and `onPresent` work on generators by entity, and `play` plays a graph on the preview stage.
▲ 0↑ born
◇
component · born here
❒asset
# SceneSetup The per-instance state of a placed scene setup. A setup's `instantiate` adds it to the placed root beside the `Asset` component whose `source` is the setup. It holds this placement's `overrides`, by parameter path, and applies the setup with them; the setup's members are applications of their assets, so the scene records the root, its `Asset` and these overrides alone. ```luau local setup = entity(root).component.get("SceneSetup") setup:members() -- { [path]: { source, state } }, every depth setup:get("fog/density") -- { value, origin, definedBy?, desc } setup:set("fog/density", 0.05) -- this placement's override setup:set("ao/@enabled", false) -- turns a member off here setup:reset("fog/density") -- back to what the setup says setup:orphans() -- overrides that address nothing ``` It applies the setup when it wakes and when it is enabled, applies a change of `overrides`, turns the setup off when it is disabled and drops it when it is removed; removing the `Asset` removes it. While it is disabled, a change of its overrides applies the setup off. Across an edit/play flip the setup stays applied: the instance that ends hands its application to the one that wakes on the same root, so no frame is drawn without its sky, sun or fog. It runs nothing per frame. A system API's write of a parameter this placement states (`fog.set`) becomes this placement's override. Its application is one of the scene's applications: the effects that hold one at a time (the sun, the ambient term, the sky, each render feature's settings) go to the newest application standing. Another setup applied from code (`setupRef:as("applicable"):apply(owner)`) holds them over this placement until it is dropped, across flips, and its drop hands them back to this placement. `audition(setup)` shows another setup in this placement's place as a preview for the session; `endAudition()`, a flip or a reload ends it.
▲ 0↑ born
◇
component · born here
❒asset
# Asset Promote the bundle's spawned children from temporary to permanent scene state and remove the Asset component, "baking" the bundle's contents directly into the owning scene. Subsequent saves persist the baked entities verbatim and stop replaying the bundle template. Location: `src/lua/lib/components/Asset.component`
▲ 0↑ born
▣
module · born here
❒asset
# scene runtime What a `.scene` folder does when it is loaded, saved, built, or swapped. A `<name>.scene/` carries `scene.json` (the entity arrangement), an optional `build.luau` (the code author's half), an optional `entrypoint.luau`, and a `scene_dirty/` overlay of unsaved edits. Reading, composing and writing all four is the scene type's own behaviour, so it lives in the type. ## Sub-modules | Module | Responsibility | |---|---| | `loader.module` | Reads scene.json v6 and v7, refuses versions it does not know, composes canonical + dirty overlay, spawns the entities, and runs the entrypoint. | | `saver.module` | Persists scene state as a delta overlay against the canonical file, promotes that overlay on save, and answers which edits are still pending. | | `build.module` | Runs a `build.luau` inside an entity capture scope and composes what it spawned into scene records. | | `observe.module` | The read side — the per-scene counts and costs `layers` and `loader` write. | | `swapOrchestrator.module` | Drives multiplayer room transitions and the scene-swap gate, so a local swap does not leak despawns to peers in the old room. | ## Reaching it ```luau local rt = require("@builtin::assetTypes.scene.shared") rt.saver.hasPendingSceneEdits(layers.active.name) ``` Fields resolve lazily. The prelude installs `swapOrchestrator` and starts `saver`'s dirty writer in a fixed order, which a table that required all five on load would take away from 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
# 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/sceneLighting.package

Problems

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

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

Usability ratings

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

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

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

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