# asset_change_dispatch (module)
Installs `_G.__zero_dispatch_asset_change`, the Luau half of the
asset-type **change-callback** system. The engine calls it once per VFS
source write (via `zero_scripting::ffi_callbacks::fire_asset_change_dispatch`,
queued as `VfsMutation::AssetSourceWritten`).
## What it does
1. Receives the written VFS path.
2. Walks up the path to the enclosing `<name>.<type>/` typed-asset folder
(deepest registered-type suffix wins, so the direct owner of the write
is chosen for nested typed assets).
3. Loads that type's `<type>.assetType/behavior.luau` via
`@builtin::assetTypes.assetType.shared.ref.loadTypeModule`.
4. If the module exports an `onChange` function, calls
`onChange(ref, change)` where `ref` is the typed `AssetRef` for the
changed asset and `change = { path, asset, type }`.
This is the type-level analogue of the component-centric
`onAssetReload(field)` fan-out: components react to assets they
*reference*; an asset *type* reacts to writes inside its own *instances*.
## Re-entrancy
A best-effort synchronous guard suppresses dispatch for an asset while its
own `onChange` is running, so a handler that writes back inline doesn't
recurse immediately. It does **not** span asynchronous work — writes
queued during a synchronous `onChange` are processed on a later drain.
`onChange` handlers must therefore be **convergent**: diff the meaningful
state before acting and short-circuit when there's nothing to do (the
`dynamicAsset` example only regenerates when the prompt actually changed
and bails while a generation is in flight). Idempotency is the contract,
exactly as it is for services' `start`/`stop`.
## Related
- `@builtin::assetTypes.assetType.shared.ref` — owns `loadTypeModule` + the per-type `ref` method
dispatch.
- `assetTypes/assetType.assetType/template/behavior.luau` — the documented
template that shows how to author `ref`, `global`, and `onChange`.
- `assetTypes/dynamicAsset.assetType` — the reference type that uses
`onChange` for prompt-driven regeneration with version control.
# asset_create
`asset.create` — the single, generic "instance a new asset of an existing type"
API. The same entry point scripts and agents use; there is deliberately no tool
wrapper, because agents author in Luau and call `asset.create(...)` directly.
```lua
local inst = asset.create("material", "my_metal", { base_color = { 0.8, 0.7, 0.2 } })
-- → AssetRef: inst.path == "/zero/source/my_metal.material", inst.guid, plus the
-- material type's ref methods.
```
`asset.create` makes a new *instance of an already-registered type* by running
that type's `onCreate(name, opts)` behaviour hook (declared in its
`behavior.luau`) and writing the produced files to
`/zero/source/<name>.<typeName>/` — the one authored location, in every mode.
While play runs, the play-mode write lock takes that write onto the **play
shadow**: live in the session, disk source untouched, listed by
`vfs.playShadowPaths()`, and promoted or discarded on a guarded play-exit. The
asset created in play therefore carries the same identity, path and `require`
spelling it has in edit, and the session decides whether it stays.
A create whose output the world **reproduces** on every load — one made from a
component or a scene entrypoint — writes to the copy-on-write runtime store at
`/zero/runtime/assets/<identity>.<typeName>/` instead, so the code that rebuilds
it each load is its only source and the saved manifest never carries a second
copy.
## Placement
Four `opts` keys are consumed by the framework before the type's `onCreate`
hook runs, and steer where the instance lands:
| Key | Effect |
|-----|--------|
| `folder` | A relative subfolder under the source root: `/zero/source/<folder>/<name>.<typeName>/`. Groups a generator's output instead of accumulating it at the source root. |
| `into` | A resolved container ref (`.toolbox` / `.package`) to author INSIDE — lands at `<container>/<name>.<typeName>/` and registers as a member. Edit-mode only. |
| `dest` | An absolute destination path, owned by the caller (an importer building a `<name>.bundle/`). |
| `overwrite` | Re-author an existing destination in place, keeping its `.meta` guid so every reference stays valid. |
The `name` is always the asset's bare identity — the path goes in `folder`:
```lua
local rock = asset.create("mesh", "rock", { positions = p, indices = i, folder = "terrain/props" })
-- → rock.path == "/zero/source/terrain/props/rock.mesh"
```
`dest` and `into` both take precedence over `folder`. `folder` decides the
asset's identity, so it applies in every context: the runtime store is flat and
spells that identity in one folder name.
```lua
-- the same call from a component's awake()
-- → rock.path == "/zero/runtime/assets/terrain.props.rock.mesh"
-- → rock.identity == "terrain.props.rock", as it is from an execute
```
Types without an `onCreate` hook fall back to cloning their verbatim
`template/` skeleton to the same destination, so `create` works for every type.
Returns the created asset's `AssetRef` (`.path` / `.guid` plus the type's ref
methods — the same interned instance `asset.resolve` returns) on success and
raises (via `error`) on bad arguments or a failing `onCreate`.
Installed onto the FFI `asset` namespace by the prelude (`M.installInto(asset)`).
See `docs/specs/runtime-asset-copying.md`.
# asset_events
Per-asset runtime for declared asset events. An assetType's `behavior.luau`
declares an `events` schema the same way a component declares one; this
module turns that schema into the live objects an asset's ref fires and
listens on.
## Three faces, one Signal — keyed by the asset
The construction is `component_events`': one `Signal` per declared event,
reachable through a private fire-capable table, an owner-side emitter the
type's own behavior fires with, and a subscribe-only facade every other
holder of the ref sees. The facade exposes `connect` / `once` / `wait` and
has no `fire` at any key, so firing authority stays with the type.
What differs is the owner. A component event belongs to one instance on one
entity; an asset event belongs to the **asset**, so the runtime is keyed by
the asset's stable guid. Every resolver of that guid subscribes to the same
Signals, and a ref that is reclaimed and re-resolved re-attaches to the
subscriptions already there — the same reason `asset_ref`'s `runtime` table
is guid-keyed rather than stored on the envelope.
Both tables reject an undeclared event name: the private table's metatable
raises on a bad key and the facade raises on a bad key, so a typo surfaces
at the subscribe call instead of returning nil.
## Declaring events on a type
```lua
-- <name>.assetType/behavior.luau
local M = {}
M.events = {
changed = { payload = { value = Field.number(0, NoSync) } },
}
M.ref = {
poke = function(self)
local emitter = require("@builtin::assetTypes.assetType.shared.events").emitter(self.guid)
if emitter ~= nil then emitter.changed:fire({ value = 1 }) end
end,
}
return M
```
```lua
-- any holder of the ref
local ref = asset.resolve("@builtin::…")
ref.events.changed:connect(function(p) print(p.value) end)
```
## Exports
- `M.forAsset(guid, eventSchema)` — the runtime for one guid, built on first
use and reused after. A later call with a different schema reconciles:
surviving events keep their Signal and their subscribers, new events get a
fresh one, removed events are disconnected and dropped.
- `M.facade(guid)` — the subscribe-only view, or nil before a runtime exists.
- `M.emitter(guid)` — the owner-side `:fire` view, or nil before a runtime
exists.
- `M.has(guid)` — whether a guid holds a live runtime.
- `M.teardown(guid)` — drop one asset's runtime, disconnecting subscribers.
- `M.teardownAll()` — drop every runtime. Called on an engine mode flip so a
play-mode subscription does not survive into edit.
- `M.liveGuids()` — every guid holding a runtime, sorted.
## Notes
- Subscriptions made through the facade are ordinary `signal.module`
connections and disconnect the same way any other does.
- The runtimes table is held strongly, and its lifetime is bounded by the
mode flip that clears it.
# scene_instantiable (module)
The instantiation contract's shared implementation. An asset type opts into
scene instantiation by defining `instantiate(self, target?, opts?)` on its
behaviour `ref` table; this module carries the parts that mean the same thing
for every type, so a caller writes ONE piece of code against all of them.
```lua
local root, idMap = ref:instantiate(target?, opts?)
```
## The contract
**IN — the base opts.** `target` is an owning entity ref: the instance lands
under (or, for a hierarchy type like a bundle, onto) that owner. With no
target the type spawns a fresh root. `position`, `rotation`, `scale`, `name`
and `temporary` place that root and mean the same for every type. `rotation`
takes three numbers as pitch/yaw/roll in DEGREES, or four as a quaternion. A
type may honour more opts of its own — `params` for a type built from declared
inputs, `idMap` / `diff` / `sourceTag` for the bundle override contract — and
says so in its own `instantiate` docs.
**OUT — the two returned values.** Every type returns the same pair:
- **`root`** — the composed root, as an `EntityRef`. Composition is
**synchronous**: the root and everything the type built under it are live
the moment the call returns, so a caller can parent to it, read its
components and hand it on in the same statement. There is no frame to wait
for and no callback.
- **`idMap`** — the `originalId -> runtimeId` map naming what the composition
spawned, `{}` for a type with no addressable children. **Never nil.** A
component that re-composes the asset on every load (`Asset`) keeps this map
and passes it back in, which is how a cross-entity reference into the
composition — `SkinnedModel.skeletonRoot` pointing at a bone — survives a
reload.
The return is enforced, not merely described: `AssetRef` dispatches every
`ref:instantiate(...)` through `result` on the way out, whether or not the
type called it. A type that returns something else fails at its own call
rather than handing its caller a nil root or a map that is sometimes absent.
## Exports
- `M.root(self, target?, opts?) -> root` — stand the root entity for a type
that spawns one: parented to `target`, born temporary when
`opts.temporary`, named `opts.name` else the asset's own name, placed.
- `M.place(root, opts?) -> root` — apply the placement opts to a root the type
already has (the adopt path: a bundle exploding onto its target, a
sceneModule reconciling under one).
- `M.result(self, root, idMap?) -> (root, idMap)` — return through the
contract. Checks `root` is a live entity ref, normalises a missing map to
`{}`, and errors naming the asset type when either is something else.
- `M.isOwned(opts?) -> boolean` — whether a component drives this call. The
`Asset` / `SceneModule` components tag their own calls with `sourceTag`;
they hold the reference and re-compose on every load. An untagged call came
straight from `ref:instantiate(...)` and has no such owner.
- `M.own(root, self, idMap?) -> root` — hand an already-composed root to an
`Asset` component pointing at `self`, so the reference and its map persist
and the composition is rebuilt on the next load. The component adopts the
live composition rather than building a second one.
- `M.check(value, constraint) -> ok, reason?` — the `sceneInstantiable`
field-constraint validator, also registered under that kind on load.
## The field constraint
`Field.instantiableRef` emits `constraint = { kind = "sceneInstantiable" }`,
and this module registers the validator for it on load. Given a written value:
1. `nil` passes — the field is optional (no asset assigned).
2. Reads the value's identity — a bare string, or a table's `__ref` / `guid` /
`identity` / `name`.
3. Resolves it (`asset.resolve(identity)` — any category) and asks the
resolved ref `ref:canInstantiate()`: true iff the asset's type defines an
`instantiate` method.
This is what lets `Field.instantiableRef` accept by CAPABILITY rather than a
hardcoded type list — a new scene-instantiable asset type is accepted the
moment it defines the hook, with no edit to the field or its consumers.
# asset_on_register
Drives the optional `onRegister(self)` assetType lifecycle hook — the surface that lets an asset instance run code exactly once when it first registers, operating on the per-instance ref (`self`). This is what makes "write an asset into the world → it takes effect live, no restart" work for content that registers into a runtime registry (editor panels, and anything else that opts in).
A type opts in by exporting `onRegister` from its `behavior.luau`. The hook fires exactly once per instance:
- On `engine.onWorldLoaded` — a batched sweep over every world instance of every type that implements `onRegister`, yielding every 32 instances so a large instance count never stalls a frame. The @builtin library (`/zero/source/libs/`) is excluded.
- On live `asset.create` — the create path calls `M.fireFor(ref)` on the freshly-created instance.
A per-VM once-guard keyed by the instance's VFS path ensures the two triggers can't double-register the same instance.
## Exports
- `M.fireFor(ref, onRegisterFn?) -> boolean` — fire one instance's `onRegister(self)` hook exactly once. Resolves the type's hook from `ref.type` when `onRegisterFn` isn't supplied. Idempotent: a second call on the same instance is a no-op. Returns true if the hook fired this call.
- `M.sweep()` — batched sweep: fire `onRegister` once for every world instance of every registered type that implements it. Yields, so it must run inside a task. Safe to call repeatedly.
- `M.install()` — install the world-loaded sweep. Idempotent. Runs the sweep on a system task so it ticks through pause and never blocks the caller.
# assetType.shared.ref
Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries. Replaces the per-call C metatable that used to live in `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable`.
## Public API
```lua
local assetRef = require("@builtin::assetTypes.assetType.shared.ref")
-- Called by the Rust factory (push_asset_ref_handle) via
-- _G.__build_asset_ref_proxy after the envelope fields are set.
assetRef.build(envelope) -- attaches AssetRefMT, returns the table
```
The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below).
## Method dispatch order
`ref.foo` is resolved in this order:
1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (engine contract from gh#1889).
2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods.
3. **Nil** — unknown key, same shape as the original C metatable.
## Adding methods for a new asset type
Drop a `behavior.luau` into the type folder:
```
src/lua/lib/assetTypes/<typename>.assetType/
├── type.yaml -- structural spec (existing)
├── behavior.luau -- ref + global behaviour (new)
└── template/ -- placeholder body (existing)
```
`behavior.luau` returns:
```lua
return {
ref = {
--!desc Per-instance method on every `<typename>` AssetRef.
myMethod = function(self, ...) ... end,
},
global = {
-- Reserved for the asset.<typename>.* surface — not consumed
-- yet; included so the contract from gh#1889 lands cleanly.
},
}
```
Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined.
## Discovery and hot-reload
Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half.
Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call.
The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods.
## Why Luau, not Rust
The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means:
- Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code.
- Adding a new asset type drops in a new folder; no Rust rebuild.
- Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives.
## Consumers
- `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable` — the Rust factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push.
- Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.
# asset_ref_shapes
Publishes what every `AssetRef<category>` answers to, so a member read on an
asset-typed value is checked against the category's own surface.
An asset category's per-instance surface is authored: a
`<name>.assetType/behavior.luau` declares `M.ref = { ... }`, and each category
declares its own. The members an `AssetRef<inputMap>` carries are therefore
knowable only to `inputMap` itself — no fixed set of types covers the ones a
world defines, and the checker has no way to guess them.
This module reads each registered category's `M.ref` table from its source
(never executing it), renders it as a Luau table type, and hands the set to
the engine. From there a `ref:method(...)` on an asset-typed value resolves
against the category's real surface: a name it does not carry is reported
along with the ones it does.
## Results shaped by the asset
Some results are shaped by the asset rather than by its category —
`inputMapRef:activate()` answers one handle per binding THAT map declares, a
set that is authored and differs per map. A category states those by
declaring `refShapes`, and this module asks it once per instance and
publishes the answers keyed by asset identity. `types/assetType` documents
the authoring side.
## When it publishes
Publishing is driven by use: every entry point that produces diagnostics
calls `ensure`, which is a no-op once the set is current. A world load, a
write inside a type definition, and a write inside any asset whose container
computes shapes each mark it stale, so the cost lands on the next check and
only if one comes.
The sweep is complete and replaces what was published before, so a category
whose type is removed stops being published.
## Reading what the checker believes
From a call site, a type that is correct and one that was never published are
the same absence of a diagnostic. `published()` tells them apart:
```lua
local shapes = require("@builtin::assetTypes.assetType.shared.refShapes").published()
shapes.categories.inputMap
--> "{ activate: () -> any, controls: () -> { any }, ... }"
shapes.returns["@builtin::inputMaps.default"].activate
--> "{ crouch: Handle, interact: Handle, jump: Handle, ... }"
```
# validate
Pure validator for `asset.create` opts — checks a creation `opts` table against the schema produced by `asset.createSchema(typeName)`. Schema in, validated opts (or a teaching error string) out. Consumed by `asset.create`, which calls `M.validate` before forwarding opts to the type's `onCreate`. No FFI, no VFS.
Errors are teaching errors: they state what was wrong at which path (`opts.cfg.size`), what was expected, and then render the full creation-parameter contract so the caller can fix the call without reading the type's `behavior.luau`. Unknown parameter names get an edit-distance "did you mean" suggestion.
## Types
- `ValidatorShape` — `{ kind, literals?, item?, members?, fields?, indexer? }`, the recursive shape encoding.
- `ValidatorParam` — `{ name, shape?, optional?, default?, desc? }`.
- `ValidatorSchema` — `{ kind, desc?, example?, open?, error?, params?, indexer? }`.
## Exports
- `M.validate(schema, opts?) -> (validatedOpts?, err?)` — validate and default-fill an `opts` table against an `asset.createSchema` result. Returns `(validatedOpts, nil)` on success (a new table for `schema`-kind schemas) or `(nil, err)` where `err` is a bare teaching error string. The caller owns presentation. Handles the `legacy`, `error`, `none`, and `schema` schema kinds.
- `M.shapeName(shape) -> string` — render a single parameter shape (literal unions as `"png" | "jpg"`, arrays as `{ T }`, tables as `table`, primitives as their kind, nil/malformed as `any`). Used by `asset.describe`.
- `M.renderContract(schema) -> string` — render a schema's creation-parameter contract as one aligned line per parameter, with an `[extra keys]` line for open schemas.
## Usage
```luau
local V = require("@builtin::modules.api.engine.asset.create.validate")
local out, err = V.validate(schema, { bytes = png })
if err then error("asset.create: " .. err) end
```