# geometry.bevel
Round the sharp edges of a mesh. Every selected edge is replaced by a strip of `segments` quads that follows a circular arc tangent to both faces; the faces are trimmed back from the edge to make room, and what is left open where several bevelled edges meet is closed with a patch.
The mesh is triangulated and welded (`core.weld`, a merged point standing where its lowest-numbered point stood) at a millionth of the length of its longest side. Then:
1. An edge is selected when exactly two faces meet along it and they turn by more than `angle` (the least that counts is a ten-thousandth of a radian), narrowed to the edges whose two ends are in `group`. Selecting no edge is refused, naming the sharpest turn the mesh has.
2. One width serves the whole mesh: a face trimmed back by `w` from each of its bevelled sides keeps an area while the sum of `w` over the altitudes to those sides stays under 1, so the narrowest face sets the limit. `maxWidth` is 0.999 of it; a `width` past it is clamped to it, or refused when `overflow` is "error".
3. Every corner of every triangle is pulled in to where the offset lines of its bevelled sides meet: along the side before it by the offset of the side after it, and along the side after it by the offset of the side before it, each over the sine of the corner's angle.
4. Where a face's corner stopped short of its neighbour's along an unbevelled edge, the neighbour's side takes the farther corner as a point, and a face that took a point is a fan of triangles around the middle of its ring of points, so the two faces meet along the whole edge.
5. At each end of a bevelled edge the strip runs along a circle of radius `width` times the cotangent of half the turn between the faces, tangent to both, from the first face's corner to the second's (`segments - 1` points between them), and is cut into triangles wound the way the two faces are.
6. The openings left where strips meet are found as the loops of open edges of the welded faces and strips (`core.boundary`); a loop of three edges closes with the one triangle its points make and a longer one with a triangle on each of its edges to a point at the middle of the loop.
The trimmed faces keep three points of their own each, on the normal of the face they came from. The strips and patches share the points they meet at. `shading` "flat" gives every bevel triangle points of its own on its face's normal; "smooth" shades the bevel as one surface; "auto" is flat at one segment and smooth above.
## Inputs
- `geometry` (Surface). The surface whose edges are rounded.
- `width` (Number, default 0.05). How far the bevel reaches onto each face. Above 0.
- `segments` (Number, default 1). Quads across a bevelled edge; 1 is a flat chamfer.
- `angle` (Number, default 30). The turn, in degrees, past which an edge is bevelled.
- `group`, `class`, `promote`, `threshold`. The part of the surface whose edges are bevelled: an attribute on `class` ("edge", "point", "primitive" or "vertex") past `threshold`, taken to the points of an edge by `promote` ("all" or "any").
- `overflow` ("clamp" or "error", default "clamp"). What a `width` past the widest the mesh admits does.
- `shading` ("auto", "flat" or "smooth", default "auto").
## Outputs
- `geometry` (Geometry). The surface with its edges bevelled.
- `info` (Data). `bevelledEdges`, `pairedEdges` (the edges with two faces), `cornerPatches`, `width` (used), `requestedWidth`, `maxWidth`, `clamped`, `segments`, `vertexCount` and `triangleCount`.
# geometry.blank
A column of one zero word, for a binding a stage of a kernel declares and does not read. A dispatch binds each buffer at one slot only, so a binding with nothing to read takes a column of its own, and every call makes one.
## Inputs
None.
## Outputs
- `words` (Column<Int>). One element, 0.
# geometry.boolean
Combine two closed meshes into one closed surface: "union" keeps everything either encloses, "intersect" only what both enclose and "subtract" what `a` encloses and `b` does not.
Each input is triangulated and welded (`core.weld`, each merged point standing where its lowest-numbered point stood), then held to what a solid is, and refused by name when it is not: an input with fewer than four triangles, one carrying degenerate triangles (collapsed by the weld, or enclosing less area than `weld` squared), one that is not closed (an edge used by one triangle), not manifold (an edge shared by more than two), wound inconsistently (two triangles run an edge the same way), enclosing no volume, or wound inside-out (negative signed volume). The two are then cut against each other with the `intersect` kernels, which cut the curve where the surfaces cross and the regions where they coincide:
1. The bounding volume hierarchy of `b` (`geometry.bvh`), then `intersect_pairs` (a count stage, a prefix sum, a write stage) lists the entries of the cut, three words each (`a`, `b`, part), ordered by the triangle of `a`.
2. `intersect_cuts` writes the segment each entry is cut along; `intersect_unify` gives every endpoint that names the same crossing one identity, so the pieces of `a` and of `b` share their cut points. A cut point's position comes from the record that names it: the plane crossing of an edge and a triangle, the crossing of two coplanar edges, or a mesh point.
3. `intersect_retri` retriangulates every triangle an entry reaches (`side` 0 for `a`, with the entries as they stand; `side` 1 for `b`, with the entries sorted by their triangle of `b`).
4. Each piece is classified by the winding number of the other mesh just outside and just inside its centre (`ray`, winding); the kernels' README holds the table of what each operation keeps, which also settles the faces the two meshes share.
5. The kept pieces are joined and welded. A triangle the weld leaves with two corners at one point encloses nothing and is dropped, and so are two triangles that stand on the same three points: where the cut runs straight across a corner within the weld distance of the line between its neighbours, each mesh keeps the sliver beside that line, and the two slivers face opposite ways over one another. The triangles are put in the order of their sorted corners (`sort` three times, by the highest, the middle and the lowest corner) so that triangles on the same points stand next to each other.
6. The surface is refused when it has no triangle (the result is empty) or when it does not close (an edge used by one triangle, by more than two, or run the same way by both), and otherwise every face is given three points of its own and its own normal, so a shaded read of the result agrees with its winding.
Two meshes that never cross skip the cutting and are classified whole.
## Inputs
- `a` (Surface). The first closed mesh.
- `b` (Surface). The second closed mesh.
- `op` ("union", "subtract" or "intersect"). Which part of each cut surface survives; swapping `a` and `b` changes the result of a subtract. There is no default: a missing `op` is refused.
- `weld` (Number, default 0). The distance below which two positions are one point while the inputs are cleaned and the pieces reassembled. 0 derives it as a hundred-thousandth of the diagonal of the smaller of the two inputs, since a mesh's coordinate precision scales with its size. May not exceed `epsilon`.
- `epsilon` (Number, default 0). The thickness of a plane: how far either side of a piece the other solid is probed is at least this. 0 derives it as the weld distance. At least `weld`.
## Outputs
- `geometry` (Geometry). The combined surface: triangles of three points each, with a flat normal on every face.
- `report` (Data). The `operation`, the `weld` and `epsilon` the run used, the result's `pointCount` and `triangleCount` (the points and triangles of `geometry`, three points a face), and the volumes enclosed by the two inputs (`volumeA`, `volumeB`) and by the result (`volume`), summed on the device in single precision. It is measured only when asked for.
# geometry.extrude
Push faces out along their own normals or along a vector, walling the gap they leave into a closed solid: the selected faces move, a copy of them left behind closes the volume (when `cap` is on), and each border edge of the selection grows a side wall of two triangles. Every emitted face is wound toward the side it faces, so a negative distance gives the mirrored solid with its normals still outward. The faces outside the group stay where they are. The result is shaded with point normals and numbered by `id`.
## Inputs
- `geometry` (Surface). The surface whose faces are pushed out.
- `distance` (Float, default 1). How far the selected faces travel. Negative travels the other way and still comes back as a solid facing outwards. 0 moves no face, and is refused.
- `offset` (Float, default 0). How far the surface the extrusion starts from stands from the input surface, along the direction of travel. 0 starts at the input surface.
- `direction` (String, default "normal", one of "normal", "vector"). What each point travels along. "normal" uses the surface normal at that point, averaged over the selected faces meeting there, so a curved selection fans out. "vector" moves every point along `vector`, so the selection travels rigidly.
- `vector` (Vec3, default (0, 1, 0)). The direction of travel when `direction` is "vector". Used as given, so its length multiplies `distance`; a vector of (0, 0, 0) moves no face, and is refused.
- `group` (String, default ""). Names a 0/1 attribute on `class` holding the faces to push; left empty, every face is pushed. A group holding no face is refused.
- `class` (String, default "primitive", one of "point", "primitive", "vertex"). The class `group` lives on. A "primitive" group is read once per face; a "point" or "vertex" group selects a face only when every one of its corners is above `threshold` (`geometry.selected`).
- `threshold` (Float, default 0.5). The value a `group` element must exceed to count as a member.
- `cap` (Bool, default true). true leaves a copy of the selected faces behind, wound the other way, so the volume is closed at both ends. false leaves that end open.
- `epsilon` (Float, default 0.00001, above 0). Points this close together are treated as one while border edges are paired and normals averaged, which lets a triangle soup extrude as the connected surface it looks like.
## Outputs
- `geometry` (Geometry). The extruded surface.
```luau
local slab = g.geometry.extrude({ geometry = g.mesh.grid({ size = { x = 2, z = 2 } }), distance = 0.25 })
```
# geometry.first
Read the first element of a column back from the device as a Number, for a count the rest of the graph sizes its work by: the total of a prefix sum, or the index a reduction picked. The cook waits for the device to answer.
## Inputs
- `value` (Column). The column read. Only its first element is answered.
## Outputs
- `value` (Number). The first element.
# geometry.following
Read a column of a closed run one place on: element i of the answer is element i + 1 of the column, and the last element reads the first. The next point round a ring, for each point of it.
## Inputs
- `values` (Column or Field). The values read, the elements of one closed run in order.
- `count` (Number). How many elements the run holds.
## Outputs
- `values` (Column). The column shifted back one place, wrapping at the end.
# geometry.kept
The places of a run that a mask keeps, in order, the number of them as a Number, and for every place how many kept places stand before it.
Built from `core.points` and `core.attribute.write` (the mask as a column of 0 and 1), `geometry.offsets` (the prefix sum of those flags), `geometry.first` (the total read back as a Number) and `core.scatter` (each kept place sends its own number to the slot its rank names).
## Inputs
- `mask` (Column or Field). A place is kept where the value is not 0.
- `count` (Number). How many places the run holds.
## Outputs
- `indices` (Column<Int>). The kept places in order, `total` of them.
- `total` (Number). How many places are kept.
- `before` (Column<Int>). For each place, how many kept places stand before it: a kept place's rank among the kept places.
# geometry.offsets
Turn a count per element into the place each element's run starts: the exclusive prefix sum of the counts, and the sum of them all.
## Inputs
- `counts` (Column<Int>). How many slots each element takes.
## Outputs
- `offsets` (Column<Int>). For each element, the sum of the counts before it.
- `total` (Column<Int>). A one-element column holding the sum of every count.
# geometry.perpendicular
A unit vector perpendicular to a unit vector, per element, found against the world axis the vector leans on least so the result stays well conditioned.
## Inputs
- `vector` (Vec3). The unit vector the answer is square to: one value, or one per element of a column.
## Outputs
- `perpendicular` (Vec3). A unit vector with a zero dot product against `vector`.
# geometry.ribbon
A flat ribbon along every curve of a geometry, `width` across, lying square to `up`, or turned to face `toward` a point: a crack glowing in the ground, a trail, a beam, a road. Each curve vertex gives two points, one each side; both carry every attribute of the curve point they were laid from and `s`, its distance along the curve, with `N` the ribbon's facing, `uv.x` running 0 to 1 along the curve by distance and `uv.y` 0 or 1 across it. Each segment is two triangles carrying the primitive attributes of its curve (apart from `curve`, `closed` and `length`). A curve running along `up` turns the ribbon to the world axis square to `up` (+Z, or +X for an `up` along Z). The result is numbered by `id`.
## Inputs
- `curve` (Curves). The curves to lay ribbons along. Every curve of it gets one; its faces are left out. A geometry holding no curves is refused.
- `width` (Float, default 0.1, at least 0). How wide the ribbon is.
- `taper` (Float, default 0, 0 to 1). How much narrower each ribbon ends than it starts: 0 keeps the width all the way, 1 closes it to a point at the end.
- `widthBy` (String, default "width"). A Float attribute of the curve points the width is multiplied by at each point, when the points carry it. An empty name reads none.
- `up` (Vec3, default (0, 1, 0)). The direction the ribbon lies square to: its width spreads across the curve and across `up`, so the default lays it flat on level ground.
- `toward` (Field<Vec3> or Vec3, optional). A point the flat side of the ribbon turns to, in place of `up`: a Vec3 faces every point to one place (a camera's position); a Field states the place for each point.
- `lift` (Float, default 0). How far along `up` the ribbon is raised off its curve.
## Outputs
- `geometry` (Geometry). The ribbon triangles.
```luau
local road = g.geometry.ribbon({ curve = g.curve.line({ finish = vector.create(4, 0, 0), segments = 8 }), width = 0.5, lift = 0.01 })
```
# geometry.rings
Make the points a surface built ring by ring stands on: `rings` rings of `size` points each, ring after ring. Answers the points, the ring each point belongs to and its place along that ring, so a node writes each point's position as a formula over the two numbers.
## Inputs
- `rings` (Number, at least 1). How many rings there are: a Number, or a live count.
- `size` (Number, at least 1). How many points each ring holds.
## Outputs
- `surface` (Geometry). `rings * size` points and no primitives.
- `ring` (Column<Int>). The ring each point belongs to, from 0.
- `along` (Column<Int>). The place of each point along its ring, from 0.
# geometry.rotate
Turn a Vec3 by Euler angles in degrees, applied about X, then Y, then Z (R = Rz * Ry * Rx), per element.
## Inputs
- `vector` (Vec3). The vector turned: one value, or one per element of a column.
- `rotate` (Vec3, default zero). Degrees about X, Y and Z.
## Outputs
- `vector` (Vec3). The turned vector.
# geometry.solidify
Give a surface thickness: a front shell and a back shell, `thickness` apart along the normals, the back one wound the other way, with every border edge bridged, so an open surface comes back closed. It is `geometry.extrude` of the whole surface (or the faces of `group`) with `cap` on, started from where the back shell sits.
## Inputs
- `geometry` (Surface). The surface given a thickness.
- `thickness` (Float, default 0.1, above 0). The distance between the two shells. A thickness of 0 or less is refused.
- `direction` (String, default "inward", one of "both", "inward", "outward"). Where the material sits: "inward" leaves the front shell on the surface and drops the back one `thickness` against the normals; "outward" leaves the back shell on the surface and raises the front one `thickness` along them; "both" straddles the surface with half the thickness each way.
- `group` (String, default ""). Names a 0/1 attribute on `class` holding the faces to thicken; left empty, the whole surface is thickened. The faces outside it stay in place as a single sheet.
- `class` (String, default "primitive", one of "point", "primitive", "vertex"). The class `group` lives on. A "primitive" group is read once per face; a "point" or "vertex" group selects a face only when every one of its corners is above `threshold`.
- `threshold` (Float, default 0.5). The value a `group` element must exceed to count as a member.
- `epsilon` (Float, default 0.00001, above 0). Points this close together are treated as one while border edges are paired and normals averaged, which lets a triangle soup thicken as the connected surface it looks like.
## Outputs
- `geometry` (Geometry). The closed solid.
```luau
local panel = g.geometry.solidify({ geometry = g.mesh.grid({ size = { x = 2, z = 1 } }), thickness = 0.05, direction = "both" })
```
# geometry.split
The x, y and z components of a Vec3, per element: one value, or one per element of a column.
## Inputs
- `vector` (Vec3). The vector split: one value, or one per element of a column.
## Outputs
- `x`, `y`, `z` (Float). The components, each the dot product of the vector with its axis.
# geometry.subdivide
Split every triangle into four, `levels` times: each side gets a midpoint shared by the triangles on either side of it. "linear" puts the midpoints on the sides and keeps the shape; "loop" moves every point by Loop's rules (the even points toward their neighbours, the new points toward the opposite corners), which rounds the surface, and rebuilds the normals. `P`, `N` and `uv` average across a side; every other point attribute takes the value of the side's first end. Primitive attributes repeat on the four children and vertex attributes follow the corner each child corner stands at. Two sides are one side when they join the same two points, so faces that share points are smoothed as one surface; faces that stand at one place with points of their own are separate pieces, and `geometry.weld` first joins them. The input is read as triangles.
## Inputs
- `geometry` (Surface). The surface subdivided. A geometry holding no primitives is refused.
- `levels` (Float, default 1, 0 to 8). How many times every triangle is split: each level multiplies the triangle count by four.
- `mode` (String, default "linear", one of "linear", "loop"). "linear" places each new point at the middle of its side. "loop" smooths by Loop's weights.
- `max_vertices` (Float, default 250000, at least 4). The most points a level may produce. A level that would pass it is refused, naming the count it would have allocated.
## Outputs
- `geometry` (Geometry). The subdivided surface, numbered by `id`.
```luau
local smooth = g.geometry.subdivide({ geometry = g.geometry.weld({ geometry = g.mesh.box({}) }).geometry, levels = 2, mode = "loop" })
```
# geometry.transport
Carry a vector along as the unit direction `from` turns onto the unit direction `onto`: rotated about their common perpendicular by the angle between them, and made square to `onto` again. Frames carried this way along a curve stay free of twist.
## Inputs
- `vector` (Vec3). The Vec3 carried.
- `from` (Vec3). The unit direction before the turn.
- `onto` (Vec3). The unit direction after the turn.
## Outputs
- `vector` (Vec3). The carried unit vector, square to `onto`.
# geometry.trim
Drop every primitive that has no area: the triangles a pole or an apex leaves, whose corners stand at one place or on one line. What remains is a surface whose every side is shared by the faces that are really there.
## Inputs
- `geometry` (Geometry). The geometry trimmed.
- `least` (Number, default 1e-9). The area a primitive has to exceed to stay.
## Outputs
- `geometry` (Geometry). The geometry without the primitives of no area.
# geometry.unit
A Vec3 scaled to unit length, per element. A vector with no length answers `fallback`.
## Inputs
- `vector` (Vec3). The vector scaled: one value, or one per element of a column.
- `fallback` (Vec3, default (0, 1, 0)). The unit vector a zero-length `vector` becomes.
## Outputs
- `unit` (Vec3). The unit vector.
# Nodebox (asset type)
A nodebox is a namespace folder that groups related `.procNode/` children, the way a toolbox groups
`.tool/` children. A node's name is its folder name inside its box: `points.nodebox/disc.procNode` is
called `points.disc`, and nothing inside the node states that name. Moving or renaming a node is a VFS
move that keeps its guid.
## Where it lives
- Source: `<anywhere>/<family>.nodebox/`, usually inside a `.package`, an effect or a world's content.
- Identity: the folders above it and `<family>` (`fx.points` for `fx/points.nodebox`; the `.nodebox`
suffix strips). A graph calls its nodes by `<family>.<node>` alone.
- Folder shape (open child set):
- `README.md`: what the family is for. Required.
- `.metadata`: description and tags. Required. It also states where the box's nodes work: `context` (one of
`proc.registry.contexts()`: `geometry`, `field`, `value`, `sim`, `raster`, `material`, `prefab`) and, when every
node of the box reads the scene or assets beside its inputs or writes them beside its outputs, `pulls` /
`pushes` (`scene` or `asset`). A node that works elsewhere states its own in its `.metadata`.
`procgen` `describeNode` and the `context`, `pulls` and `pushes` filters of `searchNodes` read them.
- `<node>.procNode/`: any number of nodes.
## How a graph reaches a node
`g.<family>.<node>(args)` resolves the node by its asset identity: the box and the folder name together
(`g.points.disc`), a path (`g["/zero/source/fx/ring.procNode"]`), `~` (the nearest enclosing package,
effect or world root: `g["~/ring"]`) or a short name the asset system resolves (`g.disc`). A name that
matches two nodes is an error naming both; a name that matches none is an error naming the closest nodes.
Each call is recorded in the graph's reference table by the node's guid.
## How to create one
```luau
asset.create("nodebox", "points", { folder = "fx" })
local box = asset.resolve("points.nodebox")
asset.create("procNode", "disc", { into = box })
```
## Discovery
- `asset.list("nodebox")`: every box.
- `asset.inspect("points")`: the nodes in it and what each does.
- `asset.list("procNode")`: every node, in or out of a box.
## In the Inspector
Nodes: how many nodes the box holds, each node's full name and what it does, and a link to each.
# procNode: one reusable step of procedural generation
A `.procNode` is a node authored as content: a folder whose `init.luau` is the node. It
returns `proc.define(function(g) ... end)`, the same function-of-`g` form a `.procGraph` is
written in, so a node is a small graph that other graphs call. Its `g:describe` text says
what it makes and when to use it, its `g:input` declarations are what a call passes, and
what it returns (or declares with `g:output`) is what the call gives back.
```
MyNode.procNode/
init.luau -- the node
README.md -- what it produces, its inputs, its outputs
.metadata -- description and tags
```
## What a node states
- **`g:describe(text)`**: what the node produces and when to use it. It is the text search,
the node catalogue and the Inspector show.
- **`g:input(name, default, opts)`**: one input of the node. The default types it (`Float`,
`String`, `Bool`, `Vec3`, `Color`, `List<T>`, `Record`); `opts` adds `type` (for a default
that does not state one, or none), `description`, `options`, `min`, `max` and `optional`. A
call names inputs in a table, or passes them in declaration order.
- **Outputs**: the returned table names them (`return { geometry = geometry }`), and
`g:output(name, value)` declares one as the node builds. A node with one output answers
that value to its caller; a node with several answers a record by output name; a node with
none answers nothing.
- **Written as literals.** What a node takes and gives is read from its source without running
it, the way search and description read it here and the way ZeroMind reads it, so each
declaration states its values as written: `g:describe` and each `g:input` once, at the top
level of the function, with a literal name, default and options (a file constant holding a
literal, or `asset.resolve("<identity>", "<type>")`, reads as one); outputs named by the table
the function returns, or by `g:output`, the same names on every branch of a condition and never
inside a loop. `asset.interface(node)` answers what the source declares, with each part it
cannot read as a problem, and a push refuses a node with such a problem
(`interface.unreadable`).
- **The body** is the node's work: calls to other nodes, arithmetic over sockets, `for`, folds,
steps and state, as the builder README (`proc.module/builder.module/README.md`) describes.
A node that uses another node is recorded in the graph that calls it, so a node can be built
from nodes.
## How a graph calls a node
A node inside a `<family>.nodebox` is called by its box and folder name:
`points.nodebox/disc.procNode` is `g.points.disc({ ... })`, and nothing inside the node states
that name. A node is also reached by:
- its path (`g["/zero/source/fx/ring.procNode"]`),
- `~`, the nearest enclosing package, effect or world root (`g["~/ring"]`),
- its guid,
- a short name only one node answers to (`g.disc`).
A name that matches two nodes and a name that matches none are errors that name the
candidates. Each call is recorded in the calling graph by the node's guid, so the node travels
with every graph that uses it, and a rename or a move keeps the reference. A `.procGraph` is
called the same way and answers what it returns.
## Nodeboxes
A nodebox is the family a node lives in: a namespace folder grouping related nodes (`points`,
`mesh`, `field`, `terrain`). `nodebox.assetType` describes it. A node placed in a box takes the
box's name as its prefix; a node outside any box is reached by path, `~` or guid.
`asset.create("nodebox", family)` makes a box and `asset.create("procNode", name, { into = box })`
makes a node in it.
## Finding nodes
`asset.list("procNode")` lists every node. The `procgen` toolbox's `searchNodes` finds them by
meaning across every published node, and with no query lists the ones this engine holds grouped
by family; its `describeNode` answers one node's inputs, their types and defaults, and its
outputs. Both read what each node's source declares and run no node. The type's `indexing`
recipe embeds a node's README and its source, so a search by meaning finds a node by what its
description and README say it is for: write them in the words someone looking for the node
would use.
## Registration
Every node the asset index lists is known to the procgen registry by what its source declares,
read when it is asked for and read again when the source changes; nothing runs a node to list
it. Its code loads the first time a build runs it. After that, the lifecycle hooks keep it
current: `onChange` loads it again and hot-reloads on an edit, `onDelete` removes it. Editing
`init.luau` cooks again every graph that reaches the node, and only the nodes downstream of the
change do work. `init.luau` is compiled from its current source on each load, so a module it
pulls in uses an absolute require
(`require("@builtin::systems.procgen.proc")`).
What a node is built from is more than its own file. A module its `init.luau` requires while it
builds, at any depth of requires, is part of it: when that module changes, `onDependencyChange`
loads the node again from the module as it now stands. A file its `init.luau` reads with
`vfs.read` while it builds is part of it too, and so is a file a module it calls reads with
`proc.read` (a module's own `vfs.read` is its own and makes no dependency). Writing such a file
loads the node again (`proc.sourceChanged`). Either way the node's definition moves, so every
graph and Generator reaching it cooks again, from one version of everything it was built from.
`proc.builder.readsOf("<node>.procNode/init.luau")` lists the files its last build read. A graph that references a node which is not
registered errors at load, naming the missing guid. A graph that reaches itself, directly or
through other nodes, errors at cook.
## Content requirements
`README.md` carries real text: what the node produces, its inputs and its outputs. `.metadata`
carries a `description` (what the node computes and the value type it answers) and `tags` (the
family, so search finds it). It may state where the node works: `context`, `pulls` and `pushes`
(the values `proc.registry.contexts()`, `"scene"` and `"asset"` name). A node in a nodebox that
states none takes its box's; `procgen` `describeNode` and `searchNodes` answer them.
A node written with `proc.graph` and `g:node` (the `procNodes/` of the procgen package) is called only
by a `proc.graph` graph, through `g:node`. A graph built with `proc.define` does not call it: `g.op.<name>`
of it is refused where it is written, naming the node written in the call form that answers to the same name.
## In the Inspector
Operation: the node's id and what it does, its cost and caching when it declares them, and its
inputs and outputs, from the procgen registry's schema for it. A node that did not register says
so.
# 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.
·computeshader · born here
❒asset # gather
Builds a column from another column and a run of indices: element `i` of the
result is element `index[i]` of `src`. An index below 0 or past the end of
`src` gives zeros. The element type is the `T` specialization (`f32`, `i32`,
and two to four lanes of either); a three-lane column is read and written
tightly packed, twelve bytes an element.
Dispatch over `n`, the number of indices. Exact: each result element has one
writer. It declares `fusion:` (the value of element `i` is `element(i)`, a thread
runs where `skip(i)` is false), so a chain of fused kernels evaluates it inside
one dispatch.
Most nodes that reorder, select or copy elements read their columns through it:
`core.select`, `core.concat`, `core.make`, `core.weld`, `attribute.gather`,
`attribute.promote`, `elements.sort` and the geometry nodes among them.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` slots are live: a slot at or past it holds zeros. It binds 4
storage buffers (3 in the plain variant), and `dst` holds `n` elements.
# math.dot (procNode)
The dot product of two vectors: a number per element.
The `dot` operation of the authoring surface, called through the Luau node on `proc.fieldc.operators`. Operands are numbers, vectors, Columns or Fields. When every operand is a plain number or vector the answer is the plain result, folded where the node cooks; otherwise the answer is a Field: a template over its operands that whatever reads it evaluates in one dispatch together with the chain around it. Nothing dispatches for this node alone.
# field.index
The element number, counted from 0. Unwired it is an Int field over whatever reads it (`fieldc.leaves.elementId`: the number of the element being written). With a `domain` it is an Int column of 0 to n - 1, one per element of the domain.
# math.cos (procNode)
The cosine of an angle in radians, element by element.
The `cos` operation of the authoring surface, called through the Luau node on `proc.fieldc.operators`. Operands are numbers, vectors, Columns or Fields. When every operand is a plain number or vector the answer is the plain result, folded where the node cooks; otherwise the answer is a Field: a template over its operands that whatever reads it evaluates in one dispatch together with the chain around it. Nothing dispatches for this node alone.
# core.select (procNode)
Keep the elements of a geometry a mask picks and drop the rest, renumbering the links between points, vertices and primitives.
Built from `math.ne` over the mask, `compact` (the kept elements and the inverse map), `core.owner`, `gather`, a segmented `reduce` (`segments = primitive.count`), `scatter`, `attribute.carry` for every class and `scan` for the new run starts. Keeping points drops every primitive that loses a vertex; keeping primitives keeps their vertices and, by default, the points those vertices read; `points` set to "all" keeps every point.
## Inputs
- `geometry` (Geometry). The geometry to filter.
- `class` (one of point, primitive). Default `"point"`. Which elements the mask is over.
- `points` (one of used, all). Default `"used"`. For class "primitive": which points stay, the points the kept primitives use or every point.
- `mask` (Value). Default `1`. A column or field over the class's elements: an element is kept where the value is not 0.
## Outputs
- `geometry`: the kept elements with the links renumbered.