# Node reference

Generated from the node registry metadata (`listNodeTypes()`) by `node scripts/gen-node-reference.mjs` — do not edit by hand. The same metadata, machine-readable, is in [nodes.json](./nodes.json). For the graph JSON format and field-expression grammar see [authoring.md](./authoring.md).

80 node types, grouped by `category` (node sections below are alphabetical):

**attribute**

- [attributeReduce](#attributereduce) — Collapses a numeric attribute over a whole domain into a single value on the detail domain: sum, min, max, average (all f32, componentwise, keeping the source tuple size) or count (u32, the number of elements — this mode reads no attribute).
- [attributeRemap](#attributeremap) — Rescales a numeric attribute linearly from an input range to an output range, writing f32.
- [brickConnectivity](#brickconnectivity) — Reads BRICKS on a stud lattice — one per point, its box in two point attributes read through the point's transform (world = P + rot * (scale * corner)), as packBricks writes them: P the brick's centre, a quarter turn about y where it was placed turned, scale its extents, the unit box.
- [partitionByAttribute](#partitionbyattribute) — Splits the input into one point cloud per distinct value of an i32, u32, or string point attribute (tuple 1).
- [pathCoverage](#pathcoverage) — Measures, at every point of the `path` input, whether that point is COVERED from some direction by any of the oriented boxes in the `boxes` input, and writes the answer as point attributes: coveredAttr gets a bool (did at least minHits rays hit anything), hitsAttr gets the u32 count of rays that did.
- [pathRuns](#pathruns) — Writes a SEGMENTED running total of a numeric point attribute along every polyline: like pathScan, except the accumulator RESETS at points a boolean attribute flags, and on a closed path a run may cross the seam.
- [pathScan](#pathscan) — Writes a RUNNING FOLD of a numeric point attribute along every polyline, in the path's own walk order — by default a prefix SUM, the accumulating counterpart to attributeReduce's collapse, and under `reduce` a running minimum or maximum over that same walk instead.
- [pathShift](#pathshift) — Reads one or more of a path's OWN point attributes from the point `offset` positions further along the polyline's walk order, and writes each into a column of its own — LEAD AND LAG on a path.
- [pointNeighborhood](#pointneighborhood) — Measures each point's neighborhood inside the same cloud and writes the result as point attributes: countAttr receives how many other points lie within radius (u32), and averageAttr/averageOutAttr average a numeric point attribute over those neighbors (f32, same tuple size — averaging "P" gives each point the centroid of its neighbors, which is one Lloyd relaxation step away from even spacing).
- [promoteAttribute](#promoteattribute) — Moves an attribute between domains using the geometry's topology, creating or overwriting it on the target domain.
- [quotaRebalance](#quotarebalance) — Reads a CATEGORY per point and a stated SHARE BAND per category, and writes down the minimum set of points that must change category for every share to land inside its band — which category each should join, and nothing else.
- [removeAttribute](#removeattribute) — Deletes named attributes from one domain.
- [runFit](#runfit) — Cuts every polyline into RUNS at along-arc GAPS, least-squares fits a numeric point attribute against arc position WITHIN each run, and writes the fit back onto every point of the run it belongs to.
- [sampleNearestPoint](#samplenearestpoint) — For every point of `in`, finds the nearest point of the `source` cloud in 3D (positions from P, ties resolved toward the lowest source index) and records what it found on the output's point domain: distanceAttr gets the distance (f32), indexAttr the source point index (i32), and `attribute`/`outAttribute` copy one of the source's point attributes across.
- [setAttribute](#setattribute) — Creates or overwrites an attribute on the chosen domain.
- [transferAlongPath](#transferalongpath) — Reads a path's point attributes AT ARBITRARY ARC POSITIONS and writes them onto a second, independent point cloud — N stations against an M-point path, with N and M unrelated.
- [transferAttribute](#transferattribute) — Transfers an attribute from the `source` geometry onto the main input's points, creating or overwriting it on the output's point domain.
- [transferByIndex](#transferbyindex) — Reads the `source` geometry's point attributes AT A PER-POINT COMPUTED INDEX and writes them onto the main input's points, creating or overwriting them on the output's point domain.
- [writeCurveFrame](#writecurveframe) — Writes a full orthonormal frame — `tangent`, `curveNormal` and `curveBinormal` (f32 tuple 3) — at the points of every polyline primitive, keeping the points, their attributes and the topology exactly as they arrived.
- [writeTangents](#writetangents) — Writes a unit `tangent` (f32 tuple 3) onto the points of every polyline primitive, keeping the points, their attributes and the topology exactly as they arrived — the output is still a path.

**composite**

- [applyRules](#applyrules) — Composite node that runs a REWRITING GRAMMAR over labelled cells, one ROUND at a time: the recursion of a split grammar (a facade into floors, floors into panels, panels halved until they are small), in a graph that cannot wire a cycle.
- [forEach](#foreach) — Composite node that cooks an inner graph ONCE PER ELEMENT instead of once.
- [repeatUntil](#repeatuntil) — Composite node that cooks an inner graph REPEATEDLY, feeding each round's output back into its own input until the body stops changing anything — a bounded fixed point, in a graph where a cycle cannot be wired.
- [subgraph](#subgraph) — Composite node wrapping an inner graph as a single node.

**filter**

- [filterByAttribute](#filterbyattribute) — Keeps points whose named point attribute satisfies a comparison.
- [filterByBounds](#filterbybounds) — Keeps points by position against the axis-aligned box [boundsMin, boundsMax].
- [filterByDensity](#filterbydensity) — Filters points by their `density` point attribute (f32, tuple 1).
- [filterByExpression](#filterbyexpression) — Keeps points where a field-capable `predicate` evaluates to a non-zero number.
- [filterPrimitivesByAttribute](#filterprimitivesbyattribute) — Keeps WHOLE PRIMITIVES whose named PRIMITIVE attribute satisfies a comparison, and preserves topology: the survivors keep their vertices, their vertex and primitive attributes, and the points they share, so a network that goes in comes out a network.
- [filterPrimitivesByBounds](#filterprimitivesbybounds) — Keeps or drops WHOLE PRIMITIVES by testing their vertices against the axis-aligned box [boundsMin, boundsMax], and it is one of the two filters in this library that PRESERVE TOPOLOGY (filterPrimitivesByAttribute, which tests a value a primitive carries rather than where its vertices lie, is the other): the survivors keep their vertices, their vertex and primitive attributes, and the points they share, so a network that goes in comes out a network.
- [occlusionCull](#occlusioncull) — Removes points whose ORIENTED BOX stands in a line of sight, after first trying to move them out of it.
- [pathClip](#pathclip) — CUTS every polyline where `field` changes sign and keeps the pieces where it is >= 0, as polylines of their own — the path node that changes TOPOLOGY by value.
- [projectToPlane](#projecttoplane) — Projects every point orthogonally onto the plane through `origin` with normal `normal` (normalized internally).
- [selfPrune](#selfprune) — Enforces a minimum distance between points, under one of two rules chosen by `mode`.

**io**

- [dataInput](#datainput) — Emits exactly the data items in its `items` param, unchanged — the bridge for injecting externally produced data (for example parent-cell outputs in the hierarchical runtime) into a graph.

**point op**

- [boxContact](#boxcontact) — Asks, for every BOX on the `in` pin (the QUERIES), whether it meets any box on the `targets` pin, and writes the answer onto the query points as attributes: `hitAttr` a bool (any target met), `countAttr` an i32 (how many distinct targets), `targetAttr` an i32 (the index of the met target whose WORLD centre is nearest the world centre of the query box as tested, -1 for none).
- [connectByIndex](#connectbyindex) — Builds one 2-vertex `polyline` per point, from that point to the point its `index` names — the edge set a PARENT POINTER describes.
- [connectPoints](#connectpoints) — Connects a point cloud into a NETWORK: one 2-vertex `polyline` primitive per edge, built over the SAME points that arrived, so every point attribute survives and a junction is genuinely one point shared by every edge that meets there.
- [copyToPoints](#copytopoints) — Copies the source point cloud onto every target point (output count = source points * target points, grouped by target).
- [jitterPoints](#jitterpoints) — Offsets each point by a deterministic random vector: each axis moves by a uniform random in [-amount, +amount], hashed from (seed, point IDENTITY, axis).
- [mergePoints](#mergepoints) — Concatenates the points of every connected geometry, in connection order, into one point cloud.
- [mergePrimitives](#mergeprimitives) — Concatenates every connected geometry, in connection order, KEEPING TOPOLOGY: points, vertices and primitives are appended and each input's vertex and primitive references are renumbered onto its place in the result, so an authored network merged with a generated one comes out a single network.
- [offsetBox](#offsetbox) — MOVES THE FACES of every cell's box OUT, or IN where the offset is negative — the scope offset of a shape grammar, the padding of a bounding box, the inset/outset of a face extrude — and changes nothing else: same points, same order, same seeds, every attribute and the topology carried, only `boundsMin`/`boundsMax` rewritten.
- [orientAlongVector](#orientalongvector) — Sets the standard rot point attribute (f32 tuple 4 quaternion, [x, y, z, w]) so the chosen local axis points along `direction`, with `up` fixing the roll.
- [packBricks](#packbricks) — Reads axis-aligned BOXES on a stud lattice — one per point, its corners in two point attributes, an extent in the point's OWN frame as every box node reads boundsMin/boundsMax (world = P + rot * (scale * corner)); the lattice is axis-aligned, so a point must carry the identity rotation and scale [1, 1, 1], and one that does not is refused naming it — and writes the BRICKS that build them: one point per brick, from a stated catalogue of footprints, that together fill exactly the lattice cells the boxes cover.
- [pathPointAt](#pathpointat) — Moves every point of every polyline to the position at a given parameter ALONG ITS OWN polyline, and writes the unit `tangent` and `curveU` it finds there.
- [pivotBox](#pivotbox) — MOVES every cell's P TO A POINT OF ITS BOX and re-expresses the box about it, so THE BOX STAYS WHERE IT IS IN THE WORLD: the hand-off from a grammar's cells to instances.
- [placeBox](#placebox) — PLACES ONE BOX INSIDE, OR AGAINST, every cell's own box, by SIZE, ANCHOR and OFFSET on each axis, and writes it as the cell's new box: the scope operations of a shape grammar (size the scope, centre it, move it in its own frame) with a per-axis min / centre / max justify.
- [pointsToPath](#pointstopath) — Turns a point cloud into one or more paths by building `polyline` primitives over the SAME points, so every point attribute survives — this is the only way to produce a path from a serialized graph.
- [repeatPoints](#repeatpoints) — Emits every input point `count` times — a PER-POINT number of times when `count` is a field — and numbers the copies 0, 1, ..., count - 1 in `indexAttr`.
- [setBounds](#setbounds) — Sets the standard per-point bounds attributes: writes boundsMin and boundsMax (f32 tuple 3) on every point, creating the attributes when missing.
- [shellSplit](#shellsplit) — BREAKS every cell's box into its SHELL — floor, the four walls south / north / west / east, and ceiling — plus, if asked, the INTERIOR they enclose, and emits one point per piece, each piece a box with its OWN FRAME and a label: the component split of a split grammar, which turns a mass into the faces later rules decorate.
- [splitBox](#splitbox) — CUTS every cell's box along one axis into an ordered list of LABELLED PIECES and emits one point per piece — the split of a split grammar (a block into storeys, a wall into bays, a bay into jamb | opening | jamb).
- [transformBox](#transformbox) — SCALES every cell's box ABOUT A PIVOT and then MOVES it — the transform of a modelling package applied to geometry that is a box, and the way a set of boxes goes from one coordinate system to another: a lattice of whole studs and plates to units, an assembly centred on its lot, a piece shrunk about its own centre.
- [transformPoints](#transformpoints) — Transforms every point: P' = R * (scale * P) + translate, with R from rotateEuler (degrees, extrinsic XYZ order — world X applied first, then world Y, then world Z; equivalent to intrinsic ZYX, three.js Euler order 'ZYX').
- [voronoiCells](#voronoicells) — Turns a point cloud into its VORONOI DIAGRAM: one closed `polyline` primitive per site, bounding the ground that site is nearer to than any other.

**sampler**

- [arcTile](#arctile) — Lays a REPEATED PIECE over arc ranges of a path: one oriented instance point every `spacing` units between each range's start and end, ready for spawnInstances.
- [pathResample](#pathresample) — Resamples every polyline primitive at even arc-length steps and emits a PATH, not a cloud: the new points carry polyline topology, and a path that was closed comes back closed.
- [pathSegments](#pathsegments) — Emits ONE POINT PER SEGMENT of every polyline primitive, placed and oriented so that spawning a unit-sized asset on it draws the path as solid geometry.
- [pointScatterOnPath](#pointscatteronpath) — Scatters `count` points at UNIFORMLY RANDOM ARC POSITIONS along EVERY polyline primitive of the `path` input and emits them as a NEW point cloud lying exactly ON the path.
- [segmentCrossings](#segmentcrossings) — Emits ONE POINT PER CROSSING among the input's SEGMENTS — its 2-vertex primitives (whatever their primtype: connectPoints' edges, connectByIndex's bars, pathClip or pathResample output made of two-point pieces) — carrying the two primitive ids and the crossing's directions, as a plain point cloud (no topology).
- [splineSample](#splinesample) — Samples points along polyline primitives by arc length, treating all polylines of the input as one concatenated curve.
- [surfaceSample](#surfacesample) — Scatters points on a triangle mesh: each of `count` candidates picks a triangle with probability proportional to its area, then a uniform position on it (uniform barycentric placement).
- [volumeSample](#volumesample) — Fills an axis-aligned box with a regular grid of points: each axis is divided into floor(extent / cellSize) cells (at least 1) and a point is placed at each cell center, then jittered inside its cell.

**source**

- [meshFromField](#meshfromfield) — Turns a scalar FIELD into a triangle mesh: the surface where the field crosses `isoValue`.
- [meshPrimitive](#meshprimitive) — Builds a parametric triangle mesh with no input: shape 'plane' is one axis-aligned rectangle, shape 'box' is six of them around a volume, shape 'cylinder' is an upright (y-axis) cylinder with optional caps, and shape 'disc' is one flat polygonal disc lying like a plane.
- [pointGrid](#pointgrid) — Creates a regular grid of points: countX * countY * countZ points starting at origin, stepped by spacing per axis.
- [pointLine](#pointline) — Creates `count` evenly spaced points on a straight line.
- [pointList](#pointlist) — Creates one point per [x, y, z] triple in `positions`, in list order, and writes named per-point columns from literal values: a TABLE of points carried in the graph file itself.
- [pointScatterInBounds](#pointscatterinbounds) — Scatters `count` points uniformly inside the axis-aligned box [boundsMin, boundsMax].
- [pointScatterInWorld](#pointscatterinworld) — Scatters points over an INFINITE lattice anchored to world coordinates, then returns the ones inside the query window [boundsMin, boundsMax).

**spawn**

- [spawnInstances](#spawninstances) — Spawner terminal: converts the input point cloud into render-agnostic instance batches.

**surface**

- [boxesToMesh](#boxestomesh) — TURNS every cell's box into MESH FACES, built where the box is: the step from a grammar's cells (splitBox, shellSplit, placeBox, offsetBox, transformBox) to geometry a renderer draws.
- [bridgePaths](#bridgepaths) — Joins each polyline on `from` to one polyline on `to` with a strip of quads, point i to point i: segment i of the one path, segment i of the other and the two rungs between their ends make one quad, emitted as two 3-vertex 'poly' triangles (the mesh convention every consumer here reads — surfaceSample, the uv and raycast transfers).
- [extrudePolygon](#extrudepolygon) — Treats every CLOSED polyline primitive as a polygon boundary and sweeps it along a direction into 3-vertex 'poly' triangles: a footprint becomes massing, a boundary loop becomes a wall.
- [polygonBoolean](#polygonboolean) — Planar boolean of closed polylines: the UNION, INTERSECTION or DIFFERENCE of the polygons on `in` (the subject) and the polygons on `clip`, computed in a plane (`plane`, 'xz' by default).
- [smoothNormals](#smoothnormals) — Rewrites the point `normal` (f32 tuple 3) of a triangle mesh so a faceted curve shades as the surface it approximates while a real edge stays sharp.
- [splitPolygons](#splitpolygons) — Cuts every polygon on `in` along the polylines on `cutters`, removing a strip `kerf` wide around each cut, and puts out the PIECES: the glass lights between a window's mullion bars, the panels of a facade between its joints, a slab cut into bays.
- [sweepProfile](#sweepprofile) — Places a cross-section on EVERY POINT of every polyline primitive and stitches consecutive placements into 3-vertex 'poly' triangles: a curve becomes a surface.

**value**

- [valueConstant](#valueconstant) — Emits a single constant number as a value item, for feeding value pins or tagging pipelines with plain data.

## applyRules

Composite node that runs a REWRITING GRAMMAR over labelled cells, one ROUND at a time: the recursion of a split grammar (a facade into floors, floors into panels, panels halved until they are small), in a graph that cannot wire a cycle. ONE INLINE BODY, AND A RULE IS A PIN PAIR: an exposed input and an exposed output with the SAME name form a rule, and that name is the LABEL it rewrites. Each round the frontier is partitioned by the string point attribute `labelAttr` ("piece", splitBox's): input X receives every cell labelled X, and output X's cells are that rule's products, whatever labels they carry, so a `panel` rule whose products are labelled `panel` again is a recursion. A label with no rule is TERMINAL: its cells leave on `out`, in the order they settle. An exposed input with NO same-named output is a BROADCAST, fed whole to every round (an occluder, a lookup cloud). So the node's own pins are `in` (the axiom cells, round 0's frontier) plus the broadcasts, and `out`, `trail` (the derivation trail, below), `rounds` (how many times the body cooked) and `converged` (1, or 0 when maxDepth cut the grammar off); the rule pairs are interior and are never wired. ONLY FED RULES COOK: each round cooks the body once, requesting only the outputs of rules that received cells, so a branch is never cooked on an empty input and may freely read a column only its own producers write. That is why the body is checked when it is built: output X may not depend on another rule's input (duplicate the node, or move it upstream of a broadcast; a node reading only broadcasts may be shared), input X must reach output X, a broadcast must reach some rule, and an output with no same-named input is refused (there are no side outputs). VARIANTS AND STOPPING ARE RELABELS IN THE BRANCH, never wrapper params: a rule picks a variant with setAttribute type "string", values ["square", "arched"] and an index field reading the roll, lt(attribute("ruleRoll"), 0.4); it stops a recursion by relabelling small cells to a terminal label (values ["panel", "leaf"], index lt(max(box("sx"), box("sy")), 1.2)) and cutting the rest with a splitBox whose `where` is attributeIs("piece", "panel"). EVERY RELABEL COSTS ONE ROUND of depth, so size maxDepth for it. ITERATION METADATA: every cell gets `depthAttr` (i32) as it is classified, the round, which is its lineage depth; every FED cell also gets `rollAttr` (f32 in [0, 1)), hashed from this node's seed, the rule's label and a SCOPE identity: the cell's own by default (and the round, so a relabel-only recursion draws afresh each round), or, with `scoped`/`scopeOf`, its nearest ancestor that was fed to the named rule ("root" for its axiom cell), so every window under one facade rolls the same number. A scoped cell with no such ancestor is refused, and a rule scoped to itself is refused as a no-op. PRODUCTS MUST DERIVE FROM THE RULE'S INPUT: each fed cell carries a u32 lineage column `__ruleSrc`, and a product that lost it or names a cell fed to another rule (a fresh pointList merged in, a broadcast cell) is refused by name. On `out` the column is handed back as the axiom cell carried it on `in` (removed when `in` had none), so an applyRules nests inside another's rule branch, directly or inside a subgraph. A column one rule writes and another does not is default-filled on the other's cells when a round's products are concatenated (mergePoints' union, in the body's exposed-output order). TERMINATION IS REPORTED, NOT THROWN: cells still feeding a rule at maxDepth go to `out` unexpanded, `converged` is 0, and the detail attribute `rulesCutOff` on `out` (i32, one component per rule in the body's exposed-output order, always written, all zero when converged) counts them per rule, with `rulesCutOffRules` (a string tuple, same order) naming the rule behind each component; a grammar grown past 4194304 cells is refused, naming the round. THE DERIVATION TRAIL: `trail` holds every cell that was FED to a rule, one row per rule application, as it was fed (its own columns and box, its label, which is the rule it was fed to, its `depthAttr` and `rollAttr`). Rows run round by round, and within a round rule by rule in the body's exposed-output order, each rule's cells in frontier order. `parentAttr` (i32, default "ruleParent") is the parent link on `trail` AND on `out`: the `trail` ROW of the rule application that produced the cell, or -1 for a cell that came in on `in`; so on `trail` a row's ruleParent is always smaller than its own index, and following it walks a cell's ancestors back to its axiom. Read an ancestor's box with transferByIndex (source the trail, index attribute("ruleParent"), outOfRange "miss" for the roots), or draw the derivation tree with connectByIndex over the trail (rootValue -1); filter the trail by label to get, say, every storey a later stage must not cover. A cell cut off at maxDepth was never fed, so it is on `out` and not on `trail`. The row numbering is a fact of the grammar, not of the wiring, so `out`'s links are the same whether or not `trail` is wired, and the trail is BUILT ONLY WHEN SOMETHING READS IT (a connection or a declared graph output): unread, it is an empty collection and the loop retains no cell. A nested applyRules' trail is its own; the outer node rewrites the parent column its products carry. Wiring the trail never fails a cook that succeeds unwired: a column the trail's rows (cells of different rounds) carry in two shapes is left off the trail and named in its detail attribute `trailDroppedColumns`, and a column named `parentAttr` in another shape is refused where it appears, under either wiring. A grammar whose trail would pass 4194304 rows is refused, naming the round, whether or not `trail` is wired, so the links on `out` always name rows that exist. SEEDS: the body cooks under one seed for every round, hashCombine(nodeSeed, hashString("applyRules")); splitBox re-seeds each piece from its parent, so a cell's draws follow its lineage rather than the round. That holds only for rules that RE-SEED: a relabel keeps the cell's identity, so a randomField in a relabel-only recursion draws the parent's number again every round (it stops at once or never); a per-round chance reads `ruleRoll` instead. A cell's subtree is independent of its siblings only when every node in its branches is ELEMENTWISE: an attributeReduce or neighbourhood node couples all cells of one label in one round, and `out` indices shift whenever a sibling's output changes. The loop is CPU; a branch's field params may resolve on the GPU device, each node recording its own fallback. Inline payload only: no `ref` in this version. Create instances with applyRulesNode(innerGraph, exposedInputs, exposedOutputs, exposedParams), or deserialize a graph containing one.

**Category:** composite

**Meters the cook budget itself:** under `cook(graph, { budgetMs })` this node yields to the event loop inside its own execute, so its `NodeDoneInfo.elapsedMs` is wall time spanning those yields — not an uninterrupted block. Derive a longest-block figure from a cook with the budget unset.

**Inputs:** *(none)*

**Outputs:** *(none)*

**Examples:** [basics-apply-rules.json](../graphs/basics-apply-rules.json), [examples-facade.json](../graphs/examples-facade.json), [examples-floorplan.json](../graphs/examples-floorplan.json) — 4 total (`pcg graphs --node applyRules`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `maxDepth` | u32 | `32` | 1..1024 |  |  | The most ROUNDS the grammar runs: the body cooks at most this many times, and a cell is expanded at lineage depth maxDepth - 1 at the deepest. EVERY RELABEL COSTS A ROUND — a rule that only picks a variant (window -> arched \| square) or marks a cell finished (panel -> leaf) is one round of depth for the cells it relabels — so count the relabels when sizing it: a facade split into floors, floors into panels, panels halved until small and then given a styled window is easily fifteen rounds deep. Reaching the cap is NOT an error and is not silent: the cells still carrying a rule's label go to "out" unexpanded, "converged" reports 0 and the detail attribute "rulesCutOff" on "out" counts them per rule, with "rulesCutOffRules" naming the rule behind each component, so the rule that would not stop is named. A grammar that GROWS every round is stopped sooner, by the 4194304-point cap, which is refused naming the round and the rule. |
| `labelAttr` | string | `"piece"` |  |  |  | The STRING point attribute (tuple 1) the frontier is dispatched on: a cell whose label equals a rule's name is fed to that rule, any other label is terminal and goes to "out". splitBox's labelAttr default, so a split's labels ARE the rules' names. Required on "in" and on every rule's products; a missing or non-string column is refused naming the rule that dropped it. |
| `depthAttr` | string | `"ruleDepth"` |  |  |  | The i32 point attribute (tuple 1) written on every cell as it is classified: the ROUND, which is the cell's lineage depth (an "in" cell is 0, its products 1, ...). A rule reads it as iteration metadata — lt(attribute("ruleDepth"), 3) caps a recursion at a fixed depth. On "out" it is the depth the cell settled at (maxDepth on a cell the cap cut off). Empty writes none. Not a standard attribute, and not the same name as labelAttr or rollAttr. |
| `rollAttr` | string | `"ruleRoll"` |  |  |  | The f32 point attribute (tuple 1) written on every FED cell: a number in [0, 1) hashed from this node's seed, the rule's label and the cell's SCOPE identity (see "scoped"); an UNSCOPED roll also folds in the round, so a rule that keeps a cell's label and identity (a relabel-only recursion: "stay a panel while the roll is under 0.7") draws afresh every round. The branch picks a variant with it — setAttribute string, values ["arched", "square"], value lt(attribute("ruleRoll"), 0.5) — so the weights sit in the branch, resolved on that rule's cells only. Different rules roll independently even under one scope. On "out" a cell carries the roll of the rule application that produced it (0 on a cell that arrived terminal). Empty writes none, and is refused when "scoped" lists anything, since the scope would then reach no column. |
| `scoped` | stringList | `[]` |  |  |  | Rules whose ROLL is SHARED by a scope, parallel to "scopeOf": rule scoped[i] rolls on the identity of its NEAREST ANCESTOR fed to rule scopeOf[i], so every such cell under one ancestor rolls the same number — one window style per facade is scoped ["window"], scopeOf ["facade"]. A rule not listed rolls on its own cell's identity, so every cell differs. The roll is shared; the DECISION is shared only if the branch's selector reads nothing per cell besides the roll. A RECURSIVE rule scoped to an ancestor rolls the same number at every depth and so decides the same at every depth, which is usually a mistake. Each entry must name a rule (did-you-mean otherwise), once. |
| `scopeOf` | stringList | `[]` |  |  |  | The scope of each "scoped" entry, same length: the name of a RULE (the nearest ancestor that was fed to it), or "root" — the cell on "in" the scoped cell descends from, which every cell has. A rule scoped to ITSELF is refused: its nearest ancestor-or-self fed to it is the cell itself, which is exactly what not listing it does. A cell with NO ancestor fed to its scope rule — it arrived on "in" already carrying the scoped label, or came down a branch that never passed through the scope rule — is REFUSED, naming the rule, the round and the scope, rather than rolled on some other identity: scope it to "root", or route every such cell through the scope rule. |
| `parentAttr` | string | `"ruleParent"` |  |  |  | The i32 point attribute (tuple 1) linking a cell to the rule application it came from, written on "out" and on "trail": the ROW of "trail" holding the cell that a rule rewrote into this one, or -1 for a cell that came in on "in" (an axiom cell, or a terminal one that never fed a rule). "trail" lists every FED cell round by round, and within a round rule by rule in the body's exposed-output order, each rule's cells in frontier order — so on "trail" a row's ruleParent is always smaller than the row's own index, and following it from any cell walks its ancestors back to the axiom. Read an ancestor's box with transferByIndex (source "trail", index attribute("ruleParent"), outOfRange "miss" for the -1 roots), or draw the derivation tree with connectByIndex over "trail" (rootValue -1). The numbering does not depend on whether "trail" is wired, so the links on "out" always mean the same rows. Empty writes none. Not a standard attribute, and not the same name as labelAttr, depthAttr or rollAttr. A column of this name already on the cells in another shape is refused where it appears (on "in", or on the output of the rule that wrote it), the same whether or not "trail" is wired. |

## arcTile

Lays a REPEATED PIECE over arc ranges of a path: one oriented instance point every `spacing` units between each range's start and end, ready for spawnInstances. This is the tile-a-tunnel-out-of-one-rib operation, and it is a primitive rather than a convenience because ENCLOSURE IS A PATTERN, NOT AN ASSET — a heavily enclosed lap needs its cover held up by scores of separate objects, no single one of them much of the total, the workhorse being one strip placed dozens of times. There is no tunnel model to find and place; there is a run of repeated pieces over an arc range, which is what this builds. THE RANGES ARRIVE AS A SECOND GEOMETRY, one point per range, carrying the range's start and length as point attributes (`runStart` and `runSpan` by default, which are runFit's own defaults, so a detected run re-tiles without renaming anything). A point cloud rather than params because there are MANY ranges and each carries its own decisions — where it starts, how long it is, which piece it is made of, how wide, which variant — and a param is one value for the cook. It also makes every existing node a range producer: scatter them, filter them, snap them, reject the ones that overlap, all before a single tile exists. ATOMICITY IS THE WHOLE POINT AND IT IS STRUCTURAL. A tunnel is the SAME piece repeated; drawing a fresh piece per rib reopens the seams the overlap was there to close, and in the case this node comes from a planned 17-unit covered stretch measured back as 8 the moment poses were drawn per piece. So the choice is made ONCE, upstream, on the range point — where there is exactly one element per run to make it on — and `rangeNames` COPIES it onto every tile of that range. Copying is what makes it atomic: a per-tile draw can be uniform only by luck, and only until someone changes the seed. The tile's own `seed` is rooted in the range for a weaker but related reason — it is hashCombine(the node's seed, hashCombine(the range's own seed, the range's index), the tile's index within the range), so the tiles of one range keep their per-tile jitter when a DIFFERENT range changes its spacing, which a seed taken from the global tile index cannot offer. The range's INDEX is folded in as well as its seed because a ranges cloud that never had a seed written carries a column of zeros, and rooting on that alone would hand every range identical tiles. SPACING IS A CEILING ON THE PITCH, NOT THE PITCH. A range takes ceil(length / spacing) tiles, placed at the centres of that many EQUAL sub-intervals, so the actual step is length / count and is at most `spacing`. Rounded UP so pieces at least abut: rounding to nearest leaves the pitch wider than asked whenever a range is not a whole number of pieces long, and a gap in a tiled cover is not a near-miss but a hole — a planned 15-unit run was closing 9.6, under the 10 that counted as a long stretch at all. Nothing here knows how big your piece is: to OVERLAP, give a spacing smaller than the piece. THE MOUTHS FLARE. `flare` is the arc distance over which each end opens and `taper` the scale the very mouth reaches, applied to the two `scale` components that are not the `axis` — so the cross-section opens and the length along the path does not, which is what makes a driver see an opening rather than a wall and what keeps the entry clear at the moment it matters. `flareAttr` writes the raw 0..1 ramp instead, for everything else a mouth might do (lift, tilt, a different asset), because WHAT flares is the asset's business and not this node's. ON A CLOSED PATH RANGES WRAP: a range crossing the seam is one range, its arc taken modulo the path's length, matching what pathRuns and runFit do with a run there. On an OPEN path a range reaching past either end is REFUSED rather than clamped — a clamped range is a shorter tunnel than the one that was planned, reported as success. THE OUTPUT IS A PLAIN CLOUD, not a path: the tiles are placements along the curve, not the curve, and no polyline topology is built over them, exactly as pathSegments leaves its segment midpoints. Each tile carries P, `rot` (the `axis` turned onto the path's tangent, roll fixed by an up hint of [0, 1, 0] with orientAlongVector's deterministic fallbacks), `scale` (1, tapered at the mouths), `tangent`, `curveU`, `seed`, the standard point attributes, whatever `rangeNames` carries, and the PATH's primitive attributes — so a road's width reaches the ribs standing over it. It emits no randomness of its own.

**Category:** sampler

**Inputs:** `path` (geometry), `ranges` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-tile-an-arc.json](../graphs/basics-tile-an-arc.json), [basics-colonnade.json](../graphs/basics-colonnade.json) — 2 total (`pcg graphs --node arcTile`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `startAttr` | string | `"runStart"` |  |  |  | POINT attribute on the RANGES input (tuple 1, numeric) holding where each range begins, as an arc length in WORLD UNITS along the path — the same coordinate pathResample steps and pathPointAt's 'distance' mode reads. Defaults to runFit's `startAttr` suggestion so a detected run tiles without renaming; note the one conversion that pairing needs, which is that runFit may have been run against a CUSTOM arc coordinate in other units (a lap measured in half-widths), and this node reads world units. On a CLOSED path the value wraps: any real number is legal and is taken modulo the path's length. On an OPEN path a range must lie inside the path, and one that does not is refused rather than clamped. |
| `lengthAttr` | string | `"runSpan"` |  |  |  | POINT attribute on the RANGES input (tuple 1, numeric) holding how much arc each range covers, in world units. Must be > 0 on every range: a range with no length is a single placement rather than a tiling, and this node refuses one instead of emitting a lone tile that looks like a very short tunnel — drop it upstream (filterByAttribute on the length) or place it with pathPointAt. On a closed path it may not exceed the path's own length, since the tiles would lap the loop and cover the same arc twice. Must differ from `startAttr`: a start and a length are two values, and one column cannot hold both. |
| `pathAttr` | string | `""` |  |  |  | POINT attribute on the RANGES input (tuple 1, numeric) naming WHICH polyline each range belongs to, as an index into the path input's PRIMITIVE domain — the same numbering every error message here uses. Empty (the default) is legal only when the path input holds exactly ONE polyline, which is the ordinary case; with several, this is REQUIRED rather than defaulted to the first, because tiling the wrong road is a cook that looks entirely fine. An index that is not a polyline of the input is refused, listing the ones that are. |
| `spacing` | f32 | `1` | >= 0 |  | yes | Ceiling on the distance between consecutive tiles, in world units. A range of length L takes max(1, ceil(L / spacing)) tiles at the centres of that many equal sub-intervals, so the PITCH is L / count and is at most this value — never more. Rounded up rather than to nearest so that pieces meant to abut do: a nearest-rounded pitch is wider than asked whenever the range is not a whole number of pieces long, and a gap in tiled cover is a hole rather than a near-miss. This node does not know how big your piece is, so overlap is spelled as a spacing SMALLER than the piece — about 5% under is enough to close the wedge two pieces leave on the outside of a bend. Must be > 0. AS A FIELD IT IS ONE SPACING PER RANGE, resolved on the RANGES input's POINT domain, which is what lets the pitch follow the piece: a range that chose a 5-unit strip and one that chose a 1-unit rib tile at their own pitches in ONE cook, reading the size the range itself carries. A field is not range-checked the way a plain value is, so bound the expression with max(<expr>, <the smallest pitch you meant>); a NaN or infinite spacing is refused, naming this param, and so is the whole cook when the resolved spacings would place more than 1048576 tiles. |
| `flare` | f32 | `0` | >= 0 |  | yes | Arc distance over which each MOUTH of a range opens, in world units; 0 (the default) is no flare. Every tile gets a ramp of 1 at the very mouth falling to 0 at this distance inside, taken from whichever end is nearer, and the ramp drives `taper` and `flareAttr`. It exists because a tiled cover that starts at full section is a wall with a hole in it: the eye reads an opening from the way the section grows, and the flare is also what keeps the view clear at the moment of entry, which is the moment it matters. A flare of at least half the range's length ramps every tile (the two mouths meet in the middle) and is legal — the ramps do not add, each tile taking the nearer mouth's. One value per RANGE as a field, resolved on the ranges' POINT domain exactly as `spacing` is, so a long tunnel and a short gantry can open over different distances in one cook. |
| `taper` | f32 | `1` | >= 0 |  | yes | The `scale` a tile reaches AT the mouth, interpolated to 1 at `flare` inside; 1 (the default) is no taper, and with `flare` at 0 this is read nowhere. Applied to the two scale components that are NOT `axis` — the cross-section — so the mouth opens or pinches while the piece's length along the path is left alone; scaling all three would make the mouth pieces longer as well as wider and leave gaps between them. Above 1 opens the mouth (1.5 is a mouth half again as tall and wide), below 1 pinches it, which is what a run that should taper away to nothing at its ends wants. One value per RANGE as a field, on the ranges' POINT domain. |
| `axis` | enum | `"+z"` |  | `+x`, `-x`, `+y`, `-y`, `+z`, `-z` |  | Which local axis of the tiled asset points ALONG the path, and therefore which two `scale` components `taper` opens. Default '+z', matching orientAlongVector rather than pathSegments' '+y': this node points a piece at a heading and does not stretch it to span anything, where pathSegments puts the SEGMENT'S LENGTH on the chosen axis to draw a tube. Roll around the path is fixed by an up hint of [0, 1, 0] with the same deterministic fallbacks orientAlongVector uses ([0, 0, 1], then [1, 0, 0]) — never random, and never left to whatever a degenerate cross product produced. |
| `flareAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (f32) on the output receiving each tile's raw FLARE RAMP — 1 at the mouth, falling linearly to 0 at `flare` inside, and 0 everywhere on a range with no flare. Empty (the default) writes none and the output is byte-identical to a cook without it. It is here because WHAT a mouth does is the asset's business and not this node's: `taper` covers the common case of opening the section, and everything else — lifting the roof, tilting the pieces outward, swapping in a wider variant at the entrance, fading a material — is a field or a setAttribute reading this column. The ramp is per tile, taken from the NEARER mouth, so a range shorter than twice its flare has every tile ramped and none of them at zero. |
| `tileIndexAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (i32) receiving each tile's 0-BASED INDEX WITHIN ITS OWN RANGE, restarting at 0 for every range. Empty (the default) writes none. It is the per-range coordinate nothing else can state: this node emits NEW points, so an index written upstream with setAttribute does not survive, and `curveU` is a fraction of the whole path rather than of the range. Without it, 'every other rib' has to be spelled on the GLOBAL point index, which agrees with the per-range one only while every range emits the same, EVEN, number of tiles and reports nothing when that stops being true. Index 0 is the tile nearest the range's start in the path's walk direction, including on a range that wraps a closed path's seam. |
| `rangeIndexAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (i32) receiving the index of the RANGE a tile came from, in the ranges input's own point order. Empty (the default) writes none. This is the group key: partitionByAttribute splits one item per run, pointsToPath's `groupAttr` threads each run's tiles into a path of their own, and attributeReduce collapses per run — 'how long did this run actually come out' is a reduction over this. It also names the atomic unit for anything that must be decided once per run and is easier to write downstream than upstream. |
| `rangeNames` | stringList | `[]` |  |  |  | Point attributes of the RANGES input to copy onto every tile of that range, in any order; empty (the default) carries nothing, which is not an error. THIS IS THE ATOMICITY MECHANISM. A tunnel is one piece repeated, so the piece is chosen ONCE — on the range point, where there is exactly one element per run to choose on, by whatever upstream node makes that kind of decision — and copied here, unchanged, onto every tile. A per-tile draw is uniform only by accident: the case this node comes from measured a planned 17-unit covered stretch back as 8 the moment poses were drawn per piece, because varying the shape along a run reopens the seams the overlap existed to close. Carry the asset id, the variant, the yaw, the width, the material — anything that must be the same all the way along. Each column arrives with the range's own type, tuple size and default. Three names are refused rather than resolved silently: one this node writes itself (P, rot, scale, density, boundsMin, boundsMax, color, seed, tangent, curveU, and whatever flareAttr/tileIndexAttr/rangeIndexAttr named) — copy it to another name on the ranges first with setAttribute and carry that; a name repeated in the list; and a name the ranges input does not have, which is an error listing what it does have. |

## attributeReduce

Collapses a numeric attribute over a whole domain into a single value on the detail domain: sum, min, max, average (all f32, componentwise, keeping the source tuple size) or count (u32, the number of elements — this mode reads no attribute). NaN elements are ignored by every mode, and average divides by however many were left, so one bad element cannot destroy the statistic; this is the deliberate difference from promoteAttribute point->detail, which propagates NaN. The other difference is outName: two reductions of one attribute (a min AND a max) can coexist, which promoting cannot do because both would land on the same detail name. Over an empty domain sum and average are 0, min is Infinity, max is -Infinity, count is 0. Note that a detail attribute is NOT readable from a point-domain field (a field reads the domain it lands on), so a reduction is for hosts, inspection and cook-stat reporting — to rescale an attribute by its own observed range use attributeRemap's 'fit' mode, which measures it internally.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-repeat-until-settled.json](../graphs/basics-repeat-until-settled.json), [basics-report-to-the-host.json](../graphs/basics-report-to-the-host.json), [examples-coral.json](../graphs/examples-coral.json) — 4 total (`pcg graphs --node attributeReduce`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"density"` |  |  |  | Numeric attribute to reduce (tuple 1..4). Must exist on `domain`. Ignored by mode 'count', which counts elements and may leave this empty. |
| `domain` | enum | `"point"` |  | `point`, `vertex`, `primitive`, `detail` |  | Domain to reduce over: point, vertex, primitive, or detail (one element). |
| `mode` | enum | `"max"` |  | `sum`, `min`, `max`, `average`, `count` |  | How the elements collapse: sum, min, max, average (each componentwise over the tuple, NaN elements skipped), or count (how many elements the domain has, ignoring `name`). |
| `outName` | string | `""` |  |  |  | Name of the detail attribute to write. Empty (the default) reuses `name`, which is what promoting would have produced; give distinct names to hold several reductions of one attribute at once. The shape is this node's to pick (f32 at the source's tuple size, or u32 for mode 'count'), so a name the DETAIL domain already holds under a different shape is REFUSED rather than deleted and re-added — writing it would destroy that column while the cook still looked fine. A same-shape column is reused and reset. The one exception is reducing a detail attribute into its own name: there the column replaced is the column read, so it converts in place. |

## attributeRemap

Rescales a numeric attribute linearly from an input range to an output range, writing f32. Mode 'range' uses inMin/inMax as given — the hand-tuned remap(x, -1, 1, 0, 1) that every noise-driven graph writes. Mode 'fit' MEASURES the attribute's own range over the domain first (ignoring NaN) and uses that, which is what turns any invented quantity — a neighbor count, a hand-built score — into a usable 0..1 density or color input without knowing its scale in advance; it is also why this node needs no help from attributeReduce, whose detail-domain output no field or param could have read back anyway. An empty input range (inMin == inMax, or a fit over zero usable elements) maps everything to outMin, matching the `remap` field function. Tuples remap componentwise against one shared range, and NaN stays NaN in every mode — including the empty-range case, so unmeasurable data never turns into a valid-looking value. Reversed output ranges are fine and invert the values. All four window ends accept a FIELD, which makes the range PER ELEMENT rather than shared: each element is rescaled against its own window, the tuple still sharing that element's one range, and every rule above (empty range maps to outMin, NaN stays NaN, reversed inverts) then holds element by element instead of domain-wide. Mode 'fit' is the exception it already was — it measures inMin/inMax and never reads them, field or not.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-attribute-remap.json](../graphs/basics-attribute-remap.json) — 1 total (`pcg graphs --node attributeRemap`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"density"` |  |  |  | Numeric attribute to rescale (tuple 1..4). Must exist on `domain`. |
| `outName` | string | `""` |  |  |  | Name of the f32 attribute to write on the same domain. Empty (the default) rewrites `name` in place, which also converts an integer attribute to f32. Writing over a DIFFERENT attribute that already exists with another shape is REFUSED rather than deleted and re-added — remapping into an i32 `id` or into `P` would destroy that column while the cook still looked fine. A same-shape column is reused, and the in-place conversion above stays legal because there the column replaced is the one being read. |
| `domain` | enum | `"point"` |  | `point`, `vertex`, `primitive`, `detail` |  | Domain the attribute lives on: point, vertex, primitive, or detail. |
| `mode` | enum | `"range"` |  | `range`, `fit` |  | 'range' takes the input range from inMin/inMax; 'fit' measures the attribute's actual minimum and maximum over the domain and ignores inMin/inMax — a FIELD in either of them is ignored the same way, and is not evaluated at all. Only the INPUT window is measured: outMin/outMax are read in both modes, fields included. |
| `inMin` | f32 | `-1` |  |  | yes | Value mapped to outMin, in mode 'range'. As a FIELD it is a PER-ELEMENT window end, evaluated on `domain`, so each element is rescaled against its OWN input range instead of one range shared by the whole domain: a per-point noise floor, or a threshold read from another attribute, turns the same source values into different results for different elements — which no single number can do. The window is per ELEMENT, not per component: a tuple attribute remaps all of its components against that element's one window, as it already does against the shared one. Mode 'fit' IGNORES this param and does not evaluate it at all — a field there is dead exactly as a plain number is, because fit measures the attribute's own minimum and maximum instead. A degenerate window is a per-element outcome, not a refusal: where inMin resolves equal to inMax that element maps to outMin (NaN sources stay NaN), the same rule the shared empty range follows. Non-finite is refused, naming this param, since an infinite span maps everything to 0 and a NaN one erases the attribute. |
| `inMax` | f32 | `1` |  |  | yes | Value mapped to outMax, in mode 'range'. As a FIELD it is a PER-ELEMENT window end evaluated on `domain`, the upper counterpart of inMin: the two together give each element its own input range, so 'what counts as high here' can vary across the domain — the per-element version of the hand-tuned remap(x, -1, 1, 0, 1). Reversed per element is fine (inMin above inMax) and inverts that element only. Mode 'fit' IGNORES this param and does not evaluate it at all. Where it resolves equal to inMin the window is empty and that element maps to outMin, NaN sources excepted (they stay NaN). Non-finite is refused, naming this param. |
| `outMin` | f32 | `0` |  |  | yes | Value inMin maps to. As a FIELD it is a PER-ELEMENT output floor, evaluated on `domain`, so each element lands in its own destination range — the way to remap a shared quantity into per-element bands (a scale whose floor follows the point's size, a colour ramp whose ends differ by region) in one node. Read per element in every mode, INCLUDING 'fit', which measures only the input window; and it is also the value an empty window (inMin == inMax, or a fit over nothing usable) maps that element to, so a fielded outMin decides the degenerate case too. With clamp on, the bounds are this element's own outMin/outMax, whichever is smaller and larger. Non-finite is refused, naming this param. |
| `outMax` | f32 | `1` |  |  | yes | Value inMax maps to. As a FIELD it is a PER-ELEMENT output ceiling, evaluated on `domain`, the upper counterpart of outMin: with both fielded, every element gets its own output band, and reversing them per element (outMax below outMin) inverts that element alone. Read per element in every mode, INCLUDING 'fit'. Note that an empty input window maps to outMin, not to this param, so a per-element ceiling has no effect where the window collapsed. Non-finite is refused, naming this param. |
| `clamp` | bool | `false` |  |  |  | Hold results inside the output range (whichever of outMin/outMax is smaller or larger). False (the default) extrapolates, matching the `remap` field function; true is the usual choice when the result feeds density or color. In mode 'fit' it only affects NaN-free data trivially, since fitted values already land inside the range. |

## boxContact

Asks, for every BOX on the `in` pin (the QUERIES), whether it meets any box on the `targets` pin, and writes the answer onto the query points as attributes: `hitAttr` a bool (any target met), `countAttr` an i32 (how many distinct targets), `targetAttr` an i32 (the index of the met target whose WORLD centre is nearest the world centre of the query box as tested, -1 for none). Nothing else changes — same points, same order, same topology, every attribute carried — so the usual next step is a filter or a relabel on the flag. This is the CONTEXT QUERY of a split grammar (the occlusion query of the shape-grammar literature, and the box form of a point-in-volume or group-by-bounding-object test): is this window blocked by a neighbour or a chimney, does this bay cross any box of another set, is this room inside the lot. A BOX is a point's standard `boundsMin`/`boundsMax`, an extent in the point's OWN frame — the one reading every box node gives it — mapped through P, rot and scale exactly as spawnInstances places a mesh (world = P + rot * (scale * corner)), so a rotated box is tested as the ORIENTED box it is (rot is normalized first, so a non-unit quaternion places the box rigidly where spawnInstances' matrix would also scale it; a missing rot is the identity and a missing scale 1). TWO BOXES IN ONE FRAME — their points' P, rot and scale bit-identical, with no scale component 0, which is every pair of pieces of one grammar root — are compared IN THAT FRAME, on their stored corners, exactly and with no tolerance band, whatever the shared rotation and scale (overlap, touch, contain and inside do not change under one shared invertible map), so a rotated building's rooms meet as they do unrotated. Boxes in different frames are compared in the world. THE MODE (`mode`) is the question: "overlap" — the two boxes CROSS: on every separating direction their extents overlap by more than zero, so boxes that only share a face, an edge or a corner do NOT overlap (two neighbouring grammar cells are not overlapping), while a zero-thickness box passing through a solid one does; "touch" — the same test closed, so sharing a face, edge or corner COUNTS (the party-wall neighbour); "contain" — the target lies wholly inside the query, boundary included; "inside" — the query lies wholly inside the target, boundary included. THE TESTS ARE EXACT for oriented boxes too — the separating-axis test on all fifteen axes for overlap and touch, the support extent along the outer box's three axes for contain and inside — with two stated approximations that apply only to a pair in DIFFERENT frames where a box is ROTATED: a cross axis of two edges within 1e-6 rad of parallel is skipped as rounding noise, which can only turn "apart" into "meet", across a gap of at most about 1e-6 of the boxes' size; and a gap or an overlap within 1e-12 of the pair's scale (its largest centre coordinate plus both boxes' half-extents), on any axis, is read as EXACT contact in both directions — "touch" accepts it and "overlap" rejects it — so two boxes under one P and rot that share a face share it under every rotation rather than as rounding decides. Same-frame pairs, and pairs whose boxes both lie along the world axes (no rotation, or a half turn), are compared with no tolerance band, in f64 from each box's centre and half-extent: exact while the terms summed on an axis (P, the corners, the margins) lie within about 2^29 of each other; past that, rounding can read an exact shared face as apart, or a one-ulp gap as touching. THE MARGINS move the QUERY box's faces before the test, per query point, in the BOX'S OWN UNITS along its own three axes — applied to the stored box before its transform, so a scale scales them, as offsetBox's margins (offsetBox margin m and then this node with margin 0 asks what margin m asks here) — and leave the point's own bounds untouched. `margin` GROWS BOTH faces of each axis: margin 0.5 with "touch" asks "is any target within half a unit of this box, measured per axis" — a box-shaped neighbourhood, not a rounded one; a vec3 gives each axis its own reach, and a scalar field broadcasts to all three. `marginMin` and `marginMax` move ONE face each — the face on the boundsMin side and the face on the boundsMax side — signed, so they reach out of one face only (a wall whose outside is -z: marginMin vec(0, 0, 2) looks two units out of the front and not into the house behind it), shift the box (marginMin -d with marginMax +d moves it d), or carve the query down to a probe of its own: the window test is the bay's box with its outward face pushed half a stud out, its inward face pulled to meet it, and its sides and height pulled in to the opening, all as fields reading the bay's box names and attributes. The three add: the min face moves out by margin + marginMin, the max face by margin + marginMax. A NEGATIVE total shrinks the query, which is how a containment test tolerates a sliver ("inside" with margin -0.01), and a query shrunk past nothing on any axis is EMPTY and meets nothing in every mode. EXCLUSION: `excludeAttr` names a tuple-1 attribute present on BOTH inputs, and a target whose value EQUALS the query's is skipped — the bay that must not count its own wall carries its wall's id (write one with setAttribute before the split; splitBox carries every attribute onto its pieces), and siblings or one parent are excluded the same way. Numbers compare by value whatever their numeric type (NaN never equals anything); strings compare by text, so the two inputs' string tables may differ. `excludeSelf` skips target i for query i, for one cloud wired to BOTH pins ("does this box overlap any OTHER box of its set"); it is refused when the two inputs have different point counts, since they cannot then be one cloud. STAGING: query against an EARLIER stage — another branch's finished output, or an applyRules `trail` (the consumed ancestors, whose boxes are the blocks and storeys a later stage needs) — never against the frontier still being rewritten. DETERMINISM: nothing is drawn, nothing is accumulated, and the nearest target is the LOWEST INDEX among the hits whose squared WORLD centre distance ties with the least (world always, since one query's hits may be in several frames), within a band scaled like the rounding a centre carries (1e-12 of the least squared distance plus 2e-12 of it times the query centre's largest coordinate), so the answers do not depend on the order the targets arrive in beyond that index, and a rotation's rounding cannot break a true tie. COST: near linear in the two counts for any mix of sizes — the targets are binned by centre into one uniform grid per SIZE CLASS (radii doubling), and each query reads each class's grid within its own half-diagonal plus that class's largest, a bounding-sphere bound (two boxes can meet only if their centres are within the sum of their half-diagonals) that changes the cost, never the answer. Under a partitioned cook it is exact given every target whose centre lies within the query's half-diagonal (margins included, measured from the moved centre) plus the largest target's half-diagonal. ERRORS name the pin and point: a box that is not finite or is inside out (min above max), a missing bounds pair, points without P; a graph that still sets the removed `queryFrame` or `targetFrame` is refused naming the removal. CPU ONLY, and deliberately not a GPU adopter: the margin is a value that decides a contact, and a device-rounded margin one ulp off flips a touching pair — the same reason filterByExpression keeps its predicate on the CPU. THE PAIRS: `targetAttr` names ONE met target per query, which cannot say WHICH wall two rooms share; the second output `pairs` is the whole relation — ONE POINT PER (query, target) PAIR that met, exactly the pairs `countAttr` counts (so there are as many as its sum), ORDERED by query index and then target index whatever order the grids found them in, each carrying the two indices as i32 (`pairQueryAttr`, `pairTargetAttr`; transferByIndex with either as its `index` reads that box's own attributes onto the pair) and a `seed` hashed from this node's seed and the two indices. When the two boxes SHARE A FRAME the pair point carries the QUERY's P, rot and scale and its BOX (boundsMin/boundsMax, in that frame) is the INTERSECTION of the query box as tested (margins applied) and the target box: under "overlap" the shared volume; under "touch" the SHARED REGION — the wall two rooms share comes out as that wall, FLAT on the axis they touch along and placed exactly on the target's face, a shared edge as a segment, a shared corner as a point; under "contain" the target's box, under "inside" the tested query's. Two boxes in DIFFERENT frames whose points are both pure translations (rot exactly the identity once normalized, scale exactly 1 — two lots meeting at a party wall) get the same region, in the QUERY's frame: the target's corners moved by the difference of the two P in f64 and rounded once. Under "touch" a pair with a region that meets across exactly ONE face — flush on one axis, by the test's own comparison — also carries that face's frame in shellSplit's vocabulary, FROM THE QUERY'S SIDE: `pairOutwardAttr` the query's outward face normal toward the target ([1, 0, 0] when the target lies on the query's +x side), `pairOutAxisAttr` its axis, and `pairAlongAxisAttr` / `pairAlongSignAttr` the along run shellSplit gives a wall facing that way, so placeBox in its "face" frame centres a door on every shared wall; an edge or a corner contact, or boxes that cross, carry [0, 0, 0], -1, -1 and 0, as shellSplit writes on a cell with no face. Any other pair in different frames has NO REGION — two oriented boxes intersect in a convex polytope, not a box — so its point sits at the midpoint of the two boxes' world centres as tested, with a zero box (boundsMin = boundsMax = [0, 0, 0], the zero box at its P), identity rot, unit scale and the no-face values. ONE CLOUD ON BOTH PINS (excludeSelf): under "overlap" and "touch" each unordered pair appears TWICE, as (i, j) and (j, i), each seen from its own query's side, and filterByExpression on lt(attribute("queryIndex"), attribute("targetIndex")) keeps each once — exact for boxes in one frame with no margins, where the test is one comparison mirrored; under "contain" and "inside" the relation is one-way, (i, j) without (j, i) unless the two boxes are equal, so that filter would drop every pair with i > j and is not the way to dedupe there. `pairs` is built only when something reads it (a connection or a declared output), and `out` is the same bytes either way. More than 3,145,728 pairs (about 377 MB at up to 120 bytes a pair, near the 369 MB of the 2^22-point ceiling repeatPoints and splitBox keep; a 50 x 50 x 50 lattice of touching cubes is 3,116,792 pairs under "touch" with excludeSelf) is refused, stating the pairs found so far, the ceiling, the two box counts and the mode, and the ways to fit: filter or split the input, a smaller margin, "overlap" in place of "touch", or `countAttr` on `out` in place of `pairs`.

**Category:** point op

**Inputs:** `in` (geometry), `targets` (geometry)

**Outputs:** `out` (geometry), `pairs` (geometry)

**Examples:** [examples-floorplan.json](../graphs/examples-floorplan.json), [examples-brick-house.json](../graphs/examples-brick-house.json) — 2 total (`pcg graphs --node boxContact`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"overlap"` |  | `overlap`, `touch`, `contain`, `inside` |  | The question asked of each (query, target) pair. "overlap": the boxes CROSS — sharing only a face, an edge or a corner is NOT an overlap, so neighbouring grammar cells that tile a block do not overlap each other. "touch": the closed test — they overlap OR share a face, edge or corner; with a margin, "within that distance along each of the query's axes". "contain": the target lies wholly inside the (grown) query, boundary included. "inside": the (grown) query lies wholly inside the target, boundary included. Decided once per cook. |
| `margin` | vec3 | `[0,0,0]` |  |  | yes | How far the QUERY box is GROWN on BOTH sides along each of its own three axes before the test, in the box's OWN units [x, y, z]: applied to the stored box before its point's transform, so a scale scales it (offsetBox's margin, with its meaning). 0 tests the box as it is. As a FIELD it is resolved per QUERY point — a scalar broadcasts to all three axes — so each query can reach as far as it needs. vec(0, 0, 2) on a wall running along x grows both its faces, the inside one too; to reach out of ONE face, use marginMin or marginMax instead. NEGATIVE shrinks the query: "inside" with a small negative margin tolerates a sliver of overhang, and "overlap" with one ignores a contact shallower than it. Adds to marginMin and marginMax. A query whose size after all three is below zero on any axis is EMPTY and meets nothing, in every mode. Must be finite. |
| `marginMin` | vec3 | `[0,0,0]` |  |  | yes | How far the query box's MIN-SIDE face — the one its boundsMin corner is on, along each of its own axes — moves OUT before the test, in the box's own units [x, y, z] (scaled with it), on top of `margin`. Signed: positive reaches out of that face only, negative pulls it in, and with marginMax it can shift the box (marginMin -d, marginMax +d moves it d along the axis) or carve a probe out of it. A wall whose outside is -z looks two units out of its front, and not into the house, with marginMin vec(0, 0, 2). As a FIELD it is resolved per QUERY point and may read the query's box names: the window probe half a stud in front of a south wall, flattened onto the outside, is marginMin vec(0, 0, 0.5) with marginMax vec(0, 0, -0.5 - box("sz")), plus whatever pulls the sides in to the opening. The side is the box's own, before its scale's sign: under a negative scale the boundsMin side is still the one this moves. Must be finite. |
| `marginMax` | vec3 | `[0,0,0]` |  |  | yes | How far the query box's MAX-SIDE face — the one its boundsMax corner is on, along each of its own axes — moves OUT before the test, in the box's own units [x, y, z] (scaled with it), on top of `margin`. Signed, with the same readings as marginMin, mirrored: a wall whose outside is +z reaches out of its front with marginMax vec(0, 0, 2). As a FIELD it is resolved per QUERY point. Must be finite. |
| `excludeAttr` | string | `""` |  |  |  | OPT-IN: the name of a tuple-1 point attribute present on BOTH inputs; a target whose value EQUALS the query's is skipped, as if absent. This is how a bay does not count its own wall (give the wall an id before splitting it — splitBox carries every attribute onto its pieces — and give the targets the same column), and how siblings or the children of one parent ignore each other. Numbers compare by value across numeric types (i32, u32, f32, bool), and NaN never equals anything; strings compare by TEXT, so the two inputs' string tables need not agree. A string on one side and a number on the other is refused. Empty (the default) excludes nothing. |
| `excludeSelf` | bool | `false` |  |  |  | Skip target i for query i: for ONE cloud wired to both pins, asking whether each box meets any OTHER box of its own set. Refused when the two inputs have different point counts, since they cannot then be one cloud. With two different clouds of equal size it silently pairs them by index, so leave it off there. |
| `hitAttr` | string | `"contact"` |  |  |  | Name of the bool point attribute (tuple 1) receiving whether the query met at least one target. A REPORTING SLOT: an existing bool tuple-1 column of that name is reset and rewritten, one of any other shape is refused rather than destroyed. Empty writes no flag (then countAttr or targetAttr must be set). |
| `countAttr` | string | `""` |  |  |  | OPT-IN: name of the i32 point attribute (tuple 1) receiving how many DISTINCT targets the query met (exclusions not counted). Worth writing when the question is how crowded a box is rather than whether it is clear. A reporting slot on the same terms as hitAttr. Empty (the default) writes none. |
| `targetAttr` | string | `""` |  |  |  | OPT-IN: name of the i32 point attribute (tuple 1) receiving the INDEX, in the targets input, of the met target whose box's WORLD centre is nearest the world centre of the query box AS TESTED (after its margins), ties — distances equal within a band scaled like the centres' rounding (see the node description), so a rotation's rounding cannot decide one — to the lowest index, or -1 when none was met. Feed it to transferByIndex as `index` to read that target's own attributes — its label, its id, its colour. A reporting slot on the same terms as hitAttr. Empty (the default) writes none. |
| `pairQueryAttr` | string | `"queryIndex"` |  |  |  | Name of the i32 point attribute on the `pairs` output receiving each pair's QUERY index — the ordinal of its box on the `in` pin. Required: the two indices are what a pair IS. The pairs are sorted by it first. Feed it to transferByIndex as `index`, with the queries as `source`, to read the query's own attributes (a room's label, its id). It may not be one of the standard point columns the cloud already carries (P, rot, scale, density, boundsMin, boundsMax, color, seed), nor a name another pair param uses. |
| `pairTargetAttr` | string | `"targetIndex"` |  |  |  | Name of the i32 point attribute on the `pairs` output receiving each pair's TARGET index — the ordinal of its box on the `targets` pin; within one query the pairs run in increasing target index. Required, and on the same terms as pairQueryAttr. With one cloud on both pins under "overlap" or "touch", lt(attribute("queryIndex"), attribute("targetIndex")) in a filterByExpression keeps each unordered pair once ("contain" and "inside" are one-way, so there it would drop pairs). |
| `pairOutwardAttr` | string | `"outward"` |  |  |  | Written under "touch", on every pair (a pair with no region, or not across one face, gets the no-face value): name of the f32 tuple-3 point attribute on the `pairs` output receiving the QUERY's outward face normal toward the target when the two meet across exactly one face — one signed axis, [0, 0, 1] when the target lies on the query's +z side — and [0, 0, 0] for an edge or corner contact or boxes that cross. shellSplit's `outwardAttr` default and meaning, so placeBox and offsetBox read it in their "face" frame. Empty writes none. |
| `pairOutAxisAttr` | string | `"outAxis"` |  |  |  | Written under "touch", on every pair (a pair with no region, or not across one face, gets the no-face value): name of the i32 point attribute on the `pairs` output receiving the axis the two boxes touch across, 0 = x, 1 = y, 2 = z — the axis the shared region is flat on — or -1 when they do not meet across exactly one face. shellSplit's `outAxisAttr` default: 1 is a floor or a ceiling, so a filter on ne(attribute("outAxis"), 1) * ge(attribute("outAxis"), 0) keeps the walls. Empty writes none. |
| `pairAlongAxisAttr` | string | `"alongAxis"` |  |  |  | Written under "touch", on every pair (a pair with no region, or not across one face, gets the no-face value): name of the i32 point attribute on the `pairs` output receiving the shared face's ALONG axis as shellSplit writes it on a face of that orientation — x for a face across z, a floor or a ceiling; z for a face across x — or -1 with no single face. With pairAlongSignAttr and pairOutwardAttr it is the frame placeBox's "face" frame reads. Empty writes none. |
| `pairAlongSignAttr` | string | `"alongSign"` |  |  |  | Written under "touch", on every pair (a pair with no region, or not across one face, gets the no-face value): name of the i32 point attribute on the `pairs` output receiving the sign along runs, +1 or -1, as shellSplit writes it so that along x up = the query's outward — left to right as seen from the TARGET's side of the shared face, looking back at the query — or 0 with no single face. Empty writes none. |

## boxesToMesh

TURNS every cell's box into MESH FACES, built where the box is: the step from a grammar's cells (splitBox, shellSplit, placeBox, offsetBox, transformBox) to geometry a renderer draws. A CELL IS A POINT WITH A BOX, as in splitBox: its standard `boundsMin`/`boundsMax`, an extent in the point's OWN frame — the one meaning every box node gives it — so every vertex is built on the stored box and mapped THROUGH THE CELL'S TRANSFORM, world = P + rot * (scale * x), exactly as spawnInstances places a mesh: a rotated building's walls are built turned, a mirrored one mirrored (rot is normalized first, as boxContact reads it, a zero quaternion is the identity and a missing rot or scale is the identity; a non-finite P, rot or scale is refused naming the cell). It needs no pivot: cells can go straight from the grammar to here. (To hand cells to INSTANCES instead — copyToPoints or spawnInstances of a unit asset — move each P to its piece first with pivotBox, then scale = mul(attribute("scale", 3), box("size")) and the unit box; that tail rebuilds each face from a centre and a size, f32(c + s * 0.5), which can miss the stored face by an f32 ulp, so two cells that share a face can open or overlap by that ulp. Here they cannot.) EXACT WHERE IT MATTERS: each vertex is the stored corner (or a grid line between two, (min * (n - i) + max * i) / n) in the box's own coordinates, mapped in f64 and rounded to f32 ONCE; under a pure translation (rot the identity, scale 1) that is f32(P + x), and at P = 0 the stored coordinate itself. Every piece of one grammar root shares that root's P, rot and scale bit for bit and the stored face between two pieces is ONE number, so two cells of one root that share a face share its vertices exactly, rotated or not, and a closed shell stays watertight once coincident points are welded. A rotation's matrix entries within 2^-40 of 0 or 1 are snapped to them, so a quarter or half turn stored in f32 moves every vertex exactly. Two cells of DIFFERENT roots meet at f32(P1 + x1) and f32(P2 + x2), equal in the reals and possibly an ulp apart in f32 unless their P lie on a dyadic lattice. THE OUTPUT is one geometry: per cell, in input order, one block per face listed in `faces`, in that order; per face its own grid of points (no point shared between faces, so uv seams and flat normals are exact), laid in meshPrimitive's box order — a face normal to box axis a is a grid over axis (a + 1) % 3, fastest, then axis (a + 2) % 3 — and two 3-vertex "poly" triangles per quad, every one wound counter-clockwise SEEN FROM OUTSIDE the box; with the default `faces` (meshPrimitive's order +x, -x, +y, -y, +z, -z) and an identity transform a cell's points and triangles are those of a unit meshPrimitive box copied onto it. A MIRRORING scale (an odd number of negative components) turns every triangle's winding round, so the node reverses them all: every triangle still faces outward. THE UV (f32 tuple 2) IS THE FACE'S FRAME, the one shellSplit writes on a face of that side (along x up = outward): u runs ALONG, v runs UP, each 0..1 across the face, so seen from OUTSIDE every face of an unmirrored box reads left to right and bottom to top — on a wall up is the box's +y and along is -x on the south, +x north, +z west, -z east; the floor runs along +x and up +z (seen from below), the ceiling along +x and up -z (seen from above), all in the box's own axes, so a rotated building's walls read the same way from outside. A texture or a uv-driven pattern therefore lands the same way on all four walls, which the box primitive's uv (mirrored on three sides) does not. Under `flip` u is mirrored (1 - u), so a room seen from INSIDE reads the same way. A mirroring scale leaves the uv alone: every point of the box keeps its uv, so the faces MIRROR WITH THE BOX, as the uv of a mirrored mesh instance does — a mirrored box is the mirror image of the unmirrored one, its texture mirrored too (seen from outside every face reads mirrored, its uv wound clockwise), and so is a mirrored room under `flip`. A closed box is a closed solid: with all six faces, every edge is shared by exactly two triangles once coincident corner points are welded. THE FACES are named by side, shellSplit's names, the box's own sides: "floor" min y, "ceiling" max y, "south" min z, "north" max z, "west" min x, "east" max x; a face not listed is left OPEN, so ["south"] alone is a facade panel and every face but "floor" a box with no bottom. `subdivisions` cuts each face into a grid of quads (meshPrimitive's param: quads per BOX axis, a face taking the two that span it), plain or a FIELD resolved per cell — vec(max(floor(box("sx")), 1), 1, 1) gives every box about one column per unit of width. The input's TOPOLOGY and its VERTEX and PRIMITIVE attributes are neither read nor carried: the cells are its points. CARRIED: every point attribute of the cell except its transform (P, rot, scale) lands on EVERY point of that cell's mesh, strings included — its colour, its label, its `seed` (so a random drawn from the seed is one value per box), its boundsMin/boundsMax (so box names still read the cell's box on its mesh; a mesh point is NOT a cell: its P is a world vertex, its box the cell's local one) — together with the detail attributes. Written: P (world), `uv`, a `normal` (f32 tuple 3, flat and outward in the world: the face's own axis through the cell's rotation, its sign turned by a negative scale on that axis, a scale of -0 or 0 counting as positive) under `normals`, the side's FACE CODE under `faceAttr` (i32: shellSplit's codes, 0 floor, 1 south, 2 north, 3 west, 4 east, 5 ceiling, the box's own sides, so a material or a filter can pick the top faces, eq(attribute("boxSide"), 5)), and the input cell's index under `cellAttr`. A written name the cell also carries is refused rather than overwritten. A box of NO VOLUME on an axis (a plate, a slab of zero height), or a cell whose scale is 0 on an axis, is KEPT, as every box node keeps it: its two faces across that axis coincide back to back, so it draws from both sides, and the faces along that axis are zero-area triangles (which area-weighted sampling and the raycast mapping skip) — the counts are always cells * the listed faces' grids; list fewer faces to drop them. An inside-out or non-finite box is refused naming the cell. No inset or bevel: shrink a box first with transformBox (about its centre, pivotIn "cell") or offsetBox (by a distance per face), which keeps the box the mesh is built from on the cell as data. -0 is written +0. The output is CAPPED at 4194304 points in all (repeatPoints' and splitBox's cap, checked after a field subdivisions resolves), refused past that naming the cell the total ran out on. CPU only, as every box node: it builds topology whose size depends on each cell's subdivisions, which the GPU's elementwise field kernels do not express. Empty input gives an empty mesh.

**Category:** surface

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-split-box.json](../graphs/basics-split-box.json), [basics-apply-rules.json](../graphs/basics-apply-rules.json), [examples-facade.json](../graphs/examples-facade.json) — 4 total (`pcg graphs --node boxesToMesh`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `faces` | stringList | `["east","west","ceiling","floor","north","south"]` |  |  |  | The sides of each box to build, in the order every cell emits them, by shellSplit's names: "floor" (min y), "ceiling" (max y), "south" (min z), "north" (max z), "west" (min x), "east" (max x), each at most once and at least one. A side NOT listed is left OPEN: ["south"] is one panel per cell, every side but "floor" a box with no bottom. The default is meshPrimitive's box order (+x, -x, +y, -y, +z, -z), which gives each cell the points and triangles of a unit meshPrimitive box copied onto it (the uv follows the face frame instead; see the description). Decided once per cook. |
| `subdivisions` | vec3 | `[1,1,1]` | >= 1 |  | yes | Quads per BOX axis [x, y, z] — meshPrimitive's param, with its reading: whole numbers, at least 1, and each face takes the two axes that span it (the floor and ceiling x and z, the south and north walls x and y, the west and east walls y and z, all the box's own axes), so [1, 1, 1] is two triangles per face. A single number, plain or a field, broadcasts to all three. As a FIELD it is resolved per cell on the input, with the cell's box names — vec(max(floor(box("sx")), 1), max(floor(box("sy")), 1), 1) cuts every box into roughly unit quads (in the box's own units: a cell's scale stretches them). A count that is not a whole number of at least 1 is refused naming the cell (make it one with max(floor(...), 1)). |
| `flip` | bool | `false` |  |  |  | Reverse every triangle's winding (and the written `normal` with it), so every box faces INWARD — a room seen from inside it. meshPrimitive's `flip`. The uv's u is mirrored with it (1 - u), so seen from INSIDE every face of an unmirrored box still reads left to right and bottom to top (a mirrored room is its mirror image, as without `flip`); v is unchanged. |
| `normals` | bool | `false` |  |  |  | Write a `normal` point attribute (f32 tuple 3): each face's unit outward normal in the world (inward under `flip`) — the face's own box axis turned by the cell's rotation, its sign turned by a negative scale on that axis — on every one of its points: flat faces and hard edges, exact because faces share no points. Off by default, as on meshPrimitive: the renderer computes one from the triangles when none is stored, and a stored normal is only right until something moves P. Turn it on when this mesh is merged with one that carries a normal (mergePrimitives fills a missing column with (0, 0, 0), which a lit material renders black). |
| `faceAttr` | string | `"boxSide"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving each point's side as shellSplit's FACE CODE: 0 floor, 1 south, 2 north, 3 west, 4 east, 5 ceiling. It is "boxSide" rather than shellSplit's "face" because a shellSplit piece already carries "face" — the side of its PARENT it was cut from — and that is carried onto the mesh too, so both stay readable: the outer face of every wall piece is eq(attribute("boxSide"), attribute("face")). Empty writes none. Refused if the cell also carries the name. |
| `cellAttr` | string | `""` |  |  |  | Name of an i32 point attribute (tuple 1) receiving the INPUT CELL'S INDEX on every point of its mesh — copyToPoints' `targetIndexAttr`: the key that groups a mesh back into its boxes (partitionByAttribute, promoteAttribute). Empty (the default) writes none. Refused if the cell also carries the name. |

## brickConnectivity

Reads BRICKS on a stud lattice — one per point, its box in two point attributes read through the point's transform (world = P + rot * (scale * corner)), as packBricks writes them: P the brick's centre, a quarter turn about y where it was placed turned, scale its extents, the unit box. The rotation must be a whole number of quarter turns about y, refused naming the point otherwise, and each brick's world box is the axis-aligned box of its transformed corners — and says how they hold together: which clutch-connected piece each brick belongs to, and the build STEP at which it can be placed. Two bricks are joined when one sits directly on the other's top face with overlapping footprints, which is what a stud gripping the brick above does; side-by-side contact joins nothing. `island` numbers the pieces 0, 1, 2…, ordered by their lowest point IDENTITY (stored position bits plus `seed`), so it does not move when the input is shuffled. `step` is an ORDER YOU COULD BUILD IN, bottom up: the steps are the distinct bottom courses of the build in rising order, and at each one a brick is placed if it stands on the build's lowest course (the table) or clutches a brick already placed. A brick that hangs UNDER something — a plate held only by the floor laid on top of it — cannot be placed in its own course, because nothing is there to grip yet; it is placed in the step of the first brick above it that is, along with anything hanging under it in turn. So every brick, when it is placed, is attached to something already standing. A brick no order can attach — in a piece with no brick on the lowest course, which is a piece held by nothing — gets `step` -1, and its `island` is still numbered: the count of -1 steps is how many bricks a build would drop. Bricks must not overlap (two bricks claiming one cell are refused, naming both points) and every corner must land on the lattice, exactly as packBricks requires; a zero-volume box is not a brick and gets -1 for both. OUTPUT `out` is the input with two i32 point attributes added, `islandAttr` and `stepAttr`, the number of steps as a DETAIL u32 (`stepCountAttr`, the range a build-step slider runs over: steps 0 to stepCount - 1), and optionally the island count as a DETAIL u32; no point is moved, added or reordered, so a filterByExpression on `step` downstream shows the build as it stood after any step. INPUT `studs` (optional) takes packBricks' `studs` output — best with `studMode: 'all'` — whose `brickId` and `brickAbove` columns are indices into the bricks on `in`, so `in` must be that same packBricks' `out` with nothing dropped or reordered (an index past the end is refused, naming the stud). Wired, OUTPUT `studs` is those studs with two i32 point attributes added: `stepAttr`, the step of the brick the stud stands on (-1 when that brick is never attached), and `stepAboveAttr`, the step of the brick resting on it — -1 when there is none OR when that brick is never attached, both of which mean no partial build ever covers the stud — plus the same `stepCountAttr`. So 'stud is showing after step t' is `step` >= 0 and `step` <= t and (`stepAbove` < 0 or `stepAbove` > t), with no join downstream. Unwired, `studs` is an empty collection and `out` is unaffected. HALO: none — a piece is a fact about the whole build. Not GPU-eligible.

**Category:** attribute

**Inputs:** `in` (geometry), `studs` (geometry, optional)

**Outputs:** `out` (geometry), `studs` (geometry)

**Examples:** [examples-brick-house.json](../graphs/examples-brick-house.json) — 1 total (`pcg graphs --node brickConnectivity`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `minAttr` | string | `"boundsMin"` |  |  |  | POINT attribute (f32 or i32, tuple size 3) holding each brick's minimum corner in the point's OWN frame, as packBricks writes it (the unit box) and every box node reads boundsMin; mapped through P, rot and scale to its world box. Refused, naming the point, unless every world corner lands on the lattice. |
| `maxAttr` | string | `"boundsMax"` |  |  |  | POINT attribute (f32 or i32, tuple size 3) holding each brick's maximum corner in the point's own frame, on the same terms as `minAttr`. |
| `pitch` | vec3 | `[1,0.4,1]` |  |  |  | World size of one lattice cell: [stud, plate, stud], the same lattice the bricks were packed on. x and z must be equal and every component positive. |
| `origin` | vec3 | `[0,0,0]` |  |  |  | World position of a lattice corner, as for packBricks. |
| `islandAttr` | string | `"island"` |  |  |  | POINT attribute (i32) receiving each brick's piece: 0 for the piece holding the lowest point identity, then 1, 2… in the same order. -1 on a zero-volume box. May not be empty. An existing column of another shape under this name is refused rather than replaced. |
| `stepAttr` | string | `"step"` |  |  |  | POINT attribute (i32) receiving each brick's build step: the index of the bottom course at which it is placed, counting only courses at which some brick is placed, so steps run 0, 1, 2… with no gaps. -1 for a brick no order can attach (its piece never reaches the lowest course) and for a zero-volume box. May not be empty, and may not equal `islandAttr`. With `studs` wired, the same name is written on each stud: the step of the brick it stands on. |
| `stepAboveAttr` | string | `"stepAbove"` |  |  |  | With `studs` wired, the POINT attribute (i32) receiving each stud's COVER step: the step of the brick resting on it (its `brickAbove`), so the stud stops showing once that step is built. -1 when no brick rests on it (`brickAbove` below 0) and when the one that does is never attached (step -1) — either way no partial build ever covers the stud, so `stepAbove` < 0 reads as 'never covered'. Must not be empty, equal `stepAttr`, or name `brickId` or `brickAbove`, the index columns it is read through. Ignored when `studs` is not wired. |
| `stepCountAttr` | string | `"stepCount"` |  |  |  | DETAIL attribute (u32) receiving the number of build steps — the highest step plus 1, or 0 when there are no bricks (an empty input, or only zero-volume boxes; a brick on the lowest course is always placed, at step 0) — on `out`, and on `studs` when it is wired. It is the range a host's build-step slider runs over: every step from 0 to stepCount - 1 places at least one brick. Empty writes nothing; may not equal `islandsAttr`. |
| `islandsAttr` | string | `""` |  |  |  | Optional DETAIL attribute (u32) receiving the number of pieces; 1 is a build that lifts as one. Empty (the default) writes nothing. The same count packBricks' own `islandsAttr` gives for the bricks it packed. |

## bridgePaths

Joins each polyline on `from` to one polyline on `to` with a strip of quads, point i to point i: segment i of the one path, segment i of the other and the two rungs between their ends make one quad, emitted as two 3-vertex 'poly' triangles (the mesh convention every consumer here reads — surfaceSample, the uv and raycast transfers). This is the band between two lines: a road shoulder between a kerb line and its pathShift offset, a ribbon between two rails, an annulus between two concentric rings, one band of a loft between two sections. PAIRING: with `pairAttr` empty the i-th polyline of `from` pairs with the i-th of `to`, in primitive order, and different path COUNTS are refused naming both; with `pairAttr` set, the path on each side carrying the same key is the pair. A pair's two paths must have the SAME number of points (refused naming both counts and both primitives — resample both with pathResample mode 'count' to one count) and must both be open or both closed: two closed paths wrap, so the last quad joins the last points back to the first and the band is a ring with no seam in its geometry. THE PATHS ARE NOT RESAMPLED OR MATCHED: point i meets point i whatever their spacing, so two paths sampled by the same count along similar lengths give an even band, and an offset path that folded back on itself gives a folded band. OUTPUT: every `from` point of every pair, then every `to` point, each carrying its own input's point attributes (a name both sides carry must agree on type and tuple size, and fills with its default where one side lacks it); a `normal` (f32 tuple 3) the node writes — shared by the two points of a rung, the normalized sum of the unit normals of the (at most two) quads meeting at that rung, so a band that bends shades round; a rung whose quads have no area or cancel borrows the nearest earlier rung that has one, or the first — and a `uv` (f32 tuple 2): `u` is each side's own normalized arc length, `v` is 0 on `from` and 1 on `to`. On a closed pair `u` returns to 0 across the closing quad, as it does on sweepProfile's closed tubes. Every triangle carries the primitive attributes of its `from` path; `to`'s primitive attributes and detail are dropped. FACING: with `from` on the right of the direction of travel and `to` on its left (seen from above), the band faces UP — the triangles wind so that (along `from`) x (from -> to) is the face normal — and `flip` turns it over. Single-sided like any mesh: flip it, or bridge the pair twice, for a band seen from both sides. `normal` and `uv` are reporting slots — an input already carrying either at a different shape is refused by name. Deterministic: pairs come out in `from` primitive order, quads in path order.

**Category:** surface

**Inputs:** `from` (geometry), `to` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-bridge-two-paths.json](../graphs/basics-bridge-two-paths.json) — 1 total (`pcg graphs --node bridgePaths`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `pairAttr` | string | `""` |  |  |  | Name of a scalar PRIMITIVE attribute, on BOTH inputs, that says which `to` path each `from` path is bridged to: the paths carrying the same key are a pair. A key is a whole number (setAttribute type 'i32' on the primitive domain) or a string compared by value — the rules pointsToPath's `groupAttr` sets. Every key must appear exactly once on each side; a key repeated on one side, or present on only one, is refused by name. Pairs still come out in `from` primitive order. Empty (the default) pairs the i-th polyline of `from` with the i-th of `to` — right whenever both sides came from the same paths through nodes that keep primitive order (pathShift, pathResample, transformPoints), and the reason this is optional. |
| `flip` | bool | `false` |  |  |  | Turn the band over: reverse every triangle's winding and negate the written `normal`, so the band faces the other way. The default faces (along `from`) x (from -> to): with `from` on the right of the direction of travel and `to` on its left, a flat band faces up. |

## connectByIndex

Builds one 2-vertex `polyline` per point, from that point to the point its `index` names — the edge set a PARENT POINTER describes. Built over the SAME points that arrived, so every point attribute survives and a junction is genuinely one point shared by every edge that meets there. This is the constructor for anything that GREW: a tree's branches, a root system, a river network, a dendrite, a crack. WHY IT IS A NODE AND NOT A RECIPE: `pointsToPath` is the only other path constructor and it PARTITIONS — `groupAttr` is read once per point and that point joins exactly one group — so its groups are vertex-disjoint chains and every point ends with degree at most 2. A star (1 -> 0, 2 -> 0, 3 -> 0) can emit at most two of its three edges under ANY assignment of group keys, because the centre belongs to one chain only. Branching is precisely the case that excludes. THE SHAPE IS NOT THE GAP — `connectPoints` already gives a point three incident edges and more, and this file's own header says a degree-5 point is expressible today. What no shipped node can do is be HANDED the answer: `connectPoints` asks its question in SPACE and decides the pairs itself, and `transferByIndex` IS handed an index but spends it on VALUES and promises it changes no topology. DIRECTION IS THE PAYLOAD, and this is where it differs from `connectPoints` deliberately: vertex 0 of each edge is the point that named the index and vertex 1 is the point it named, so child-to-parent is recoverable from the topology itself rather than needing a separate column. `connectPoints` orders its endpoints by key because a proximity edge has no direction to preserve; a parent pointer has nothing else. Edges come out in POINT ORDER, one per point that names a usable parent. A ROOT names `rootValue` (-1 by default, the sentinel `copyToPoints`' `targetIndexAttr` writes and `quotaRebalance` uses for 'stays') and contributes no edge — that is ordinary data, not a miss, which is why it is a separate param from `outOfRange`: a forest of several trees is a normal input here, and a node that could not say 'this one has no parent' could not describe one. THE INDEX IS AN ORDINAL, NOT AN IDENTITY, and it carries `transferByIndex`'s trap in a sharper form: a filter, a sort, a resample, a partition or a `mergePoints` anywhere between the node that COMPUTED the pointers and this one renumbers every point, and index 7 is then whatever landed seventh. There the damage is a wrong value; here it is a wrong EDGE, and a plausible-looking one. Compute the pointers and spend them with no renumbering step in between. PARTITIONING: an edge reads one stored index and the point it names, and consults no third point, so a cell holding both decides that edge exactly — emit it from the cell owning its FIRST vertex under the half-open rule and the cells tile the network with no duplicate and no gap, exactly as `connectPoints` documents. The halo is whatever bound the PRODUCER of the index column already needed, and is not this node's to invent; that is what separates this from the two things Stretch actually cut — CHAINING degree-2 runs into polylines, which is not partition-invariant at the primitive domain, and `findPath`, for which no finite halo suffices. (`maxDegree` itself is recorded there as halo-exact and merely unbuilt, not refused.) ONE CONDITION, and it is the ordinal again: `connectPoints` pairs by POSITION, which survives a repartition, while this node pairs by ORDINAL, which does not. So the argument holds only while the pointers are produced in the SAME numbering this node reads them in — a partitioned cook must compute its pointers inside the cell that spends them, never across a split. Any existing topology on the input is REPLACED and its vertex and primitive attributes drop with it, and the downstream rule `connectPoints` states applies unchanged: a network routed through any node that REMOVES points arrives as a plain cloud.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [examples-coral.json](../graphs/examples-coral.json) — 1 total (`pcg graphs --node connectByIndex`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `index` | f32 | `-1` |  |  | yes | Which point each point links to, as an ordinal counting from 0, resolved on the point domain. TRUNCATED TOWARD ZERO before it is read, on `transferByIndex`'s rule and for its reason, so 3.9 and 3.0 both name point 3. AS A FIELD THIS IS THE POINT OF THE NODE: `attribute("parent")` spends a column an earlier stage settled, which is how a growth loop's `targetIndexAttr` or a `sampleNearestPoint` `indexAttr` becomes an edge. As a plain number it is one parent shared by every point — a star, and mostly useful for a test — with one catch worth stating: the point it names then names ITSELF, which the default `outOfRange` refuses, so a plain index wants `outOfRange: "skip"` alongside it. Note also that the shipped defaults (`index` -1 against `rootValue` -1) make every point a root, so an unconfigured node emits no primitives at all rather than failing. PRECISION: a field resolves to an f32 column and f32 represents every integer only to 16,777,216, so a pointer computed beyond that lands on a neighbouring integer — the arithmetic that produced it is where the precision went, not this node, and a cloud that large wants an i32 attribute read straight through `attribute()`. NON-FINITE IS REFUSED before this node reads a thing, through two different doors: a FIELD is caught by the shared resolver guard, which names this param and the offending element and says how to guard the expression, while a PLAIN number is caught by the param schema wherever a graph is loaded, patched or exposed. `execute` itself has no check, because neither door can be walked past. NaN and the infinities are what a broken sub-expression produces, and none of them is a pointer under any reading. If a broken pointer should be a root rather than a failed cook, say so — map it to `rootValue` with a select() and it is data again. |
| `rootValue` | f32 | `-1` |  |  |  | The index value meaning THIS POINT HAS NO PARENT: it contributes no edge, and that is not a miss. -1 by default, matching the sentinel `copyToPoints`' `targetIndexAttr` writes and `quotaRebalance` uses for 'stays'. Compared AFTER the same truncation the index takes, so -1.5 and -1 are the same root. A rootValue that lands INSIDE [0, pointCount-1] is legal and silently drops every edge naming THAT POINT, counting no miss, because a root is not a miss — it is a sentinel, and one a real ordinal could equal is an ambiguous sentinel. -1 cannot collide with any ordinal, which is why it is the default. A forest of several trees, a growth loop's seed point, and a network still being built all need to say this, which is why it is separate from `outOfRange`: folding the two together would make 'no parent yet' indistinguishable from 'this pointer is broken', and the first is the ordinary state of the data while the second is a defect worth stopping for. |
| `outOfRange` | enum | `"error"` |  | `error`, `skip` |  | How a pointer that is neither usable nor `rootValue` is read: one outside [0, pointCount-1], or one naming the point ITSELF, which would be a 2-vertex polyline whose two vertices are the same point and is never what an author meant. 'error' (the default) refuses the cook naming the point and the value, which is right when the pointers were COMPUTED by the graph and a bad one is a defect upstream. 'skip' emits no edge for that point and counts it in `missCountAttr`, which is right when the pointers are DATA the graph does not control — read from a table, carried across a cell boundary, or produced by a stage that legitimately does not resolve every one. THERE IS NO 'clamp' OR 'wrap', and their absence is deliberate: `transferByIndex` can clamp because the nearest VALUE is a defensible answer, but the nearest EDGE is not — clamping would silently wire a whole subtree onto point 0 and the result would look like a real network. |
| `degreeAttr` | string | `""` |  |  |  | Name of a u32 point attribute receiving each point's DEGREE — how many emitted edges touch it, counting BOTH directions, so a fork with three children and one parent reads 4 and a tip reads 1. Empty (the default) writes none. This is how a grown structure is read back: tips are degree 1, a root with no parent is degree 1 too, and anything above 2 is a fork. The shape is this node's to pick (u32, tuple 1), so a name the input already holds under a DIFFERENT shape is REFUSED rather than overwritten — writing it would delete that column outright and the cook would still look fine. A same-shape column IS reused and reset, so re-running this node over its own output is fine. |
| `lengthAttr` | string | `""` |  |  |  | Name of an f32 PRIMITIVE attribute receiving each edge's length in world units. Empty (the default) writes none. On a grown structure this is the segment length, which is what a taper or a cost driver wants. The shape is this node's to pick (f32, tuple 1), so a name already present on the output's primitive domain under a different shape is REFUSED — which in practice means `primtype`, the string attribute that marks these primitives as polylines and without which nothing downstream would recognise them. |
| `missCountAttr` | string | `""` |  |  |  | When non-empty, writes the number of points whose pointer was SKIPPED into a u32 DETAIL attribute of this name. Always 0 under `outOfRange` 'error', which cannot reach this. ROOTS ARE NOT COUNTED — a root is data, not a miss. Empty = don't record. A count is a cook statistic and cannot be filtered on; for WHICH points, read `degreeAttr` and compare against what you expected. This is a reporting slot whose shape this node picks (u32, tuple 1), so a name the detail domain already holds under a different shape is REFUSED rather than deleted and re-added — give it a name of its own (a "__" prefix marks it internal) or removeAttribute the clash first. |

## connectPoints

Connects a point cloud into a NETWORK: one 2-vertex `polyline` primitive per edge, built over the SAME points that arrived, so every point attribute survives and a junction is genuinely one point shared by every edge that meets there. This is how you get roads between district centres, a trail net between camps, or a triangulated-looking scaffold to displace. There is no edge domain and none is needed — per-edge values come from promoteAttribute point->primitive (`min` for a width, `first` for a kind) and setAttribute on domain 'primitive', and per-junction values from promoteAttribute primitive->point (`max`). mode 'radius' connects every pair closer than `radius`. mode 'relativeNeighborhood' keeps such a pair ONLY when no third point is closer to BOTH of its endpoints than they are to each other (the lune test): that thins a dense blob into a road-like net that still CONTAINS a minimum spanning tree — so the network stays connected wherever the radius does — while leaving the cycles a road layout wants and a tree does not have. mode 'gabriel' applies the other classical test — no third point inside the SPHERE on the pair as diameter — which disqualifies strictly fewer pairs, so relativeNeighborhood is a SUBSET of gabriel and gabriel is a subset of the Delaunay edges. It is the mode for a CELLULAR subject rather than a road one: it keeps the short cross-links that close small polygons, so a scatter comes out as plots, cracked ground or leaf venation instead of a branching net. It contains a minimum spanning tree for the same reason relativeNeighborhood does. Distances are 3D over P and the test is STRICT (d < radius), which is what makes this node's answer independent of how the cloud was windowed: a pair at exactly `radius` is not an edge. Edges come out in a canonical order fixed by the POINTS (identity, then position bits, then seed) and never by the order they arrived in, and each edge's FIRST vertex is its lower-keyed endpoint — reorder the input and you get the same network, permuted. PARTITIONING: an edge reads two stored positions and no third point, so a cell that also holds every point within `radius` of its own rectangle decides its edges exactly; emit an edge from the cell that owns its FIRST vertex under the half-open rule (filterByBounds' 'halfOpen'), and the cells tile the network with no duplicate and no gap. The wiring is three NODES, so a partitioned network cook is a serializable graph and needs no host code: widen the cell's rectangle by `radius` — or, when `radius` is a field, by the GLOBAL MAXIMUM it can return anywhere in the world — and clip the cloud to it with filterByBounds ('halfOpen'), run this node, then run filterPrimitivesByBounds on the UNWIDENED rectangle with vertex 'first' and the same 'halfOpen' boundary — that node keeps the primitives whose FIRST vertex lies back inside the cell, and it is one of the two filters in the library that trim topology instead of dropping it. The relativeNeighborhood witness lies inside the pair's own neighbourhood, so it needs no wider halo, and neither does the gabriel witness: a point inside the sphere on the pair as diameter is at most `d(i,j)` from either endpoint, which the radius already bounds. Any existing topology on the input is REPLACED, and its vertex and primitive attributes drop with it. Downstream, any node that can REMOVE points drops topology — filterByDensity, filterByBounds, filterByAttribute, filterByExpression, selfPrune, partitionByAttribute — and so do mergePoints and repeatPoints, so a network that passes through one stops being a network — use mergePrimitives to combine this node's output with another network, an authored path or a mesh, which concatenates points, vertices AND primitives and renumbers the references; category is not the rule, since projectToPlane is categorised `filter` and PRESERVES topology, and so do filterPrimitivesByBounds and filterPrimitivesByAttribute, which filter the PRIMITIVE domain and are the nodes to reach for when a network has to be cut down rather than a cloud — the second tests a primitive attribute, so a network thinned by its own `lengthAttr` (or by a promoted or setAttribute-authored per-edge value) stays a network, and the thinning happens before anything downstream pays for the edges it removes. degreeAttr and lengthAttr are reporting slots whose shape this node picks, so pointing either at an existing attribute of a DIFFERENT shape is refused rather than silently deleting it.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-filter-primitives-by-attribute.json](../graphs/basics-filter-primitives-by-attribute.json), [basics-connect-by-reach.json](../graphs/basics-connect-by-reach.json), [basics-merge-primitives.json](../graphs/basics-merge-primitives.json) — 10 total (`pcg graphs --node connectPoints`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"radius"` |  | `radius`, `relativeNeighborhood`, `gabriel` |  | Which pairs become edges. 'radius' connects every pair closer than `radius` — dense, and the count grows with the square of the point count. 'relativeNeighborhood' additionally requires that no third point is closer to BOTH endpoints than they are to each other (the lune test), which keeps a sparse, road-like net (it contains a minimum spanning tree, so it does not disconnect what the radius reached, and it keeps cycles, so it is a network rather than a tree). 'gabriel' requires instead that no third point lies inside the SPHERE having the pair as its diameter, which is a strictly weaker condition than the lune: every relativeNeighborhood edge is also a gabriel edge, so gabriel sits BETWEEN the two other modes in density and likewise contains a minimum spanning tree. Reach for it when relativeNeighborhood thins a layout too far — it keeps the short cross-links that close small cells, which is what makes it read as cracked ground, leaf venation or plot boundaries rather than as a road net. All three modes read the same radius neighbourhood and are bounded by the same edge limit, so neither test costs a wider search than 'radius'. |
| `radius` | f32 | `1` | >= 0 |  | yes | Largest distance that can become an edge, in world units, tested STRICTLY: a pair at exactly `radius` is NOT connected. That strictness is deliberate and is what makes a partitioned cook exact — a neighbour lying exactly on a cell's far face is excluded from the cell by the half-open ownership rule, and under a strict test it is not an edge of anything that cell owns either, so the two conventions cannot disagree. 0 builds no edges. As a FIELD it is a PER-POINT REACH, and a pair becomes an edge when it is closer than the LARGER of the two reaches — the same rule selfPrune's minDistance uses, and for the same reason: the SMALLER would let a big point be crowded by a small one, and the SUM would double the spacing of an evenly-sized cloud, so neither agrees with the same number passed plainly. That rule is what keeps the relation SYMMETRIC. Without one a per-point radius makes 'A is near B' and 'B is near A' two different tests and an edge depends on which endpoint asked, which is why a field here needs a stated pair rule and not merely a column. A per-point reach of 0 or less connects that point to nothing, though a bigger neighbour can still reach IT. A NON-FINITE reach is REFUSED rather than read as nothing: this param takes the guarded resolver, so a NaN or an Infinity stops the cook naming the offending element, unlike pointNeighborhood's radius, where both are documented values. The distinction is which mistake is likelier — a reach is arithmetic an author writes, and a NaN there is a broken expression rather than a request for no edges. TWO COSTS travel with a field, both cost and neither correctness. The candidate scan runs at the WIDEST reach in the cloud, since either endpoint may be the larger, so the edge ceiling is measured on those candidates rather than on the edges that survive. And under a partitioned cook the halo is no longer `radius` but the GLOBAL MAXIMUM this field can return anywhere in the world — a bound to be derived rather than measured, because the cloud a cell sees has already been clipped by the halo being sized. Take a constant times the range of whatever drives it (a noise is in [-1, 1], so `2 + 3 * noise` maxes at 5) and widen by that; underestimating does not throw, it drops the long edges at the seams only. |
| `degreeAttr` | string | `""` |  |  |  | Name of a u32 point attribute receiving each point's DEGREE — how many emitted edges touch it (0 for an isolated point). Empty (the default) writes none. Use it to size junctions, or to find the dead ends of a network with filterByAttribute. The shape is this node's to pick (u32, tuple 1), so a name the input already holds under a DIFFERENT shape is REFUSED, not overwritten: writing it would delete that column outright and the cook would still look fine (degreeAttr "P" would leave a cloud with no positions). A same-shape column IS reused and reset, so re-running this node over its own output is fine. |
| `lengthAttr` | string | `""` |  |  |  | Name of an f32 PRIMITIVE attribute receiving each edge's length in world units. Empty (the default) writes none. Handy as a width or cost driver, and as a filter key once the network is promoted. The shape is this node's to pick (f32, tuple 1), so a name already present on the output's primitive domain under a different shape is REFUSED — which in practice means `primtype`, the string attribute that marks these primitives as polylines and without which nothing downstream would recognise them. Note that the input's own primitive attributes are dropped by the topology replacement before this is written. |

## copyToPoints

Copies the source point cloud onto every target point (output count = source points * target points, grouped by target). Set `sourceGroupAttr` and `targetGroupAttr` and each target instead takes only the source points whose group key it asks for, which is the same node stamping a DIFFERENT subset per target rather than the whole cloud. Transforms compose per copy: P = targetP + targetRot * (targetScale * sourceP), rot = targetRot * sourceRot (quaternion product), scale = targetScale * sourceScale (componentwise), and each copied seed is hashCombine(sourceSeed, targetSeed). All other source point attributes are carried through unchanged — including a DIRECTION such as a mesh's `normal` or a path's `tangent`, which therefore keeps pointing the source's way on every copy unless `rotateAttrs` names it, and then it turns by the copy's target rotation on the point, vertex or primitive domain; missing transform attributes are treated as identity. `targetNames` additionally carries named TARGET point attributes onto the copies: every copy in a target's block receives that target's value, in a column keeping the target's type, tuple size and default. That is what lets copies vary by what the author computed on the target cloud — a species tag, an age, a noise sampled per target — since the copies are otherwise identical in everything but placement. The composed transform attributes cannot be carried, a name the source already carries is refused rather than silently overwritten, a name repeated in the list is refused, and a name absent from the target is an error. `targetIndexAttr` writes the target's INDEX rather than one of its attributes, which is what makes "one thing per target" — one path per anchor, one group per instance — expressible without an upstream setAttribute whose only job was to give this node something to carry. `sourceGroupAttr` and `targetGroupAttr` are PER-TARGET SOURCE SELECTION, the pair that turns "every target takes every source point" into "every target takes the source points it names": without them a vocabulary in which each target wants a different subset has to stamp the whole cloud and filter the wrong copies away, which is quadratic in a library nobody uses all of. A target whose scale MIRRORS (an odd number of negative components) reverses the winding of every copied face under topology "keep" and reflects the `rotateAttrs` directions, so a mirrored copy of a solid still faces outward (`mirrorAware`, on by default). The source's TOPOLOGY is dropped by default — an array of a path comes out a bare cloud — and `topology "keep"` re-emits every source primitive once per target instead, which is what makes the array of paths a set of paths without rebuilding them downstream.

**Category:** point op

**Inputs:** `source` (geometry), `target` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-copy-to-points.json](../graphs/basics-copy-to-points.json), [basics-self-similar-frond.json](../graphs/basics-self-similar-frond.json), [basics-spiral-stair.json](../graphs/basics-spiral-stair.json) — 16 total (`pcg graphs --node copyToPoints`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `targetNames` | stringList | `[]` |  |  |  | Target point attributes to carry onto the copies, in any order. Each copy in a target's block gets that target's value, and the column arrives with the target's type, tuple size and default. An empty list carries nothing, which is the default and not an error. Three kinds of name are refused rather than resolved silently: "P", "rot", "scale" and "seed", because they are composed per copy and already hold the target's contribution (copy one to another name on the target with setAttribute and carry that to get the raw value); a name repeated in the list; and a name the source also carries, because the two would write the same column. A name absent from the target is an error listing what the target does carry. |
| `targetIndexAttr` | string | `""` |  |  |  | Name of an i32 point attribute to write the TARGET INDEX into — 0 for every copy that landed on the first target point, 1 for the second, and so on. Empty (the default) writes nothing. This is the key downstream nodes group by: pointsToPath's `groupAttr` turns "the copies of one target" into one path per target, and partitionByAttribute turns them into one item each. The node already computes this index to place the copies, so naming it here replaces the setAttribute writing `{"fn":"index"}` on the target purely so `targetNames` had something to carry. The column is i32, tuple size 1, default -1 (which no copy ever gets, so an element appended later reads as belonging to no target). That stays true under `sourceGroupAttr`/`targetGroupAttr` selection, and it is worth saying why, because selection is exactly what could have broken it: a target that matches no source group contributes ZERO copies rather than a copy carrying some placeholder, so its index is simply a value this column never holds — -1 still means "no target" and not "the target that took nothing". What selection does change is that a target index can be MISSING from the output entirely, so a downstream grouping on this column sees fewer groups than the target cloud has points (pointsToPath's `shortGroups "skip"` is the setting that expects exactly that). Refused for the same three reasons `targetNames` refuses a name: "P", "rot", "scale" and "seed" are composed per copy, a name the source already carries would have two writers, and so would a name `targetNames` is carrying. |
| `rotateAttrs` | stringList | `[]` |  |  |  | SOURCE direction attributes (f32, tuple size 3) to turn with each copy — a mesh's `normal`, a path's `tangent` or `curveNormal`, any axis the graph wrote. Without this every attribute but the composed transform rides onto the copies unchanged, so a direction comes out pointing the SOURCE's way on every copy even though the copy's positions and `rot` turned: a box copied onto a target turned 90 degrees is lit as if it had not turned. Each named column is rotated by its copy's TARGET rotation — the target's `rot`, identity when the target has none — which is exactly the rotation P goes through (P = targetP + targetRot * (targetScale * sourceP)), so the direction stays in the frame the copy's positions are in. The SOURCE point's own `rot` is not applied, because source P is not turned by it either. ROTATION ONLY, plus the SIGNS of the target's `scale` under `mirrorAware` (the default), which is what keeps a normal outward on a mirrored copy: the length is kept (up to f32 rounding; nothing is renormalized, a zero vector stays zero) and the MAGNITUDES of the target's `scale` are NOT applied. Under a uniform target scale that is exact for any direction. Under a NON-UNIFORM target scale it is not: a surface normal would need the inverse-transpose of that scale (and a tangent the scale itself), then a renormalize, and this param applies neither — scale uniformly, or recompute the directions downstream. DOMAINS: a name is looked up on the source's point, vertex and primitive domains and turned on every one of them that carries it, each copy of an element by the target its block landed on. The vertex and primitive domains reach the output only under `topology "keep"`, so under "drop" (the default) only the point domain is searched, and a name the source carries ONLY on its vertex or primitive domain is an error rather than a silent no-op — the likely intent was `topology "keep"`. The detail domain is never carried, so never searched, and neither is a `targetNames` column: that is the target's own value, already in the target's frame. Refused rather than resolved silently: "P", "rot", "scale" and "seed" (composed per copy — P and rot already carry the target's rotation, so naming one would apply it twice, and scale and seed are not directions); "boundsMin" and "boundsMax" (extents in the point's own frame, which the composed `rot` already turns); a name repeated in the list; a name no searched domain carries; and a column of that name that is not f32 with tuple size 3 — including one on a dropped domain, so the fix offered is never "keep" when "keep" would fail next. Every refusal but the repeat lists the source's f32 tuple-3 attributes per domain. Nothing is added, renamed or reordered — the named columns keep their place, type and default, and only their values turn — so an empty list, the default, leaves every output byte-identical to what this node produced before the param existed. |
| `sourceGroupAttr` | string | `""` |  |  |  | Name of a scalar SOURCE point attribute holding each source point's group key — the half of per-target source selection that says what each source point IS. Set it together with `targetGroupAttr` (the key each target ASKS FOR) and a target receives only the source points whose key equals its own; leave BOTH empty, the default, and every target receives every source point exactly as before. Setting one without the other is refused rather than half-applied, because the two lenient readings — ignore it, or match everything against nothing — differ by the entire output. A NUMERIC key must be a whole number, the rule `pointsToPath`'s `groupAttr` sets and for its reason: a key is an IDENTITY, two values a ULP apart would be two groups, and CPU/GPU parity is a tolerance rather than an equality — so write ids with setAttribute type 'i32' (which truncates), and a fractional value is an error naming the point. A STRING key names the group instead, which is the usual thing a group is (an asset id, a pose name, a species), and it compares BY VALUE and never by string-table index, so the same word selects the same points in every geometry and every cell. Both sides must be the same kind: a string column against a numeric one can never match and is refused rather than cooking to nothing. This column is an ordinary source attribute and rides onto the copies like any other; the key does not disappear because it was used. |
| `targetGroupAttr` | string | `""` |  |  |  | Name of a scalar TARGET point attribute naming which source group that target takes — the half of per-target source selection that does the asking. Used only together with `sourceGroupAttr`, under the key rules stated there. What it buys is the case this node could not express: when each target wants a DIFFERENT subset of the source, the alternative is to stamp the whole source on every target and filter the wrong copies away, which costs sourcePoints * targetPoints intermediate points to keep a few thousand — the measured racetrack case stamped 776,000 copies to keep 1,900. With this set the node emits only the copies that survive, so the stage becomes linear in the answer. Everything else is unchanged: the copies still come out in contiguous per-target blocks, in ascending SOURCE INDEX within a block, and `targetNames`, `targetIndexAttr` and the composed transforms all behave as they do without selection — selection REMOVES copies from that layout, it never reorders what is left, and it never perturbs the seed of a copy that would have existed anyway (a copy's seed is hashCombine(sourceSeed, targetSeed), which names the pair and not the slot). A target whose key matches NO source group takes zero copies and that is legal, not an error, for the reason `pointsToPath`'s `shortGroups "skip"` gives: a selection key is normally DATA — resolved from a catalogue, drawn from a noise, chosen per placement — so which keys a cell's targets ask for is unknowable at graph-build time, and a cell asking for a pose this source does not carry must not fail the whole cook. If a missing key IS an authoring error in your graph, catch it upstream where the population is known rather than here where it is data. |
| `mirrorAware` | bool | `true` |  |  |  | Honour a MIRRORING target transform. A target whose `scale` has an odd number of negative components (a negative determinant — `[-1, 1, 1]` is the mirror image across the target's local YZ plane) produces a mirror-image copy, and a mirror reverses handedness: kept as it was, every copied face's winding would describe the inside of the solid and a back-face-culled render shows the copy inside out. With this on (the default), under `topology "keep"` each 'poly' primitive of a mirrored target's copy has its vertex order reversed about its first vertex — (v0, v1, ..., vn-1) becomes (v0, vn-1, ..., v1), so a fan from v0 keeps its root — with its vertex attributes following their corners; polylines are NOT reversed, because a path's vertex order is its direction of travel and its `curveU`, not a winding (untagged primitives are read as polylines and left alone too). And every `rotateAttrs` direction goes through the SIGNS of its target's scale before the target's rotation — the reflection part of the transform, which is its own inverse-transpose, so a mirrored surface normal comes out a proper OUTWARD normal that agrees with the reversed winding, and a tangent comes out along the mirrored path; the MAGNITUDES of the scale are still not applied (see `rotateAttrs`). That sign flip applies to any negative component, mirror or not: `[-1, -1, 1]` is a half turn, and its directions turn with it. Off, a mirrored copy keeps the source's winding and directions — the behaviour before this param existed. A cook whose target scales have no negative component is byte-identical either way. The copied `scale` attribute carries the negative components as before, so an instance renderer composing its own matrix still mirrors the instance. |
| `topology` | enum | `"drop"` |  | `drop`, `keep` |  | What happens to the SOURCE's topology — the vertices and primitives built over the source's points. 'drop' (the default) copies POINTS only: an array of a path comes out a bare cloud with the paths gone, which is why the copies have to be rebuilt downstream (targetIndexAttr, then a pointsToPath grouping on it). 'keep' re-emits source primitives onto the target blocks instead, which is the whole difference between an array of points and an array of paths. WITHOUT SELECTION (`sourceGroupAttr` and `targetGroupAttr` both empty) that is every source primitive once per TARGET, and the arithmetic is closed: the copies are laid out in contiguous blocks of nSource (copy s of target t is point t * nSource + s), so primitive p of block t walks exactly the points its original walked, t * nSource further on, and a source with N primitives always yields nTarget * N, in target-block order, nothing filtered and no primitive reshaped. That is what mergePrimitives produces from nTarget copies of the source. WITH SELECTION both of those identities are gone, and they have to be: a target holds only the source points its key asked for, so there is no fixed block stride, and a vertex referencing a point the block did not take has no point to renumber onto — it cannot be carried, and carrying it anyway would produce an index setTopology's bounds check accepts as some OTHER target's point. What replaces them is the POINT FILTERS' survival rule, quoted rather than invented: a primitive is re-emitted for a target only when ALL of its points are in that target's block. So a source primitive whose points carry two different keys belongs to no block and is re-emitted for none of them (put the key on whole primitives, not across them), and the primitive count is the sum over targets of what each target's key kept — not a product of anything. What does NOT change is the order: within a block the surviving primitives keep ascending source order and each keeps its own vertices in their own order, and the blocks still follow target order. One further difference is visible only on a source whose vertex array does not tile: an unselected block copies that array verbatim, gaps and out-of-order primitive ranges included, while a selected block is compacted to the surviving primitives' own vertices in primitive order — what gatherPrimitives produces. Everything setTopology and setPolylineTopology build already tiles in order, so for those the two are the same array. A MIRRORED target's block (see `mirrorAware`) is compacted the same way, with or without selection, because reversing a face's winding needs each primitive to own its vertex range. The source's VERTEX and PRIMITIVE attributes come along, each copy carrying the original's values (a per-primitive width, a per-vertex uv, and `primtype`, so the copies stay samplable as what they are). The TARGET's own topology is never read under either setting — the target contributes point transforms and, through targetNames/targetIndexAttr, point attributes, while its primitives describe points that are not in this output at all. The POINT domain is IDENTICAL under both settings — same points, same order, same attributes, same identities — so this param only ever ADDS information, and neither targetNames nor targetIndexAttr (which write point columns) can be disturbed by it, with or without selection. The DETAIL domain is carried under NEITHER setting, for the reason mergePrimitives gives for dropping it: there are two inputs, each has a detail domain, and choosing between them would be a guess. On IDENTITY, because it decides what per-copy randomness does: a primitive is named by the fold of its own points' identities, and a point's identity is its position bits plus its `seed` — both of which this node composes per copy (P from the target's transform, seed from hashCombine(sourceSeed, targetSeed)). So the copies of one source primitive are DISTINCT primitives, one per target that re-emitted it, and a randomField on the primitive domain draws a different value for each, which is what 'one variation per copy' needs. The exception is the one mergePrimitives documents: two targets sharing a position AND a seed produce copies that are the same points, hence ONE primitive to every identity-keyed decision — give coincident targets distinct seeds. |

## dataInput

Emits exactly the data items in its `items` param, unchanged — the bridge for injecting externally produced data (for example parent-cell outputs in the hierarchical runtime) into a graph. Items hash by rev in memo keys, so caching stays correct as items are swapped.

**Category:** io

**Inputs:** *(none)*

**Outputs:** `out` (any)

**Examples:** *(no corpus graph uses it)*

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `items` | items | `[]` |  |  |  | Data items to emit, bound at runtime via graph.setParam (the World binds parent-cell outputs here, per cell, at bind time). Live DataItems are runtime-injected and never serialized: a serialized graph carries an empty item list, and items must be re-bound after deserialization. |

## extrudePolygon

Treats every CLOSED polyline primitive as a polygon boundary and sweeps it along a direction into 3-vertex 'poly' triangles: a footprint becomes massing, a boundary loop becomes a wall. This is the node a pipeline that already computed its plots has been waiting for — a closed quad per lot renders as four hairlines until something gives it a third dimension. Output carries P, a `normal` (f32 tuple 3) and a `uv` (f32 tuple 2) the node writes itself, plus every INPUT POINT attribute copied onto the points that came from it and every input PRIMITIVE attribute gathered onto the triangles, so a per-lot `lotId` or `districtKind` survives; input VERTEX attributes are dropped. `normal` and `uv` are reporting slots — an input already carrying either at a different shape is REFUSED by name rather than silently deleted. On the walls `u` runs 0..1 around the boundary by ARC LENGTH (so a plot with one long side does not stretch its texture there) and `v` 0..1 from bottom to top; on the caps both run 0..1 across the footprint's own bounding box in the plane perpendicular to the direction. Walls, top cap and bottom cap keep SEPARATE points, so the edge where a roof meets a wall stays a crease instead of being shaded round. Caps are exact for any SIMPLE footprint, convex or not: a convex one is a fan from the boundary's first point (n - 2 triangles), a concave one (an L, a U, a courtyard block) is ear-clipped — deterministically, adding no points — as seen along the extrusion direction. HOLES: a closed loop whose i32 primitive attribute `holeOf` is 0 or more is a HOLE through the outline whose primitive index it holds (-1 marks an outline) — the convention polygonBoolean and splitPolygons write, so their output extrudes with its courtyards and stair wells as it comes; setAttribute writes it by hand. The caps are cut around each hole, and each hole gets walls of its own, facing INTO the hole. The outline decides the whole polygon: its direction (a 'vector' field is read on the OUTLINE's primitive, 'polygonNormal' is the outline's own normal), which side the solid is on (`distance` summed over every loop), and the cap normals and uv box; every cap triangle carries the outline's primitive attributes, each hole's walls the hole's. Loops may wind either way. A hole with a point outside its outline (seen along the direction), a `holeOf` naming no closed loop, and a hole of a hole are refused by primitive; crossing edges and holes overlapping each other are not searched for. A hole of zero area cuts nothing and still gets its walls. Without a `holeOf` attribute every loop is a polygon of its own. A self-crossing boundary is not refused and its caps describe nothing. An OPEN polyline is refused by name: extrusion is not defined on one, and the fix is pointsToPath with `closed: true`. Winding is derived from the polygon's own Newell normal against the direction and against the sign of `distance`, so a footprint wound either way, extruded either way, comes out facing outward.

**Category:** surface

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-extrude-polygon.json](../graphs/basics-extrude-polygon.json), [basics-voronoi-plots.json](../graphs/basics-voronoi-plots.json), [basics-cut-a-courtyard.json](../graphs/basics-cut-a-courtyard.json) — 5 total (`pcg graphs --node extrudePolygon`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `distance` | f32 | `3` |  |  | yes | How far the boundary travels along the direction, in world units. Field-capable and resolved on the INPUT points — the footprint's own points — so a per-point value gives a sloped top rather than a flat one, and a per-lot height living on the primitive domain becomes a field once promoteAttribute has put it on the points. A negative distance builds the solid on the OTHER side of the footprint and still comes out facing outward — the winding flips with it. A footprint whose distances straddle zero is a bowtie and has no outward side; the sign of their sum decides, which is total rather than right. |
| `direction` | enum | `"+y"` |  | `+y`, `vector`, `polygonNormal` |  | Which way the boundary travels. '+y' is straight up, the answer for buildings and walls on a ground plane. 'vector' uses the `vector` param, normalized. 'polygonNormal' computes each polygon's OWN normal by Newell's method — a sum over the boundary edges, so it is exact for a planar polygon, deterministic, and defined for a non-planar one (it returns the best-fit plane's normal) — which is what extrudes a footprint that is not lying flat. A polygon whose Newell normal is zero (every point collinear, or zero area) is refused by primitive index. |
| `vector` | vec3 | `[0,1,0]` |  |  | yes | Direction for the 'vector' mode; need not be unit length, and is normalized before use. Ignored by the other modes. Field-capable on the PRIMITIVE domain — one direction per closed polyline, which is the element a whole extrusion belongs to — so two footprints in one input rise along two different vectors in a single cook: a per-lot `attribute('slope')`, a `byAttribute` over a per-lot string kind, or `randomField` all read there. It is NOT per point and cannot be: a per-point direction would shear the footprint rather than sweep it, and a per-point HEIGHT is what `distance` already is. Read the domain it resolves on before writing the expression — the primitive domain carries no P, so `position()` is not available there and a value the points know reaches it through promoteAttribute (point to primitive). A vector that resolves to [0, 0, 0] refuses THAT PRIMITIVE BY INDEX rather than flattening it into a sheet, exactly as direction 'polygonNormal' refuses a polygon whose Newell normal is zero — the same condition (this polygon names no direction) and the same answer; a plain [0, 0, 0] is still refused before the walk, by the param rather than by a primitive. Resolved on the CPU whether or not the cook carries a GPU device: the primitive domain holds one element per polygon, so a dispatch would cost more than the three multiplies it replaces. `distance` is the param that may resolve on the device. |
| `caps` | enum | `"both"` |  | `none`, `top`, `bottom`, `both` |  | Which ends are closed. 'both' is a solid; 'bottom' or 'top' alone leaves an open shell (with `sides` false, 'top' is a floating lid — a roof with no building); 'none' with `sides` is a tube of wall. Each cap faces along its OWN plane's normal rather than along the direction, which is what makes a per-point `distance` shade as the sloped roof it actually builds, and what keeps a footprint lying in a tilted plane correct when it is extruded straight up. |
| `sides` | bool | `true` |  |  |  | Build the wall between the two ends. False keeps only the caps the `caps` param asked for, which is how a flat slab (`caps: 'bottom'`) or a floating roof (`caps: 'top'`) is spelled without a second node. False with `caps: 'none'` has nothing to build and is refused. |

## filterByAttribute

Keeps points whose named point attribute satisfies a comparison. Numeric attributes (f32/i32/u32/bool, tuple 1) compare against `value` with any comparison. String attributes compare against `stringValue` and support only 'eq' and 'ne'. Output is a point cloud of the survivors with all attributes carried, so by default the topology describing the points that are gone goes with them — all of it. Two ways to keep a network a network: set `topology` to 'keep' here, which preserves every primitive ALL of whose points survived and drops the rest, or reach for filterPrimitivesByAttribute, which is this node at the PRIMITIVE domain and tests a value the primitive itself carries.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-filter-by-attribute.json](../graphs/basics-filter-by-attribute.json), [basics-runs-along-a-path.json](../graphs/basics-runs-along-a-path.json), [examples-headless-scatter.json](../graphs/examples-headless-scatter.json) — 6 total (`pcg graphs --node filterByAttribute`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `attribute` | string | `"density"` |  |  |  | Name of the POINT attribute to test. Must exist on the point domain with tuple size 1. A name that exists on the primitive domain instead is refused with the fix, since filtering a primitive column here means letting a sampler flatten it onto points first. |
| `comparison` | enum | `"ge"` |  | `eq`, `ne`, `lt`, `le`, `gt`, `ge` |  | Comparison operator: eq (equal), ne (not equal), lt (<), le (<=), gt (>), ge (>=). String attributes allow only eq and ne. |
| `value` | f32 | `0` |  |  | yes | Right-hand side for numeric attributes. Ignored for string attributes, and a field written here is not even evaluated for one — the param nothing reads costs nothing and refuses nothing. As a FIELD it is a PER-POINT right-hand side, evaluated on the input's points, so each point is compared against its own number: `attribute("minLevel")` with comparison 'ge' keeps every point that clears the bar it was given, and a noise or a position expression makes the bar vary across the world. The comparison itself is unchanged — the same six operators, the same meaning per point — so this is the two-column test (attribute against attribute) that otherwise needs a scratch column plus filterByExpression. A a constant field matches the plain number wherever that number is exactly representable in f32 — which is the honest form of the claim, because a field resolves into an f32 COLUMN while a plain param stays the f64 the author wrote. `constant(0.7)` is 0.699999988079071 and a datum sitting between the two lands on different sides of them. That is not a defect to be fixed here but clause 1 of the capability rule showing through, and it is why the equality tests use f32-exact values on purpose. Non-finite values are REFUSED rather than read: a field resolving to NaN or ±Infinity names this param and stops, because a right-hand side has no documented meaning for one. Note that this refusal is about the FIELD, never about the attribute — a NaN in the COLUMN being tested is still data and still passes only 'ne'. |
| `stringValue` | string | `""` |  |  |  | Right-hand side for string attributes. Ignored for numeric attributes. |
| `topology` | enum | `"drop"` |  | `drop`, `keep` |  | What happens to the input's TOPOLOGY — the vertices and primitives built over these points. 'drop' (the default) outputs a point cloud: the survivors are rebuilt as points and EVERY primitive goes with them, whether or not the filter touched one of its points, which is why a filtered network has to be rebuilt downstream (pointsToPath over a grouping attribute, or connectPoints again). 'keep' preserves the primitives ALL of whose points survive, carrying their vertices, their vertex and primitive attributes, and the detail domain, renumbered onto the surviving points. A primitive that loses even ONE point is dropped whole: there is no truncation of a polyline or a poly that means anything — closing the gap invents a segment nobody authored and splitting the primitive in two invents a primitive, and neither is a filter's job. A primitive is never SHORTENED, so one that comes out with fewer than two vertices is one that went in that way — this node cannot manufacture a degenerate primitive, and it does not delete one either (setPolylineTopology already refuses a polyline under two vertices, so such a primitive can only have come from bare setTopology, deliberately). The POINT domain is IDENTICAL under both settings — same points, same order, same attributes, same identities — so this param only ever ADDS information and nothing reading a point can tell which was set; the one thing 'keep' carries beyond topology is the DETAIL attributes, which a point cloud has no room for. A predicate that keeps every point reproduces the input's topology, with one inherited caveat it shares with filterPrimitivesByBounds and filterPrimitivesByAttribute: surviving primitives are laid out into contiguous vertex runs, so a geometry whose primitive ranges do not TILE its vertex array (only bare setTopology can build one — nothing checks more than start + count <= vertexCount) loses the vertices no primitive references, and their vertex attribute values with them. This is the point-domain mirror of the primitive filters' `unreferencedPoints`, and it is what lets mergePrimitives find something to preserve downstream of a filter. |

## filterByBounds

Keeps points by position against the axis-aligned box [boundsMin, boundsMax]. What happens ON a face is the `boundary` param, and it is the difference between a selection and an OWNERSHIP RULE: the default 'halfOpen' keeps min <= p < max on every axis — the min face is inside, the max face is not — so two boxes that MEET at a face (one's max is the other's min, the same number) tile space with no gap and no duplicate, and each point belongs to exactly one of them. That is the rule a grid cell uses, and the one pointScatterInWorld's query window and a World cell rectangle already follow; note that it is the shared ENDPOINT VALUE that makes the tiling exact, so building the boxes as [c*size, (c+1)*size) is exact at any size, while recovering the index arithmetically as floor(p / size) can name the neighbouring cell when size is not exactly representable (floor(67.8 / 0.1) is 677, yet 678*0.1 is exactly 67.8). 'inclusive' keeps min <= p <= max, which is what you want to select a box whose faces carry points on purpose, and which emits a point sitting on a shared face from BOTH neighbouring boxes — harmless in a one-off selection, wrong in a partitioned cook, where a doubled point is invisible until two cells disagree. mode 'outside' is the exact complement of 'inside' under whichever boundary rule is active, so the two modes always partition the input: no point lost, none emitted twice. Infinite bounds work under both rules (every finite coordinate satisfies p < +Infinity), so an axis that should not be bounded — the Y of a World 'xz' column — needs no extra param. A NaN coordinate is never inside, so such a point lands in 'outside'. Output is a point cloud of the survivors with all attributes carried — unless `topology` is set to 'keep', which also preserves every primitive ALL of whose points survived, renumbered onto them.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [examples-streamed-terrain.json](../graphs/examples-streamed-terrain.json) — 1 total (`pcg graphs --node filterByBounds`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `boundsMin` | vec3 | `[0,0,0]` | (±Infinity ok, but never serializes) |  | yes | Minimum corner of the box, in world units. INCLUSIVE under both boundary rules: a point lying exactly on this face is inside. Use -Infinity on an axis that should not be bounded (an infinity does not survive JSON, so a graph that must serialize needs a finite bound wide enough to hold the world). As a FIELD it is a PER-POINT corner, evaluated on the input's points, so each point is tested against its OWN box rather than against one box shared by the cloud — which turns this node from 'keep what is in this region' into 'keep every point that is inside the box it carries', the test a per-point cell, plot or footprint written upstream asks for. Build the corner with vec(x, y, z); a scalar field broadcasts to all three axes exactly as a plain scalar would. NON-FINITE VALUES ARE READ, NOT REFUSED — this is one of the few field params where they are data: -Infinity on a component leaves that axis unbounded for that point, exactly as the plain value does, and a NaN component satisfies no comparison at all, so that point is never inside and lands in 'outside'. `inside` and `outside` stay exact complements point by point, since both read the same resolved value for a point — with one caveat a plain box does not have: two SEPARATE nodes resolve their own columns, so a bound built from randomField or nodeSeed differs between them and the pair no longer partitions. Give both nodes the same bounds field to keep it exact. |
| `boundsMax` | vec3 | `[1,1,1]` | (±Infinity ok, but never serializes) |  | yes | Maximum corner of the box, in world units. EXCLUSIVE under the default 'halfOpen' boundary (a point exactly on this face belongs to the next box along), INCLUSIVE under 'inclusive'. Use +Infinity on an axis that should not be bounded. An axis with max <= min keeps nothing under 'halfOpen' — a zero-width box has no interior — while under 'inclusive' max === min still keeps the points lying exactly on that plane. As a FIELD it is a PER-POINT corner on the input's points, with the same reading boundsMin's description gives, and the two are independent: a field min with a plain max is legal and the plain one costs nothing per point. The max <= min rule above then applies PER POINT — a point whose own box is empty on any axis simply fails the test and lands in 'outside'. Non-finite components are read rather than refused (±Infinity unbounds an axis, NaN keeps nothing), and a scalar field broadcasts to all three axes. |
| `mode` | enum | `"inside"` |  | `inside`, `outside` |  | 'inside' keeps points within the box, 'outside' keeps the rest. They are exact complements under whichever `boundary` rule is active, so running both over one input reproduces it exactly once. |
| `boundary` | enum | `"halfOpen"` |  | `halfOpen`, `inclusive` |  | Which faces belong to the box. 'halfOpen' (the default) keeps min <= p < max on every axis, matching the half-open windows of pointScatterInWorld and of a World cell: two abutting boxes then own a point on their shared face exactly once between them, which is what makes this node usable as the ownership rule of a partitioned cook. 'inclusive' keeps min <= p <= max, so BOTH such boxes emit that point — choose it when the box is a selection whose faces carry points deliberately (a pointGrid's last row, an authored extent) and nothing downstream requires one owner per point. |
| `topology` | enum | `"drop"` |  | `drop`, `keep` |  | What happens to the input's TOPOLOGY — the vertices and primitives built over these points. 'drop' (the default) outputs a point cloud: the survivors are rebuilt as points and EVERY primitive goes with them, whether or not the filter touched one of its points, which is why a filtered network has to be rebuilt downstream (pointsToPath over a grouping attribute, or connectPoints again). 'keep' preserves the primitives ALL of whose points survive, carrying their vertices, their vertex and primitive attributes, and the detail domain, renumbered onto the surviving points. A primitive that loses even ONE point is dropped whole: there is no truncation of a polyline or a poly that means anything — closing the gap invents a segment nobody authored and splitting the primitive in two invents a primitive, and neither is a filter's job. A primitive is never SHORTENED, so one that comes out with fewer than two vertices is one that went in that way — this node cannot manufacture a degenerate primitive, and it does not delete one either (setPolylineTopology already refuses a polyline under two vertices, so such a primitive can only have come from bare setTopology, deliberately). The POINT domain is IDENTICAL under both settings — same points, same order, same attributes, same identities — so this param only ever ADDS information and nothing reading a point can tell which was set; the one thing 'keep' carries beyond topology is the DETAIL attributes, which a point cloud has no room for. A predicate that keeps every point reproduces the input's topology, with one inherited caveat it shares with filterPrimitivesByBounds and filterPrimitivesByAttribute: surviving primitives are laid out into contiguous vertex runs, so a geometry whose primitive ranges do not TILE its vertex array (only bare setTopology can build one — nothing checks more than start + count <= vertexCount) loses the vertices no primitive references, and their vertex attribute values with them. This is the point-domain mirror of the primitive filters' `unreferencedPoints`, and it is what lets mergePrimitives find something to preserve downstream of a filter. |

## filterByDensity

Filters points by their `density` point attribute (f32, tuple 1). mode 'threshold' keeps points with density >= threshold; mode 'probabilistic' keeps each point when a deterministic per-point hashed random in [0, 1) is < its density (so density 0 never survives, 1 always does). The probabilistic draw is keyed on each point's IDENTITY — its stored position bits together with its `seed` point attribute — not on its array index, so the same point survives or does not whatever order it arrives in and whichever cell derived it. Two points that share a position AND a seed are one point as far as that draw is concerned and always decide the same way, so a cloud with no per-point seeds (the attribute defaults to 0) decides purely on position. Output is a point cloud of the survivors with all attributes carried — unless `topology` is set to 'keep', which also preserves every primitive ALL of whose points survived, renumbered onto them.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-filter-by-density.json](../graphs/basics-filter-by-density.json), [basics-volume-scatter.json](../graphs/basics-volume-scatter.json), [examples-streamed-terrain.json](../graphs/examples-streamed-terrain.json) — 4 total (`pcg graphs --node filterByDensity`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"threshold"` |  | `threshold`, `probabilistic` |  | 'threshold' keeps density >= threshold; 'probabilistic' keeps each point with probability equal to its density. |
| `threshold` | f32 | `0.5` |  |  | yes | Minimum density a point needs to survive in 'threshold' mode: a point is kept when its own `density` attribute is >= this. Ignored in 'probabilistic' mode, and a field written here is not even evaluated in that mode — the param nothing reads costs nothing and refuses nothing. As a FIELD it is a PER-POINT threshold, evaluated on the input's points, so each point is tested against the bar IT was given rather than against one number shared by the cloud: attribute("minDensity") lets a value written upstream set each point's own bar, and a noise or a position expression makes the bar vary across the world, which thins one region at 0.8 while another survives at 0.2 in a single cook. The comparison is unchanged and still `density >= threshold`, so a constant field matches the plain number wherever that number is exactly representable in f32 — which is the honest form of the claim, because a field resolves into an f32 COLUMN while a plain param stays the f64 the author wrote. `constant(0.7)` is 0.699999988079071 and a datum sitting between the two lands on different sides of them. That is not a defect to be fixed here but clause 1 of the capability rule showing through, and it is why the equality tests use f32-exact values on purpose. Non-finite values are REFUSED rather than read: a field resolving to NaN or ±Infinity here names this param and stops, because a threshold has no documented meaning for one — unlike selfPrune's radius, where NaN means 'claims no room'. Guard the expression itself (max(x, 1e-6) under a div) if it can produce one. |
| `seed` | u32 | `0` |  |  |  | Extra seed for 'probabilistic' mode; change it to re-roll which points survive. |
| `topology` | enum | `"drop"` |  | `drop`, `keep` |  | What happens to the input's TOPOLOGY — the vertices and primitives built over these points. 'drop' (the default) outputs a point cloud: the survivors are rebuilt as points and EVERY primitive goes with them, whether or not the filter touched one of its points, which is why a filtered network has to be rebuilt downstream (pointsToPath over a grouping attribute, or connectPoints again). 'keep' preserves the primitives ALL of whose points survive, carrying their vertices, their vertex and primitive attributes, and the detail domain, renumbered onto the surviving points. A primitive that loses even ONE point is dropped whole: there is no truncation of a polyline or a poly that means anything — closing the gap invents a segment nobody authored and splitting the primitive in two invents a primitive, and neither is a filter's job. A primitive is never SHORTENED, so one that comes out with fewer than two vertices is one that went in that way — this node cannot manufacture a degenerate primitive, and it does not delete one either (setPolylineTopology already refuses a polyline under two vertices, so such a primitive can only have come from bare setTopology, deliberately). The POINT domain is IDENTICAL under both settings — same points, same order, same attributes, same identities — so this param only ever ADDS information and nothing reading a point can tell which was set; the one thing 'keep' carries beyond topology is the DETAIL attributes, which a point cloud has no room for. A predicate that keeps every point reproduces the input's topology, with one inherited caveat it shares with filterPrimitivesByBounds and filterPrimitivesByAttribute: surviving primitives are laid out into contiguous vertex runs, so a geometry whose primitive ranges do not TILE its vertex array (only bare setTopology can build one — nothing checks more than start + count <= vertexCount) loses the vertices no primitive references, and their vertex attribute values with them. This is the point-domain mirror of the primitive filters' `unreferencedPoints`, and it is what lets mergePrimitives find something to preserve downstream of a filter. |

## filterByExpression

Keeps points where a field-capable `predicate` evaluates to a non-zero number. The predicate is resolved once over the input's point domain, so it can read position, any attribute, noise, or per-point randomness — which means a test that would otherwise need a scratch attribute plus filterByAttribute becomes one node, with no leftover column on the output. Comparison field functions (gt/ge/lt/le/eq/ne) already yield 1 and 0, and combining them with mul acts as AND, max as OR. NaN never passes, so a predicate that fails to compute drops the point instead of keeping it. The predicate must evaluate to tuple size 1: comparisons broadcast elementwise, so comparing a vector yields a vector of flags, which is not a decision. Output is a point cloud of the survivors with all attributes carried — unless `topology` is set to 'keep', which also preserves every primitive ALL of whose points survived, renumbered onto them. The second output `rest` carries the points the predicate rejected, so a two-way split is one node: it is the exact complement of `out` (0 and NaN land there), in stable input order with all attributes carried, and under 'keep' it preserves the primitives all of whose points were rejected, so a primitive straddling the split is on neither side, and a primitive with no vertices at all (which loses no point) stays on `out` only, so the two sides never share one. `rest` is built only when something reads it, and `out` is the same bytes either way.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry), `rest` (geometry)

**Examples:** [basics-filter-by-expression.json](../graphs/basics-filter-by-expression.json), [basics-worley-cells.json](../graphs/basics-worley-cells.json), [basics-suspension-bridge.json](../graphs/basics-suspension-bridge.json) — 18 total (`pcg graphs --node filterByExpression`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `predicate` | f32 | `1` |  |  | yes | Per-point test: non-zero keeps the point, 0 and NaN drop it. Field-capable and evaluated on the input's points. The default 1 keeps everything, so an unconfigured node passes its input through. |
| `seed` | u32 | `0` |  |  |  | Extra seed for evaluating `predicate`: 0 (the default) uses the node's derived seed unchanged; any nonzero value folds in as hashCombine(nodeSeed, seed). This re-rolls randomness drawn from the evaluation context (randomField, the per-point seed attribute, and the `nodeSeed` field) but not a noise on its own, whose seed lives inside its own field spec — a noise moves with this only when its `opts.position` reads `nodeSeed`. |
| `topology` | enum | `"drop"` |  | `drop`, `keep` |  | What happens to the input's TOPOLOGY — the vertices and primitives built over these points. 'drop' (the default) outputs a point cloud: the survivors are rebuilt as points and EVERY primitive goes with them, whether or not the filter touched one of its points, which is why a filtered network has to be rebuilt downstream (pointsToPath over a grouping attribute, or connectPoints again). 'keep' preserves the primitives ALL of whose points survive, carrying their vertices, their vertex and primitive attributes, and the detail domain, renumbered onto the surviving points. A primitive that loses even ONE point is dropped whole: there is no truncation of a polyline or a poly that means anything — closing the gap invents a segment nobody authored and splitting the primitive in two invents a primitive, and neither is a filter's job. A primitive is never SHORTENED, so one that comes out with fewer than two vertices is one that went in that way — this node cannot manufacture a degenerate primitive, and it does not delete one either (setPolylineTopology already refuses a polyline under two vertices, so such a primitive can only have come from bare setTopology, deliberately). The POINT domain is IDENTICAL under both settings — same points, same order, same attributes, same identities — so this param only ever ADDS information and nothing reading a point can tell which was set; the one thing 'keep' carries beyond topology is the DETAIL attributes, which a point cloud has no room for. A predicate that keeps every point reproduces the input's topology, with one inherited caveat it shares with filterPrimitivesByBounds and filterPrimitivesByAttribute: surviving primitives are laid out into contiguous vertex runs, so a geometry whose primitive ranges do not TILE its vertex array (only bare setTopology can build one — nothing checks more than start + count <= vertexCount) loses the vertices no primitive references, and their vertex attribute values with them. This is the point-domain mirror of the primitive filters' `unreferencedPoints`, and it is what lets mergePrimitives find something to preserve downstream of a filter. |

## filterPrimitivesByAttribute

Keeps WHOLE PRIMITIVES whose named PRIMITIVE attribute satisfies a comparison, and preserves topology: the survivors keep their vertices, their vertex and primitive attributes, and the points they share, so a network that goes in comes out a network. It is filterByAttribute at the primitive domain — the same six comparisons, the same numeric/string split, the same scalar-only rule — and filterPrimitivesByBounds' sibling, differing only in what it asks about a primitive (a value it carries, rather than where its vertices lie). Numeric attributes (f32/i32/u32/bool, tuple 1) compare against `value`; string attributes compare against `stringValue` and allow only 'eq' and 'ne', which includes `primtype`, so 'primtype eq polyline' is how a mixed geometry is narrowed to its curves. WHY IT MATTERS WHERE THE FILTER SITS: a primitive attribute — connectPoints' edge length, a promoted density, anything promoteAttribute lifted onto the primitive domain — can also be read AFTER a sampler has flattened it onto points, because every sampler carries primitive columns down onto the points it makes; filterByAttribute then works, and that is how such graphs were written before this node existed. The cost is that the flattening, and everything downstream of it, runs on primitives that were always going to be discarded. Filtering here instead discards them while they are still primitives, so the work that follows is proportional to what survives rather than to what was proposed. POINTS: by default (unreferencedPoints 'keep') the point domain is passed through untouched — same points, same indices, same attributes, same identities — so anything computed per point upstream still lines up and a partition cell keeps its halo; 'drop' removes every point no surviving primitive references and renumbers the topology onto what is left, which is how a clean network comes out. DETERMINISM: the test reads one primitive's own value and nothing else — not its index, not its neighbours, not how many primitives there are — so the survivors and their order are the input's however the cook was partitioned, and no index column is emitted for a per-partition number to leak through. An EMPTY primitive domain that still carries the named column is an empty result rather than an error, as in filterPrimitivesByBounds: a cell too sparse to make a primitive is a legitimate, silent case in a partitioned cook. A geometry with no primitive columns at all is refused instead, and told so — that is a topology never built or dropped upstream, not a sparse cell.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-filter-primitives-by-attribute.json](../graphs/basics-filter-primitives-by-attribute.json), [examples-rig.json](../graphs/examples-rig.json) — 2 total (`pcg graphs --node filterPrimitivesByAttribute`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `attribute` | string | `"edgeLength"` |  |  |  | Name of the PRIMITIVE attribute to test. Must exist on the primitive domain with tuple size 1. The default names connectPoints' own convention for its `lengthAttr`, which is the commonest key here; `primtype` is always present once a geometry has topology and is tested with 'eq'/'ne' against stringValue. A name that exists on the POINT domain instead is refused with the fix, since that is the shape of the idiom this node replaces. |
| `comparison` | enum | `"ge"` |  | `eq`, `ne`, `lt`, `le`, `gt`, `ge` |  | Comparison operator: eq (equal), ne (not equal), lt (<), le (<=), gt (>), ge (>=). String attributes allow only eq and ne. Identical to filterByAttribute's, deliberately: moving a filter between the two domains must not change what it means. |
| `value` | f32 | `0` |  |  | yes | Right-hand side for numeric attributes. Ignored for string attributes, and a field written here is not even evaluated for one. As a FIELD it is evaluated on the PRIMITIVE DOMAIN — one right-hand side per primitive, never per point — so each primitive is compared against its own number: `attribute("maxLength")` with comparison 'le' keeps every edge shorter than the limit IT carries, which is the per-primitive budget one shared number cannot express. Everything else is unchanged: the same six operators with the same meaning, the same scalar-only rule, and a a constant field matches the plain number wherever that number is exactly representable in f32 — which is the honest form of the claim, because a field resolves into an f32 COLUMN while a plain param stays the f64 the author wrote. `constant(0.7)` is 0.699999988079071 and a datum sitting between the two lands on different sides of them. That is not a defect to be fixed here but clause 1 of the capability rule showing through, and it is why the equality tests use f32-exact values on purpose. Because the value is read per primitive and nothing else — not its index, not its neighbours, not how many primitives there are — the determinism the node's description promises is unaffected, PROVIDED the field is too: a field reading position or a primitive attribute is partition-independent, while randomField and nodeSeed are per-node and per-cell like any other seeded draw. Non-finite values are REFUSED rather than read, naming this param: a right-hand side has no documented meaning for NaN or ±Infinity. That is about the FIELD only — a NaN in the primitive COLUMN being tested is still data, and still passes only 'ne'. |
| `stringValue` | string | `""` |  |  |  | Right-hand side for string attributes. Ignored for numeric attributes. |
| `unreferencedPoints` | enum | `"keep"` |  | `keep`, `drop` |  | What happens to points no surviving primitive references, exactly as in filterPrimitivesByBounds. 'keep' (the default) leaves the point domain completely untouched: same points in the same order, so every point index, attribute and identity is still the input's. 'drop' removes them and renumbers the topology onto the points that remain, in ascending input order, which yields a clean network with nothing dangling; the cost is that point indices move. Note that 'drop' also drops points that had NO primitive to begin with, so a cloud carrying both a network and unrelated scatter loses the scatter. |

## filterPrimitivesByBounds

Keeps or drops WHOLE PRIMITIVES by testing their vertices against the axis-aligned box [boundsMin, boundsMax], and it is one of the two filters in this library that PRESERVE TOPOLOGY (filterPrimitivesByAttribute, which tests a value a primitive carries rather than where its vertices lie, is the other): the survivors keep their vertices, their vertex and primitive attributes, and the points they share, so a network that goes in comes out a network. Every point filter — filterByDensity, filterByBounds, filterByAttribute, filterByExpression, selfPrune — rebuilds the point domain from the survivors and the primitives go with it; this node filters the PRIMITIVE domain instead, which is what makes the difference. It exists to complete the partitioned network cook connectPoints prescribes, whose last step no node could perform: widen the cell's rectangle by `radius` and clip the CLOUD to it with filterByBounds ('halfOpen'), run connectPoints, then run THIS node on the UNWIDENED rectangle with vertex 'first' and the same 'halfOpen' boundary. Each cell then emits exactly the edges it owns, the cells tile the whole-region network with no duplicate and no gap, and the recipe is a serializable graph rather than a TypeScript script. `vertex` decides what 'in the box' means for a primitive: 'first' and 'last' consult ONE vertex, which is what makes them OWNERSHIP rules — every primitive has exactly one first vertex, so exactly one box of a tiling claims it — while 'all' and 'any' are SELECTIONS and do not tile ('any' claims a straddling primitive from every box it reaches, 'all' from none of them). connectPoints emits each edge's lower-keyed endpoint FIRST, so with vertex 'first' this node's owner and that node's canonical edge order are the same choice by construction. For a polyline from any other source — pointsToPath, resamplePath, createPolyline — the first vertex is simply the path's START point: still exactly one owner per path, so the tiling is still exact, but the owner is the cell holding the start rather than the cell holding most of the road, and that one cell emits the whole path however far it runs. `mode` 'outside' is the exact complement of 'inside' under whichever vertex rule and boundary are active, so running both over one input reproduces its primitives exactly once; combined with `vertex` that spans the four quantifiers — 'all'+'inside' keeps primitives lying entirely inside, 'any'+'outside' those lying entirely outside, 'any'+'inside' those touching the box, 'all'+'outside' those not entirely within it. A fifth rule, 'boundingBox', is geometric rather than a quantifier: it keeps every primitive whose axis-aligned bounding box OVERLAPS the box, so a long triangle crossing the box with no vertex inside it is kept — the selection a cell needs when it must emit everything that passes through it. `boundary` is filterByBounds' rule with the same meaning and the same reason to prefer 'halfOpen' wherever ownership matters. POINTS: by default (unreferencedPoints 'keep') the point domain is passed through untouched — same points, same indices, same attributes, same identities — so a partition cell keeps its halo points as isolated leftovers; 'drop' removes every point no surviving primitive references and renumbers the topology onto what is left, which is how a clean network comes out. A geometry with no primitives is not an error but an empty result: a cell too sparse to make an edge is a legitimate, silent case in a partitioned cook. Primitives of any kind are handled, polylines and polys alike — this reads vertices, never `primtype`.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-two-kinds-of-bounds.json](../graphs/basics-two-kinds-of-bounds.json) — 1 total (`pcg graphs --node filterPrimitivesByBounds`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `boundsMin` | vec3 | `[0,0,0]` | (±Infinity ok, but never serializes) |  | yes | Minimum corner of the box, in world units. INCLUSIVE under both boundary rules: a vertex lying exactly on this face is inside. Use -Infinity on an axis that should not be bounded (note that an infinity does not survive JSON, so a graph that must serialize needs a finite bound wide enough to hold the world). As a FIELD it is evaluated on the PRIMITIVE DOMAIN, not on the points — one corner per primitive, so each primitive is tested against the box IT carries, and every vertex the `vertex` rule consults is tested against that same box. Read a primitive column (attribute("cellMinX") and friends, promoteAttribute lifts a point column onto primitives) or build one with vec(x, y, z); a scalar field broadcasts to all three axes. The reading it enables is 'does this edge lie in ITS OWN cell', which one shared box cannot ask. TILING IS THEN THE AUTHOR'S TO PRESERVE: the ownership guarantee this node's description makes — abutting boxes claim each primitive exactly once — is a property of the BOXES, so per-primitive boxes tile only if they were built to, and boxes that overlap or leave a gap double-count or lose primitives with no error to say so. Non-finite components are read rather than refused: ±Infinity unbounds an axis exactly as the plain value does, and a NaN component satisfies no comparison, so a primitive whose box has one is never inside and lands in 'outside'. |
| `boundsMax` | vec3 | `[1,1,1]` | (±Infinity ok, but never serializes) |  | yes | Maximum corner of the box, in world units. EXCLUSIVE under the default 'halfOpen' boundary (a vertex exactly on this face belongs to the next box along), INCLUSIVE under 'inclusive'. Use +Infinity on an axis that should not be bounded, subject to the serialization note on boundsMin. As a FIELD it is one corner PER PRIMITIVE, with the same reading boundsMin's description gives, and the two are independent: a field min with a plain max is legal and the plain one costs nothing per primitive. A primitive whose own box is empty on an axis (max <= min under 'halfOpen') keeps nothing and lands in 'outside'; non-finite components are read rather than refused; a scalar field broadcasts to all three axes. |
| `vertex` | enum | `"first"` |  | `first`, `last`, `all`, `any`, `boundingBox` |  | Which of a primitive's vertices the box test reads. 'first' (the default) and 'last' read exactly ONE — the primitive's first or last vertex — which is what makes them ownership rules: every primitive has exactly one of each, so abutting boxes under the 'halfOpen' boundary claim it exactly once between them. Use 'first' with connectPoints, whose edges already lead with their lower-keyed endpoint, so the owner a cell computes matches the canonical edge order rather than merely correlating with it. 'all' keeps a primitive only when EVERY vertex is in the box, 'any' when at least one is; both are selections, and neither tiles — 'any' hands a straddling primitive to every box it reaches and 'all' to none of them, so a partitioned cook using either double-counts or loses edges at the seams. 'boundingBox' reads every vertex and tests the axis-aligned box they SPAN, [lo, hi] per axis, CLOSED: a primitive is inside when that box OVERLAPS the filter's box. It is 'any' made geometric — a long triangle or edge that crosses the box with no vertex in it is inside, which 'any' misses — and, for a primitive with no NaN coordinate, it is a superset of 'any' (a vertex in the box puts its bounding box in the box). Under 'halfOpen' the test is lo < max and hi >= min on every axis (and min < max, so an empty box meets nothing); under 'inclusive' it is lo <= max and hi >= min (and min <= max). The primitive's own box is closed on purpose: a flat primitive — zero extent on an axis, like an axis-aligned plate — must still be able to meet a box. ABUTTING BOXES: like 'any', this is a SELECTION and does not tile. A primitive straddling a shared face is in both boxes; one that merely TOUCHES the face is claimed by the box whose half-open side holds that face — under 'halfOpen' a primitive whose box ends exactly at x = c is kept by the box [c, …) as well as by the box it lies in, because the point x = c it reaches belongs to that neighbour, and a primitive lying wholly in the plane x = c is kept only by [c, …); under 'inclusive' both boxes keep both. It is the rule for a cell that must emit EVERY primitive that can be seen inside it (a renderer clipping at the cell's faces), not one owner per primitive — to catch primitives NEAR the cell too, widen the box by the halo. A NaN vertex coordinate makes the primitive's box NaN, so that primitive is never inside and lands in 'outside'. A primitive with no vertices is never inside, under all five rules. |
| `mode` | enum | `"inside"` |  | `inside`, `outside` |  | 'inside' keeps the primitives the `vertex` rule places in the box, 'outside' keeps the rest. They are exact complements under whichever vertex rule and boundary are active, so running both over one input reproduces every primitive exactly once. Read the two params together: 'any' with 'outside' keeps primitives lying ENTIRELY outside the box (no vertex inside), which is the deletion 'all' with 'outside' does NOT perform — that one keeps everything not entirely within it, straddlers included. |
| `boundary` | enum | `"halfOpen"` |  | `halfOpen`, `inclusive` |  | Which faces belong to the box, exactly as in filterByBounds. 'halfOpen' (the default) keeps min <= p < max on every axis, so two boxes meeting at a face claim a vertex lying on it exactly once between them — pair it with vertex 'first' and it is an ownership rule a partitioned cook can tile with. 'inclusive' keeps min <= p <= max, so both boxes claim that vertex, and with vertex 'first' both would emit the same edge; choose it for a selection whose faces carry points on purpose, never for a cook that is split into cells. |
| `unreferencedPoints` | enum | `"keep"` |  | `keep`, `drop` |  | What happens to points no surviving primitive references. 'keep' (the default) leaves the point domain completely untouched: same points in the same order, so every point index, attribute and identity is still the input's and anything computed per point upstream still lines up — a partition cell keeps its halo points as isolated leftovers beside the network it owns. 'drop' removes them and renumbers the topology onto the points that remain, in ascending input order, which yields a clean network with nothing dangling; the cost is that point indices move, and that a point kept by one cell may also be kept by its neighbour, since an edge crossing a seam needs both of its endpoints wherever it is emitted. Note that 'drop' also drops points that had NO primitive to begin with, so a cloud carrying both a road network and unrelated scatter loses the scatter — filter such a cloud before the network is built, or keep the leftovers. |

## forEach

Composite node that cooks an inner graph ONCE PER ELEMENT instead of once. Exactly one exposed input must be named "each" (one iteration per item of the collection on that pin) or "eachPoint" (one iteration per point of the one geometry on that pin, the body seeing a one-point cloud); every other exposed input is broadcast whole to every iteration. Each iteration's outputs are concatenated onto the matching output pin in the iterated collection's own order, and carry the iterated item's tags. Every iteration is seeded on its element's CONTENT — position bits, the seed attribute and the tags — never on its position in the collection, so reordering the input reorders the output without re-rolling any of it. Pins and params are per-instance exactly as for "subgraph", and the serialized form is the same payload: create instances with forEachNode(innerGraph, exposedInputs, exposedOutputs, exposedParams), or deserialize a graph containing one. The body gets no memo reuse between iterations, by construction — each rotates the inner seed, and a node holds one cache slot.

**Category:** composite

**Meters the cook budget itself:** under `cook(graph, { budgetMs })` this node yields to the event loop inside its own execute, so its `NodeDoneInfo.elapsedMs` is wall time spanning those yields — not an uninterrupted block. Derive a longest-block figure from a cook with the budget unset.

**Inputs:** *(none)*

**Outputs:** *(none)*

**Examples:** [basics-foreach-per-group.json](../graphs/basics-foreach-per-group.json), [examples-rig.json](../graphs/examples-rig.json) — 2 total (`pcg graphs --node forEach`)

**Params:** *(none)*

## jitterPoints

Offsets each point by a deterministic random vector: each axis moves by a uniform random in [-amount, +amount], hashed from (seed, point IDENTITY, axis). Identity is the point's incoming position bits together with its `seed` point attribute, not its array index, so the offset belongs to the point: reorder the cloud, drop points upstream, or derive the same region inside another cell's halo, and every point still moves exactly as far. Two points that share a position AND a seed move identically and stay coincident (the `seed` attribute defaults to 0, so a cloud with no per-point seeds jitters on position alone). amount is field-capable (evaluated on the input positions; tuple 1 broadcasts to all axes).

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-jitter-points.json](../graphs/basics-jitter-points.json), [basics-foreach-per-group.json](../graphs/basics-foreach-per-group.json), [examples-headless-scatter.json](../graphs/examples-headless-scatter.json) — 6 total (`pcg graphs --node jitterPoints`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `amount` | vec3 | `[0.1,0.1,0.1]` |  |  | yes | Maximum offset per axis, in world units. Field-capable (tuple 1 broadcasts). |
| `seed` | u32 | `0` |  |  |  | Extra seed folded into the node seed; change it to re-roll the jitter. |

## mergePoints

Concatenates the points of every connected geometry, in connection order, into one point cloud. The output carries the union of all point attributes: an attribute missing on an input fills with its default over that input's range. Attributes sharing a name must agree on type and tuple size. Topology (vertices/primitives) is not carried — the result is points only, so a network or a mesh arrives here and leaves as a bare cloud; `mergePrimitives` is the twin that keeps it. Output tags are the union of input tags.

**Category:** point op

**Inputs:** `in` (geometry, multi, optional)

**Outputs:** `out` (geometry)

**Examples:** [basics-merge-points.json](../graphs/basics-merge-points.json), [basics-curve-shaping.json](../graphs/basics-curve-shaping.json), [basics-field-shaping.json](../graphs/basics-field-shaping.json) — 16 total (`pcg graphs --node mergePoints`)

**Params:** *(none)*

## mergePrimitives

Concatenates every connected geometry, in connection order, KEEPING TOPOLOGY: points, vertices and primitives are appended and each input's vertex and primitive references are renumbered onto its place in the result, so an authored network merged with a generated one comes out a single network. The topology-preserving twin of mergePoints, which carries points only and so turns any input into a bare cloud. The point, vertex and primitive domains each carry the union of that domain's attributes: an attribute missing on an input fills with its default over that input's range, and attributes sharing a name must agree on type and tuple size. The one exception is `primtype`, which is a type tag rather than a value: each input's primitives keep their own tag, and primitives from an input carrying no primtype column come out with an EMPTY tag rather than inheriting another input's — this node cannot know what an untagged primitive is and must not guess. One consequence to know before relying on absence: surfaceSample ignores the tag entirely when a geometry has NO primtype column, so an untagged triangle mesh samples fine alone but is skipped once a tagged input is merged in and the column exists — tag such a mesh upstream (createTriangleMesh does) rather than leaving it untagged. Mixed primitive types are allowed, because every consumer selects what it understands (surfaceSample takes 3-vertex `poly`, the path nodes take `polyline`). An input with no topology contributes its points and no primitives, which is not an error. The detail domain is not carried: every input has one and choosing between them would be a guess. Output tags are the union of input tags. Point identity is position bits plus the `seed` attribute and both are copied verbatim, so two inputs holding a point at the same position with the same seed are ONE point to every identity-keyed decision (jitter, probabilistic filters, randomField) — the same inherited hazard mergePoints carries. Give clouds that must stay distinct distinct seeds.

**Category:** point op

**Inputs:** `in` (geometry, multi, optional)

**Outputs:** `out` (geometry)

**Examples:** [basics-merge-primitives.json](../graphs/basics-merge-primitives.json), [basics-cut-a-courtyard.json](../graphs/basics-cut-a-courtyard.json), [basics-gabriel-cells.json](../graphs/basics-gabriel-cells.json) — 14 total (`pcg graphs --node mergePrimitives`)

**Params:** *(none)*

## meshFromField

Turns a scalar FIELD into a triangle mesh: the surface where the field crosses `isoValue`. Other nodes build geometry from no input at all — meshPrimitive makes a box, pointGrid a lattice — but their SHAPE is written into the node; this is the only one whose shape and topology come out of an EXPRESSION, which is how a cave, a blob, an eroded cliff or a melted rock gets made, which is to say every shape that is easy to write as 'where is this quantity zero' and hard to model any other way. Output is 3-vertex `poly` primitives carrying P and a `normal` taken from the field's own GRADIENT, so the surface shades smoothly however coarse the lattice; there is no `uv`, deliberately, because an isosurface has no natural parameterisation and a planar one would be a lie on every vertical face — use triplanar shading, or transferAttribute with mapping 'nearest' from something that does have UVs. IT CONTOURS BY TETRAHEDRA, NOT CUBES. Marching cubes looks 8 corner signs up in a 256-entry table, several of whose cases are genuinely ambiguous — a face with two diagonal corners inside can be joined either way — so the table encodes a convention that neighbouring cubes must agree on or the mesh cracks. Splitting each cube into 6 tetrahedra removes the choice: 4 corners, no ambiguous case, watertight because there is nothing to get wrong rather than because a table is right. The cost is roughly twice the triangles for the same lattice, which is the trade being made. THE LATTICE IS ANCHORED TO THE WORLD, not to `boundsMin`. Cube (i, j, k) always spans [i * cellSize, (i+1) * cellSize) whatever bounds asked for it, so two windows that overlap sample the same corners at the same positions and agree bit for bit — the property `volumeSample` deliberately does not have, since its cell size is a request divided into the extent it was given. `cellSize` here is exact and the bounds are widened outward to whole cubes. An optional geometry input replaces the bounds params with that geometry's own point extents, which chooses the REGION and never the lattice: contour around a scatter and the cubes are still the world's cubes. PARTITIONING: a tetrahedron reads 4 corner samples and no neighbour's answer, so this is zero-hop; a cell of a partitioned world cooks the cubes its own bounds cover and the union tiles them, because a cube belongs to exactly one cell under a half-open rule on its INDEX. Nothing is welded — every triangle carries its own three points — so no cell ever depends on a number another cell chose. Two conditions are on the caller. The field must be a function of POSITION: `fraction` and `index` measure the population of this cook and `attribute` can only read the bookkeeping columns of a cloud this node manufactured, so all three are REFUSED by name (a field built with the code combinators carries no spec and cannot be screened, which makes it the author's promise instead). And the field must resolve on ONE path for a given world: CPU and GPU agree within a published tolerance, a corner classification is a COMPARE, and no tolerance bounds a comparison, so two cells that resolved the same corner differently can disagree about its sign and crack the seam.

**Category:** source

**Inputs:** `in` (geometry, optional)

**Outputs:** `out` (geometry)

**Examples:** [basics-mesh-from-field.json](../graphs/basics-mesh-from-field.json) — 1 total (`pcg graphs --node meshFromField`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `field` | f32 | `0` |  |  | yes | The scalar field to contour. A plain number contours nothing — a constant never crosses anything — so this is a field param that only makes sense as a field. Any expression of position works: a noise for a cloud or a rock, `sub(length(position()), r)` for a sphere, the difference of two for a carve. IT MUST BE A FUNCTION OF POSITION AND THAT IS ENFORCED: `fraction`, `index` and `attribute` are refused by name, because the first two measure the population of this cook and the third can only reach the bookkeeping columns of the lattice this node builds. The refusal names the offending position inside the expression. A field composed with the CODE combinators carries no spec and so cannot be screened at all; that one is the author's promise, and breaking it does not throw, it makes a partitioned world disagree with itself at the seams. Resolved on the CPU over the lattice corners, in chunks — a partitioned world cooks under a deadline, and one resolve over every corner at once is a single uninterruptible call however small the budget. The chunking cannot move the answer precisely BECAUSE of the purity rule above: a field that reads only position cannot tell one split of the corners from another. |
| `isoValue` | f32 | `0` |  |  |  | The value the surface sits at. Moving it grows or shrinks the solid without re-sampling anything conceptually — for a signed distance it is a plain offset, and for a noise it is a threshold, which is why an eroded rock and a cave are the same graph with two settings. The surface passes EXACTLY through this value: a vertex is placed by linear interpolation along the lattice edge that crosses it, so evaluating the field at any emitted vertex returns this number to within the interpolation's own error, which is what `isosurface.test.ts` measures. |
| `cellSize` | f32 | `1` | >= 0 |  |  | Lattice cube edge in world units, and unlike volumeSample's it is EXACT rather than a request. The lattice is anchored at the world origin, so cube (i, j, k) spans [i * cellSize, (i+1) * cellSize) whatever bounds asked for it, and the bounds are widened outward to whole cubes rather than divided into them. That is the whole partitioning story in one sentence: two windows that overlap sample the same corners at the same world positions, so they agree bit for bit, where a lattice fitted to its own bounds would put its corners somewhere different in every window. Cost grows with the CUBE of the bounds over this value, and every sample is a field evaluation, so halving it is eight times the work. |
| `boundsMin` | vec3 | `[-8,-8,-8]` |  |  |  | Low corner of the region to contour, in world units, and IGNORED when a geometry is connected — the input's own point extents replace both bounds then. Widened outward to the enclosing whole cube, so the surface is never clipped mid-cube by a bound that fell inside one. Under a partitioned world this is the cell's own rectangle: bind it per cell, and because the lattice is world-anchored rather than bounds-anchored the cells agree about every corner they share. |
| `boundsMax` | vec3 | `[8,8,8]` |  |  |  | High corner of the region to contour, in world units, and IGNORED when a geometry is connected. HALF-OPEN: the last cube walked is the one ending at or before this face, so two cells whose rectangles meet on a cell-size multiple tile the surface instead of both emitting the seam. The low face is widened OUTWARD to a whole cube, so the contoured region can reach up to one cube below `boundsMin` — a solid that leaves the box is left open there rather than capped, since this node emits the surface it found and never invents a lid. Note also that the FIELD is evaluated one cube further out again on every face, because the gradient that gives the normals is a central difference and needs a corner beyond the ones it reports on. A field with a pole just outside the box therefore still refuses the cook, and moving the box is the fix. |
| `inside` | enum | `"below"` |  | `below`, `above` |  | Which side of `isoValue` is solid, which decides only two things: which way the surface faces, and hence which way the winding runs. 'below' (the default) treats field < isoValue as inside, the convention a signed distance uses — negative within the shape. 'above' is the one a density or an occupancy noise wants, where more means more material. The surface geometry is identical either way; flipping this turns it inside out rather than moving it. |

## meshPrimitive

Builds a parametric triangle mesh with no input: shape 'plane' is one axis-aligned rectangle, shape 'box' is six of them around a volume, shape 'cylinder' is an upright (y-axis) cylinder with optional caps, and shape 'disc' is one flat polygonal disc lying like a plane. Output carries P (f32 tuple 3), a uv point attribute (f32 tuple 2) running 0..1 across each face, one 3-vertex 'poly' primitive per triangle — everything surfaceSample, transferAttribute's 'uv' and 'raycast' mappings, and promoteAttribute need — and, with `normals` on, a `normal` point attribute (f32 tuple 3). This is the only mesh source that survives serialization: dataInput's items are injected at runtime and a saved graph carries none, so a graph that must cook from JSON alone gets its surface from here. Plane and disc normals point along the positive third axis (+y for orientation 'xz', +z for 'xy', +x for 'yz'); box and cylinder normals point outward. A plane or box face's point order is u fastest then v, a box one block per face in the order +x, -x, +y, -y, +z, -z; a box's faces do not share points, so uv seams are exact. A cylinder is its wall block — `subdivisions.y + 1` rings of `sides + 1` points, round the ring fastest, bottom ring first, the seam column duplicated so u runs 0..1 — then the top cap's `sides` corners, then the bottom cap's; caps share no points with the wall, so the rim is a real crease, and each cap (like a disc) is a fan of `sides - 2` triangles from its first corner with no centre point. Ring corners lie ON the ellipse whose diameters are the size's components, starting on +z and turning toward +x, so a `sides` that is a multiple of 4 reaches the full `size` extents exactly. A zero size component makes degenerate (zero-area) triangles, which area-weighted sampling and the raycast mapping skip.

**Category:** source

**Inputs:** *(none)*

**Outputs:** `out` (geometry)

**Examples:** [basics-mesh-primitive.json](../graphs/basics-mesh-primitive.json), [basics-surface-sample.json](../graphs/basics-surface-sample.json), [basics-promote-attribute.json](../graphs/basics-promote-attribute.json) — 19 total (`pcg graphs --node meshPrimitive`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `shape` | enum | `"plane"` |  | `plane`, `box`, `cylinder`, `disc` |  | 'plane' builds one rectangle in the world plane named by `orientation`; 'box' builds a closed six-sided box of the full `size` extents (and ignores `orientation`); 'cylinder' builds a `sides`-sided cylinder standing on the y axis, `size.y` tall, closed at the ends `caps` names (it ignores `orientation` — rotate it downstream to lay it down); 'disc' builds one flat `sides`-sided disc in the plane named by `orientation`, the round counterpart of 'plane'. A disc is its own shape rather than a zero-height cylinder because a flat cylinder is the wrong mesh for it: its wall would be a ring of `2 * sides` zero-area triangles per band, and with both caps on it would be two coincident discs facing opposite ways. |
| `size` | vec3 | `[10,10,10]` | >= 0 |  |  | Full extents along world x, y, z, in world units (not half-extents). For 'plane' and 'disc', the component along the normal axis is ignored. For 'cylinder' and 'disc' the two in-plane components are DIAMETERS — x and z for a cylinder, whose height is y — so unequal ones make an elliptic section; a stud of radius 0.3 is size [0.6, height, 0.6]. |
| `center` | vec3 | `[0,0,0]` |  |  |  | World position of the shape's center. |
| `orientation` | enum | `"xz"` |  | `xz`, `xy`, `yz` |  | Which world plane a 'plane' or a 'disc' lies in, and so which axis is its normal: 'xz' is the ground plane (normal +y), 'xy' faces +z, 'yz' faces +x. Ignored for 'box' and 'cylinder'. |
| `subdivisions` | vec3 | `[1,1,1]` | >= 1 |  |  | Quads along world x, y, z — whole numbers, minimum 1. A plane uses the two components of its own axes ([1,1,1] is a single quad, two triangles); a box uses all three, each face taking the two that span it; a cylinder uses only y, the number of bands its wall is cut into up its height (round it, `sides` counts instead); a disc uses none. More subdivisions give finer sampling and a finer uv/raycast target. |
| `sides` | i32 | `16` | 3..256 |  |  | Corners round a 'cylinder' or a 'disc' — whole number, 3..256; ignored by 'plane' and 'box'. The section is the regular polygon INSCRIBED in the ellipse (its corners lie on it), the first corner on +z, so 3 is a triangular prism, 4 a diamond, and a multiple of 4 reaches the full `size` extents exactly. Cost is linear: each wall ring is `sides + 1` points (the extra one duplicates the seam for the uv), each band `2 * sides` triangles, and each cap `sides` points and `sides - 2` triangles. The same name and range as sweepProfile's circle `sides`; the default is 16 rather than its 8 because that one matches a shipped tube asset and this one is meant to read round on its own. |
| `caps` | enum | `"both"` |  | `none`, `top`, `bottom`, `both` |  | Which ends of a 'cylinder' are closed, in extrudePolygon's spelling: 'both' is a closed solid (every edge shared by exactly two triangles once the coincident rim and seam points are welded), 'bottom' alone is a cup, 'top' alone a tube with a lid, 'none' is an open tube. Ignored by every other shape. A cap faces out of the cylinder (+y on top, -y below) and shares no points with the wall, so the rim stays a hard crease and the cap's planar uv is independent of the wall's. |
| `flip` | bool | `false` |  |  |  | Reverse every triangle's winding (and the written `normal` with it, under `normals`), which flips the surface — a plane or a disc becomes a ceiling, a box an inward-facing room, a cylinder an inward-facing shaft. |
| `normals` | bool | `false` |  |  |  | Write a `normal` point attribute (f32 tuple 3): FLAT on every flat face — one face's unit axis on each of that face's points, derived from the same winding the triangles use (so `flip` turns both) — the split-corner shading sweepProfile's 'square' and extrudePolygon give their hard edges, which a box's unshared face points make exact; a cylinder's caps and a disc are flat the same way. A cylinder's WALL is the one curved face, and gets its SMOOTH analytic normal instead (radial on a circle, the ellipse's own normal on an elliptic section), so it shades round with no smoothNormals pass while its rim, whose cap points are separate, stays a hard edge. That holds however few `sides` it has: a 3- or 6-sided prism with `normals` on shades ROUND, not faceted, and so does the renderer's own computed normal with `normals` off, because the wall's points are shared round the ring. A faceted prism needs split corners, which this node does not build: extrudePolygon over a polygon outline gives one. TURN IT ON when this mesh is merged with one that carries a normal (sweepProfile, extrudePolygon, meshFromField): mergePrimitives fills a column missing on one input with its default, (0, 0, 0), and a lit material renders those points black. OFF BY DEFAULT because a stored normal is only right until something moves P, and the renderer computes one from the triangles when none is stored: the commonest use of a plane is displacement into terrain, which would then shade flat on rolling ground, and a box copied onto ROTATED targets keeps its unturned normal unless copyToPoints' `rotateAttrs` names `normal`. A graph that displaces the mesh and still wants a stored normal recomputes it afterwards with smoothNormals. |

## occlusionCull

Removes points whose ORIENTED BOX stands in a line of sight, after first trying to move them out of it. Its subject is three things and nothing else: a cloud of EYE POSES, the TARGETS visible from each of them, and a cloud of boxes that may block the lines between — so it serves a driver who must see the road ahead, a guard who must see the gate, and a camera that must see the actor, with no knowledge of roads, gates or actors in it. The `in` pin carries the boxes: each point's `P` is the box centre, its `rot` (f32x4) the orientation and its `scale` (f32x3) the FULL extents, which are the same three columns spawnInstances reads, so what is tested is what will be drawn. That unit cube scaled by `scale` about P is a separate, INSTANCE convention, the box a unit asset fills: the point's own bounds (boundsMin/boundsMax, the extent in its frame the box nodes cut) are not read, so a grammar's cells take pivotBox and scale = mul(attribute("scale", 3), box("size")) (the cell-to-instance tail) before they are tested here. The `sight` pin carries the lines: its points are the eye positions, raised by `eyeOffset`, and the path through them supplies the targets. FROM EACH EYE THE TEST IS A FAN OF CHORDS, not one chord to the far end, and that is the difference between a rule that works and one that passes vacuously: the requirement is that the next `lookAhead` of PATH be visible, and a box can leave the far point in plain view while standing in front of everything between — a single chord to the end of the run would clear it. `samples` chords are tested per eye, to points evenly spaced in ARC LENGTH along the run ahead. The test itself runs in each box's OWN frame (the slab method over its three axes), never in the world: a box turned into the sight line presents a narrower profile than its world-aligned hull, and on a straight the two agree while through a bend they do not — which is precisely where the rule matters, so testing the hull would check the one case that never fails. `include` DECIDES WHETHER A POINT IS ASKED AT ALL, and a point it switches off is carried to the output unmoved and IN ITS PLACE — never tested, never pushed, never dropped — which is how a class of geometry that is STRUCTURE rather than scenery stays out of a rule about what may stand in a sight line: a tunnel's ribs span the road by construction, and 'clearing' one by shoving it aside opens a hole in the roof it is part of. Doing that with a filter and a merge instead would CONCATENATE, so the exempt points would come out at the end of the cloud and every index after them would shift, which for a cloud copyToPoints or spawnInstances reads in order is a different scene. A blocked point is PUSHED before it is dropped: the node steps it along `pushAxis` in `pushStep` increments up to `pushMax`, away from the sight path, and keeps the first position that clears every chord. Only a point that cannot be cleared by pushing is removed. That order is the point of the node and not an optimisation — pushing PRESERVES THE POPULATION COUNT, so any rule upstream that budgeted a number of points still has that number, and the asset the author placed is still in the scene; dropping spends both. With the default `pushMax` of 0 nothing is pushed and every blocker is dropped, which is the conservative reading: this node will not silently relocate an authored point by a distance nobody chose. DETERMINISM: points are visited in an order fixed by point IDENTITY — the bits of the stored position plus the per-point `seed` attribute — and never by array index, so shuffling the input, filtering something upstream, or deriving the same points inside another cell's halo yields the identical survivor set. Order matters here only when `pushClearance` is above 0, which makes a pushed point avoid the points already settled and so makes one verdict depend on others; below that every point is decided from the sight input alone. HALO: with `pushClearance` at 0 the answer for a point depends on the eyes within roughly `lookAhead + pushMax` of it and on nothing else, so a partitioned cook is exact given a window that wide. Above 0 it is a GREEDY op, and a greedy op has no finite width — this point settled here because that one settled there, an unbounded chain no halo covers — so a per-cell cook will differ from a whole-region one, and the difference shows up as pushed points overlapping at the seams rather than as an error. OUTPUT is a point cloud of the survivors with every point attribute carried, and the input's topology is NOT preserved under any setting. There is no `topology: "keep"` here, unlike the five point filters, for a reason those five do not have: this node MOVES points as well as removing them, and a primitive kept over a moved point would describe a shape nobody authored — a road that follows its lamp posts sideways. Rebuild any network downstream (pointsToPath, connectPoints). One consequence worth stating because nothing else will say it: a PUSHED point comes out with a different `P`, and `P` is half of a point's identity, so anything identity-keyed downstream (filterByDensity's probabilistic mode, selfPrune's tiebreak, randomField) re-rolls for exactly the points this node moved. COST is one occlusion test per (point, nearby eye, sample), so it scales with the eye density of the sight path as well as with the cloud — resample the path to the spacing the rule actually needs rather than to the spacing it happens to have.

**Category:** filter

**Inputs:** `in` (geometry), `sight` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-sightline-cull.json](../graphs/basics-sightline-cull.json) — 1 total (`pcg graphs --node occlusionCull`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `include` | f32 | `1` |  |  | yes | Nonzero (the default) puts the point IN the test: its box is checked against every chord it can reach, and it is pushed or dropped on the answer. Zero takes it out entirely — no chord is ever tested against it, and it is carried to the output UNMOVED AND IN ITS PLACE, between the same two neighbours it arrived between. THAT LAST PART IS WHY THIS IS A PARAM AND NOT SOMETHING A CALLER CAN SPELL WITH A FILTER. Holding a class of points out of this node by filtering them off and merging them back concatenates: the exempt ones arrive at the END of the cloud, every index after the first of them shifts, and a cloud that copyToPoints or spawnInstances reads in order becomes a different scene — so the only way to say 'do not test this point' without also saying 'and put it somewhere else' is here. IT IS NOT A SECOND SPELLING OF `pushMax` 0, and the two cannot compete because they answer different questions: `pushMax` 0 says 'drop this one rather than move it', which is a verdict on a point that WAS tested and did block, while this says the question is never asked — so for an excluded point `pushAxis` and `pushMax` are never read, and it can be neither pushed nor dropped no matter what they say. An excluded point is never a blocker, so nothing about how blockers are handled reaches it. It does still OCCUPY its position: `pushClearance` counts it among the points already settled, exactly as it counts a point that was tested and cleared, because a pushed point has to avoid what is there rather than what was tested. As a FIELD it is evaluated on the `in` points, one flag per point, which is the form this is really for — attribute("cover"), or a comparison against a class column, excludes a KIND of thing rather than a list of indices, and the expression goes on meaning the right thing after the cloud upstream changes length. A non-finite value is refused with the param named, as every field-capable param in this node is: a NaN gate is a broken expression rather than a decision, and it is deliberately not filterByExpression's reading, where NaN means drop. NOTHING IS REPORTED, which a reader has to know before relying on the output: this node writes no column saying which points it tested, so a point it never asked about and a point it asked and cleared are indistinguishable on the way out — both come out exactly where they started. The `include` expression IS the record of the difference, it is one the caller already has, and asking it again is cheaper than a column this node would have to write on every cook for the callers that do not care. |
| `lookAhead` | f32 | `12` | >= 0 |  | yes | How far along the sight path, in world units of ARC LENGTH, must be visible from each eye. The fan's targets are spread evenly over that distance, so this and `samples` together fix the resolution of the test: `lookAhead / samples` is the gap between consecutive targets, and a box narrower than that gap can slip between two chords and be kept. Size them together — halving the gap doubles the cost. As a FIELD it is evaluated on the SIGHT input's points, one look-ahead per eye, which is how a rule that varies along the route is written: attribute("speed") scaled to a stopping distance asks for more sight where the observer is moving faster and less where a tight corner makes the demand impossible to satisfy anyway. A value of 0 leaves the fan with nowhere to go and collapses every chord to the eye position itself, which still asks one question — is the eye INSIDE the box — and nothing more; that is the honest reading of a zero-length line of sight, not an off switch. Negative values are read the same way as 0. A look-ahead longer than the path itself simply clamps at the far end on an open run and wraps on a closed one. This is also the HALO WIDTH a partitioned cook needs, plus `pushMax` and plus the widest box half-diagonal; as a field, use the bound the expression can reach ANYWHERE in the world rather than the largest value present in the cell, which is circular — the cell's cloud has already been clipped by the very halo you are sizing. |
| `samples` | u32 | `8` | 1..1024 |  |  | How many chords make up one eye's fan. The targets sit at `lookAhead * i / samples` for i in 1..samples, so the far end of the run is always tested and the eye's own position never is. The count exists because the rule is about a STRETCH of path rather than a point on it: with samples 1 the test is a single chord to the far end, which a box standing squarely across the middle of the run does not touch — it leaves the far point visible while hiding everything before it, and the cull would keep it. Raise this until the gap between targets is smaller than the narrowest box you care about; lowering it is the cheapest way to make the node faster and the first thing to make it wrong. The ceiling of 1024 is a guard on cost rather than a semantic limit, and the total number of chords (eyes times samples) is bounded again at cook time. |
| `eyeOffset` | vec3 | `[0,1.5,0]` |  |  | yes | World-space offset added to each eye's position on the sight path, in world units. The default raises the eye 1.5 above the path, which is where an observer's eye is relative to the ground they stand on — the reason the param exists at all is that the path is almost always the surface and almost never the viewpoint, and testing from the surface would have every kerb and every rut block the view. The TARGETS are not offset: they stay on the path, because what must be visible is the path itself, and lifting both ends would let a low box hide under a chord that clears it. As a FIELD it is evaluated on the SIGHT input's points, one offset per eye, so a route that climbs into a vehicle and back out again can carry its own eye height; build it with vec(x, y, z), and note that a scalar FIELD broadcasts to all three axes (rarely what an eye height means) while a plain scalar is refused outright. An offset of [0, 0, 0] puts the eye exactly on the path. |
| `pushAxis` | vec3 | `[1,0,0]` |  |  | yes | Direction along which a blocked point is moved before the node gives up and drops it, in world units. Normalized internally, so only its direction is read; the SIGN is chosen by the node, not by the author — a point is pushed in whichever of ±axis takes it FURTHER from the nearest eye, because 'out of the way' has no other meaning when the sight line is the only thing there is to be out of the way of. That is what lets one axis serve both sides of a route without an author writing a sign per point. As a FIELD it is evaluated on the `in` points, one direction per point, which is the form this param is really for: a lateral written upstream by pathSegments or promoted off the road primitive gives every point the outward direction of the stretch it stands on, and a straight world axis stops being an approximation the moment the route turns. A ZERO axis cannot be pushed along, so such a point is dropped the moment it blocks — which is a deliberate way to spell 'this one must never move' for a piece whose whole value is being in line with its neighbours (a row of markers with one shoved out of line reads as a mistake; the same row two markers shorter still reads as a row). `pushMax` 0 says the same thing for the whole cloud. |
| `pushMax` | f32 | `0` | >= 0 |  | yes | Furthest a blocked point may be moved along `pushAxis`, in world units. The default of 0 means NEVER PUSH: every blocker is dropped, and the node is a pure cull. There is deliberately no generous default distance — 6 is a long way in a corridor and nothing at all on a motorway, so a default would either do nothing or silently relocate an authored point by an amount nobody chose, and of the two failures dropping the point is the one an author notices. Set it as soon as the population count matters: pushing keeps the point, keeps the asset, and keeps whatever budget upstream counted, where dropping spends all three. As a FIELD it is evaluated on the `in` points, one allowance per point, and 0 for a point is exactly the 'drop rather than move' exception — attribute("locked") driving it lets a class of props be immovable while everything around them shuffles aside. The search is a ladder of `pushStep` increments and stops at the FIRST distance that clears every chord, so the point moves the least it can rather than the most it may; a point still blocked at `pushMax` is dropped. Widening this widens the halo a partitioned cook needs by the same amount, since a point can be tested against eyes that far beyond where it started. |
| `pushStep` | f32 | `0.5` | >= 0 |  |  | Distance between successive push attempts, in world units. Must be greater than 0 — a step of 0 is a search that never advances, and it is refused rather than silently treated as 'do not push', which is what `pushMax` 0 already says. This is a RESOLUTION knob and not a distance the author cares about: it decides how close to the minimum the found position is, so a point that would clear at 1.2 is placed at 1.5 with the default step and at 1.25 with a step of 0.25. It is deliberately not field-capable — a per-point search resolution is a knob nobody needs and would make two points that started together end up on different ladders, which is a difference in the OUTPUT that no author asked for. Every attempt costs a full sweep of the point's eyes, so the ratio pushMax / pushStep is the per-point cost multiplier and is bounded: a ratio above 4096 is refused with both numbers named. |
| `pushClearance` | f32 | `0` | >= 0 |  | yes | Room a PUSHED point needs at its new position, in world units, measured to the points already settled. It exists because pushing along a shared axis piles blockers up: a dozen props shoved aside from a dozen different eyes all come to rest at the same offset, interpenetrating, and the cull that was supposed to tidy the scene has made a heap in it. With a clearance set, a pushed point skips a rung of the ladder that would land it inside a neighbour and keeps climbing. THIS IS WHAT MAKES THE NODE GREEDY, and the trade is worth stating plainly: at 0 (the default) every point's verdict depends only on the sight input and on the point itself, so the node is embarrassingly parallel, exactly reproducible from a bounded halo, and completely indifferent to visit order. Above 0 a verdict depends on where other points settled, which depends on where THEIR neighbours settled, and no halo width covers that chain — a per-cell cook will disagree with a whole-region one at the seams. The visit order is fixed by point identity either way, so the answer is at least always the same answer. Only PUSHED points are tested: a point that never had to move stays exactly where the author put it and is never dropped for standing too close to something, which is selfPrune's job and not this node's. As a FIELD it is evaluated on the `in` points, so a large prop can demand more room than a small one; it is read on the point being PUSHED, not on the neighbour it is avoiding. |

## offsetBox

MOVES THE FACES of every cell's box OUT, or IN where the offset is negative — the scope offset of a shape grammar, the padding of a bounding box, the inset/outset of a face extrude — and changes nothing else: same points, same order, same seeds, every attribute and the topology carried, only `boundsMin`/`boundsMax` rewritten. A CELL IS A POINT WITH A BOX, as in splitBox: its standard boundsMin/boundsMax, an extent in the point's OWN frame (world = P + rot * (scale * x)), read and written in the coordinates they hold; the faces move along the box's own axes, so P, rot and scale are not read and the offset box turns and moves with its point. THE OFFSETS are boxContact's margins, with boxContact's names and meaning, applied to the box itself instead of to a query: `margin` moves BOTH faces of each axis out (the uniform shorthand — [0.5, 0.5, 0.5] pads the box half a unit all round, [-0.5, -0.5, -0.5] insets it, and a scalar FIELD broadcasts to all three), `marginMin` moves the face on the MIN side of each axis and `marginMax` the face on the MAX side, signed and on top of `margin`: the min face moves out by margin + marginMin, the max face by margin + marginMax, so marginMin -d with marginMax +d SHIFTS the box d, and a box name in a field reads the box as it ARRIVED (marginMax vec(0, 1 - box("y1"), 0) puts the top face at y = 1 wherever it was). All three are vec3, plain or fields resolved per cell. THE FRAME (`frame`, placeBox's) says what the three components are. "box" (the default): [x, y, z] along the box's own axes, min side = the boundsMin corner ("box" was called "world"; that word is refused with the rename stated). "face": the cell's OWN axes [along, up, out], read from the frame shellSplit writes on every piece and splitBox carries onto every piece cut from one — `alongAxisAttr` (the axis code, 0 = x, 1 = y, 2 = z) and `alongSignAttr` for along, `outwardAttr` (the outward normal) for out, and up DERIVED as the axis that keeps along x up = out, shellSplit's right-handed frame, so it need not be written. In "face" the MIN side of a component is the end its axis runs FROM and the MAX side the end it runs TO: marginMax [0, 0, 1] pushes the OUTER face out one unit and marginMin [0, 0, 1] the inner face in, on every wall and the floor and ceiling alike — one rule for a sill standing out of whichever face is outside; marginMin [1, 0, 0] grows the LEFT end as seen from outside; marginMax [0, 1, 0] raises the top. The frame is SELECTED, never inferred from what attributes happen to be present: under "face" a missing frame attribute is refused, naming every one missing, and a cell whose outward normal is not one signed axis (exactly one nonzero component — shellSplit's interior, whose normal is zero, has no out) or whose along axis is not 0, 1 or 2, is the out axis, or has a zero sign, is refused naming the cell; under "box" the frame attributes are not read at all. SNAP (`snap`, a lattice step per box axis [x, y, z], 0 = none, placeBox's) puts the offset box on a lattice afterwards, every face of each snapped axis. `snapTo` "lattice" (the default) moves each face onto the lattice anchored at 0 of the box's coordinates — the cell's P, in its own units — as splitBox's snap, so neighbouring cells that share a frame agree on one lattice; "size" rounds the box's SIZE on that axis to a whole number of steps and keeps its CENTRE, so a footprint grown by a margin and then made a multiple of 8 stays centred on what it grew from (a baseplate of a stock size under a lot). `snapMode` is the same five words on every box node: "round" (the default) goes to the nearest line (or size; a half rounds up), "floor" and "ceil" move every face down or up the axis (the size down or up), "out" GROWS onto the lattice (min face down, max face up; size up), "in" SHRINKS onto it (the reverse; size down). A face within f32 precision of a line counts as on it. COLLAPSE (`fit`): an inset past the box's own size crosses the faces, and a box written inside out is a defect every box node downstream refuses, so the default "error" refuses the cook, naming the cell, the axis, the crossed faces and the offsets; "scale" shrinks the INWARD moves in proportion until the two faces meet (a face that moved out keeps its place, so a one-sided inset past the far face stops ON it), leaving a box of no volume on that axis — and after a lattice snap "in" the meeting point is that proportion, not a lattice line; "allow" writes the crossed box as computed, as setBounds would. FIT GLOSSARY, one meaning per word across splitBox, shellSplit, placeBox and offsetBox: "error" refuses the cook, naming the cell and the numbers; "allow" writes the result as computed; "scale" rescales what does not fit, in proportion, until it fits exactly; "clamp" slides the box back inside, keeping its size, and cuts a box larger than its limit to the limit; "clip" cuts away what passes the limit and keeps the rest, nothing moved or rescaled. This node takes "error", "scale", "allow". Faces on an unsnapped axis that cross by no more than two f32 ulps at their coordinates, plus half an f32 ulp of each inward move (an f32 margin is that far from the decimal it was written as, so insets written to sum to the box meet), MEET under "error" and "scale", put on one stored number; a crossing any larger is a real one, and faces on a snapped lattice axis are lattice lines, so any crossing there is a whole step. Under `snapTo` "size" a size that rounds to no whole step leaves a box of no volume at its centre: that is not a crossing, so `fit` has nothing to settle. An input box already inside out, or not finite, is refused under "error" and "scale". `where` leaves chosen cells exactly as they arrived (0 = untouched, no offset, snap or check), e.g. attributeIs("piece", "sill"). The output keeps every point: a box offset to nothing is a box of no volume, never a dropped point. CPU ONLY, and not a GPU adopter, for boxContact's reason: the offsets decide comparisons — which lattice line a face lands on, whether two faces crossed — and a device-rounded offset one ulp off moves a face a whole lattice step. Use it where a setBounds rebuilt a corner from box("lo") or box("hi") plus an offset: the face moved is then named rather than reconstructed.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-split-box.json](../graphs/basics-split-box.json), [basics-apply-rules.json](../graphs/basics-apply-rules.json), [examples-brick-house.json](../graphs/examples-brick-house.json) — 3 total (`pcg graphs --node offsetBox`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `margin` | vec3 | `[0,0,0]` |  |  | yes | How far BOTH faces of each axis move OUT, per component — [x, y, z] under frame "box", [along, up, out] under "face" — in the box's own units: the uniform shorthand. [1, 1, 1] pads the box one unit all round, [-1, -1, -1] insets it, [2, 0, 2] grows a footprint two units each way and leaves its height. As a FIELD it is resolved per cell on the INPUT (box names read the box as it arrived) and a scalar broadcasts to all three components. Adds to marginMin and marginMax. Must be finite. |
| `marginMin` | vec3 | `[0,0,0]` |  |  | yes | How far the MIN-SIDE face of each axis moves OUT, on top of `margin`, signed (negative pulls it in): under frame "box" the face the boundsMin corner is on, so marginMin [0, 1, 0] lowers the floor one unit; under "face" the end each frame axis runs FROM — the left end along (as seen from outside, on a shellSplit wall), the bottom up, the INNER face out. With marginMax it can shift the box (marginMin -d, marginMax +d moves it d). boxContact's marginMin, with its meaning. As a FIELD it is resolved per cell on the input, and may read the box names. Must be finite. |
| `marginMax` | vec3 | `[0,0,0]` |  |  | yes | How far the MAX-SIDE face of each axis moves OUT, on top of `margin`, signed: under frame "box" the face the boundsMax corner is on; under "face" the end each frame axis runs TO — the right end along, the top up, the OUTER face out, so marginMax [0, 0, 1] stands a sill one unit out of whichever face of its wall is outside. boxContact's marginMax, with its meaning. As a FIELD it is resolved per cell on the input, and may read the box names: marginMax vec(0, 1 - box("y1"), 0) puts the top at y = 1. Must be finite. |
| `frame` | enum | `"box"` |  | `box`, `face` |  | What the three components of the margins mean — placeBox's `frame`, with its meaning. "box" (the default): the box's own axes [x, y, z], min side the boundsMin corner — the frame attributes are not read (it was called "world"; that word is refused with the rename stated). "face": the cell's own axes [along, up, out] from the frame shellSplit writes (`alongAxisAttr`, `alongSignAttr`, `outwardAttr`; up is derived, completing the right-handed frame along x up = out), min side the end each axis runs from — so one offset reads the same on every wall, floor and ceiling of a shell. Selected here, never inferred: under "face" a missing frame attribute is refused, naming every one missing. Decided once per cook. |
| `alongAxisAttr` | string | `"alongAxis"` |  |  |  | Read only under frame "face": the tuple-1 numeric point attribute holding each cell's ALONG axis code, 0 = x, 1 = y, 2 = z — shellSplit's `alongAxisAttr`, carried by splitBox onto every piece. Any other value, or the out axis itself, is refused naming the cell. |
| `alongSignAttr` | string | `"alongSign"` |  |  |  | Read only under frame "face": the tuple-1 numeric point attribute holding the direction ALONG runs, its sign read (+1 or -1; shellSplit's `alongSignAttr`, left to right as seen from outside on a wall). Zero — what shellSplit leaves on a cell its `where` passed through — has no direction and is refused naming the cell, and so is a non-finite value. |
| `outwardAttr` | string | `"outward"` |  |  |  | Read only under frame "face": the tuple-3 numeric point attribute holding each cell's OUTWARD normal — shellSplit's `outwardAttr`. It must be ONE signed axis (exactly one nonzero component; its sign is the side), which is what makes the out component of a margin a face of the box; shellSplit's interior, whose normal is [0, 0, 0], and any tilted normal, are refused naming the cell. |
| `snap` | vec3 | `[0,0,0]` | >= 0 |  |  | A LATTICE STEP per box axis [x, y, z] — in every frame, since a lattice is the box's, anchored at 0 of its coordinates (the cell's P, in its own units) — applied after the offset to every face of each axis whose step is not 0 (0 = no snapping, the default). How depends on `snapTo` and `snapMode`. splitBox's and placeBox's snap: snap [1, 0.4, 1] keeps a box on a brick lattice of 1-stud by 1-plate cells. |
| `snapTo` | enum | `"lattice"` |  | `lattice`, `size` |  | What `snap` rounds — placeBox's `snapTo`. "lattice": each face onto the ABSOLUTE lattice anchored at 0, as splitBox's snap, so neighbouring boxes share lines. "size": the box's SIZE on the axis to a whole number of steps, keeping its CENTRE — the box grows (or shrinks) equally at both faces, which is how a lot padded two studs each way becomes a stock 8-stud-multiple baseplate centred under it (margin [2, 0, 2], snap [8, 0, 8], snapTo "size", snapMode "out"). Under "size" an axis whose size is already negative is left for `fit`, and a size that rounds to no whole step is a box of no volume at its centre. Decided once per cook. |
| `snapMode` | enum | `"round"` |  | `round`, `floor`, `ceil`, `out`, `in` |  | Which way a face (or a size) lands on the `snap` lattice — the same five words on every box node. "round" (the default): the nearest line or size, a half rounding up. "floor" / "ceil": every face down / up the axis, both the same way (the size down / up). "out": the box GROWS onto it — the min face to the line at or below it, the max face to the line at or above it, the size up — so a padded box never loses what the offset gave it. "in": it SHRINKS onto it (the reverse), which can cross the faces of a box with no whole step inside it, for `fit` to settle. Ignored where the step is 0. Decided once per cook. |
| `fit` | enum | `"error"` |  | `error`, `scale`, `allow` |  | What happens when an inset (or an inward snap) crosses a box's two faces on an axis. "error" (the default) refuses the cook, naming the cell, the axis, the faces and the offsets — a box written inside out is refused by every box node downstream, so it is caught where it is made. "scale" shrinks the INWARD moves of the two faces in proportion until they meet, which leaves the box no volume on that axis — a symmetric inset past the middle stops at the centre, and a face that moved OUT keeps its place, so a one-sided inset past the far face stops on it. "allow" writes the crossed box as computed, as setBounds would. FIT GLOSSARY, one meaning per word across splitBox, shellSplit, placeBox and offsetBox: "error" refuses the cook, naming the cell and the numbers; "allow" writes the result as computed; "scale" rescales what does not fit, in proportion, until it fits exactly; "clamp" slides the box back inside, keeping its size, and cuts a box larger than its limit to the limit; "clip" cuts away what passes the limit and keeps the rest, nothing moved or rescaled. This node takes "error", "scale", "allow". On an unsnapped axis, faces crossing by no more than two f32 ulps at their coordinates plus half an f32 ulp of each inward move MEET under "error" and "scale", on one stored number. An input box that is already inside out or not finite, and an offset that takes a face past what f32 bounds hold, are refused under "error" and "scale", and written as computed under "allow". Decided once per cook. |
| `where` | f32 | `1` |  |  | yes | Which cells are offset: nonzero offsets the cell, 0 leaves it EXACTLY as it arrived — no offset, no snap, no fit check, and its frame values not read (under frame "face" the frame attributes must still exist, so their columns can be looked up once). As a field it is resolved per cell, e.g. attributeIs("piece", "sill"). A non-finite value is refused naming the cell. |

## orientAlongVector

Sets the standard rot point attribute (f32 tuple 4 quaternion, [x, y, z, w]) so the chosen local axis points along `direction`, with `up` fixing the roll. The quaternion is right-handed and matches the spawner path's three.js Matrix4.compose conventions (and quatFromEulerDeg's frame), so with the default '+z' axis, spawned assets face the direction the way the spline-fence example's tangent yaw does. For axes ±x and ±z the local +Y axis turns as close to `up` as the direction allows; for axes ±y (which consume the up-like axis) local +Z takes that role. Points with a zero-length direction keep their existing rot (identity when the attribute is newly created). When direction and up are parallel or antiparallel (cross product squared length <= 1e-12, after normalizing both), the up hint deterministically falls back to [0, 0, 1], then [1, 0, 0].

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-orient-along-vector.json](../graphs/basics-orient-along-vector.json), [basics-orient-along-path.json](../graphs/basics-orient-along-path.json), [basics-where-bars-cross.json](../graphs/basics-where-bars-cross.json) — 13 total (`pcg graphs --node orientAlongVector`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `direction` | vec3 | `[0,0,1]` |  |  | yes | World-space direction the chosen local axis should point along; need not be unit length. Field-capable (resolved per point on the input, e.g. a tangent attribute; tuple 1 broadcasts). Zero-length directions leave that point's rot unchanged (identity when the rot attribute did not exist before). |
| `up` | vec3 | `[0,1,0]` |  |  | yes | Up hint fixing the roll around the direction; need not be unit length. When parallel/antiparallel to the direction (or zero), deterministically falls back to [0, 0, 1], then [1, 0, 0]. Field-capable (resolved per point on the input; tuple 1 broadcasts). A per-point up is what a curve that turns over needs: a CONSTANT up flips the roll a half turn as the direction passes through it, and everything placed along the curve snaps round with it — feed writeCurveFrame's `curveNormal` here instead and the roll varies smoothly. A field `up` keeps this node OFF the device-resident path, because the apply kernel bakes the normalized up in as a constant; the cook reports that by name in its fallbacks rather than silently producing different bytes. |
| `axis` | enum | `"+z"` |  | `+x`, `-x`, `+y`, `-y`, `+z`, `-z` |  | Which local axis maps onto the direction. Default '+z' — the forward axis assets face in the examples (a spline-fence style tangent yaw). For ±x/±z the local +Y follows the up hint; for ±y the local +Z follows it. |

## packBricks

Reads axis-aligned BOXES on a stud lattice — one per point, its corners in two point attributes, an extent in the point's OWN frame as every box node reads boundsMin/boundsMax (world = P + rot * (scale * corner)); the lattice is axis-aligned, so a point must carry the identity rotation and scale [1, 1, 1], and one that does not is refused naming it — and writes the BRICKS that build them: one point per brick, from a stated catalogue of footprints, that together fill exactly the lattice cells the boxes cover. The lattice is `pitch` in world units per cell (a stud is 1 across, a plate 0.4 tall, by default), anchored at `origin`; x and z count studs and y counts plates. Every corner must land on the lattice, and one that does not is refused naming the point and the corner, because a box half a stud off is a box the graph upstream built on a different lattice. Boxes may overlap: their cells are unioned, and a cell two boxes claim belongs to the one with the lower point IDENTITY (stored position bits plus `seed`), never the lower array index, so shuffling the input changes nothing — unless two overlapping boxes share both P and `seed`, which identity cannot tell apart, and then the earlier one in the input wins. WHAT A BRICK MAY NOT CROSS is `groupBy`: cells whose boxes differ in any listed attribute are different material and never share a brick, so a wall's colour changes exactly where its boxes' colour does. Each brick carries every point attribute of the box that owns its anchor cell. THE PACKING IS A SCANLINE GREEDY, course by course from the bottom and within a course in z then x. The first unfilled cell of a scan is always the minimum corner of the brick that covers it, so the scan is complete without backtracking; the choice there is WHICH catalogue entry, either way round. HEIGHT COMES FIRST: the tallest entry that fits is the course, so a wall is laid in full bricks and plates appear only where the space is shorter than a brick. Among footprints of that height the score is the footprint in studs less `stagger` for every stud of joint in the brick's bottom course that sits directly on a seam in the course below, counted only on the joints the placement decides — where the cell across is the same material and not yet filled — a running bond, the reason real walls hold together, charged only where a different brick could have avoided it — PLUS `bond` for every two separate pieces the placement joins into one, which is what keeps a floor or a roof laid over an empty room from coming out as loose plates (pieces as stud clutch holds them; see `islandsAttr`). AHEAD OF THAT SCORE, WITHIN THE HEIGHT, COMES WHAT HOLDS. A brick is gripped only through its top and bottom faces, so a placement with no brick under its footprint and no cell to be filled over it — a plate in the middle of a one-plate floor, over an empty room and under another — is loose in every build order. A placement that would leave a cell beside it with no HELD placement left to cover it STRANDS the cell: whatever brick covered it would be loose too. So each placement is charged the loose bricks it commits the build to — one if it is held by nothing, plus one for every cell it strands — and the fewest wins, then a held placement over one held by nothing, then the score. Both charges only ever decide where a course has cells with nothing under or over them; a wall, or anything standing on what is below it, packs by the score alone. Ties go to the larger footprint, then the earlier catalogue entry, then the entry as listed rather than turned. If nothing fits — a catalogue with no 1x1 plate meeting a one-plate gap — the cell is refused by name rather than left empty, so the output always covers the input exactly. THE HOLD SEARCH answers what that one-placement look cannot see: a trap set two or more placements back, an early brick that took the grip a later cell needed. Wherever a course comes out with a brick held by nothing, that course is laid again with each REGION around such a brick — the course's cells of that material that were unfilled when the course began, joined side to side — packed by an EXACT search for a packing in which every brick is held: depth first over the held placements alone, first in scan order and then from the cell the fewest of them cover, each cell's placements tried by the same score, a placement dropped the moment it leaves a cell of the region with no held placement over it, and a failure going straight back to the latest placement to blame for it. Its first answer is the greedy's own choice wherever that choice holds. It is bounded in STEPS of work, never in time, so the result is the same on every machine and under any load: 2097152 per region and 8388608 per cook, a few milliseconds for the regions a generated house has and some 30 ms at the bound. Where the search in scan order runs out, three more answers are asked, each exact and each bounded in steps of its own (4194304 and 1048576 per region, 16777216 per cook, for the first and last; 1048576 per region and 8388608 per cook, and at most 128 cells, for the second): first two proofs that no held packing exists, before the search from the fewest goes on — a PARITY proof, if no set of held placements covers every cell of the region an odd number of times, which is what rules out a one-plate floor walled round whose middle every plate reaches only by an even length, a 21 x 21 slab among them, and PROBES, cases on one cell: each held placement over it is taken in turn with every placement it forces (a cell left exactly one held placement clear of those taken), and if each comes to a cell nothing can cover, or to two forced placements that overlap, no packing exists, which is what rules out a floor over posts too far apart, where a cell only a baseplate reaches leaves another such cell nothing — and, where the search from the fewest runs out as well, a packing by STRAIGHT CUTS — the region's bounding box cut across, again and again, into rectangles each empty or one held catalogue entry — which finds the baseplate-and-strips packings of a big walled slab that a search laying one brick at a time from a corner does not reach. A region proven to have no held packing (a cell no held brick can reach is the usual proof, the parity count and the probes the next most common), one nothing answered within its budget, and one that mixes brick heights are laid by the greedy as before — byte for byte in a course where no region was solved; where one was, its bricks can join pieces the greedy weighs elsewhere in the course. The course is laid again only from the first cell of its new regions, every brick before it kept, and a brick after it is weighed again only where something the greedy reads there — the course's cells round it, the pieces under it — can differ from the laying before; everywhere else the earlier choice stands, so the course comes out brick for brick as laying all of it again would. A course with no brick held by nothing is never searched, so it packs exactly as the greedy alone does. Where the search ran on a course as laid (the regions the ground repair below asks for are its own, and counted there), `out` carries a DETAIL u32 `holdSearch` of four counts — regions searched, solved, proven to have no held packing, and left to the greedy unproven (budget spent, or heights mixed) — and where it never ran there is no such attribute. A BRICK CAN BE HELD AND STILL HANG FROM NOTHING: bricks that hold each other across two or more courses — a floor's edge row under a roof's edge column — with none of them standing on anything that reaches the bottom course, which no look at one course sees. So the finished build is asked what brickConnectivity asks for step -1: the pieces stud clutch makes, and whether each holds a brick of the bottom course. A piece that does not is FLOATING, and is repaired course by course, its lowest first: the build is taken back to that course and laid again from it, with the regions round the piece's bricks there packed by the hold search under one more demand — a brick over a cell of the piece must also cover a cell standing on a brick of a piece that already reaches the bottom course — and every course above laid on that as usual. A repair is kept only if the build it makes, asked again, floats fewer bricks; otherwise the build is put back exactly as it was. A course where a brick of the piece lies in a region the hold search came back from without a held packing is not asked (a firm packing is a held one). Each course asked costs every cell from it up, against a budget of 1048576 cells per cook, never time. Where something floated, `out` carries a DETAIL u32 `groundRepair` of six counts — floating pieces and their bricks before the repair, the same after it (as asked of the finished build, never assumed), courses asked, and repairs kept — and where nothing floated there is no such attribute and the build is packed exactly as without the repair. OUTPUT `out`: one point per brick in scan order. P is the brick's centre, `rot` a quarter turn about y when the entry was placed turned (identity otherwise), and `scale` its full extents in its OWN frame — w and d studs and h plates as listed, in world units — so a unit box copied onto these points draws every brick in place. `boundsMin`/`boundsMax` are the UNIT box, [-0.5, -0.5, -0.5] to [0.5, 0.5, 0.5]: the brick's box in its own frame, world = P + rot * (scale * x) with `scale` its extents, which is how brickConnectivity and every box node read it. So the box names on a brick describe the unit box, and a WORLD fact about a brick comes from its transform: the bottom of a brick turned only about y is P.y - 0.5 * scale.y, sub(component(position(), 1), mul(0.5, component(attribute("scale", 3), 1))). `brick` (string) is the entry as `WxDxH`, ready to be spawnInstances' `assetAttr`, and `brickIndex` (i32) is its position in the catalogue — `bricks` followed by `extraBricks`. OUTPUT `studs`: one point per stud left SHOWING — on a brick's top where the lattice cell above is empty — at the stud's base centre on the brick's top face, carrying the brick's attributes and its `brick`/`brickIndex`, plus `brickId` and `brickAbove` (the indices in `out` of the brick it stands on and the brick resting on it, -1 for none; see `studMode`, which can ask for every stud instead), with identity `rot` and unit `scale`, so a stud mesh modelled at world size with its base at the origin spawns straight onto it; the bounds columns are reset to the zero box (at P). `islandsAttr` optionally writes a DETAIL u32 on `out` counting the pieces the build falls into when only stud CLUTCH holds it — a brick is joined to the bricks sitting on its top face where their footprints overlap, and side contact does not count, so a value above 1 is a build that comes apart when lifted. HALO: none. A brick spans cells, so cooked over part of the boxes it cuts bricks at the part's edge; this belongs on an unbounded level or before a split. Not GPU-eligible: the packing is sequential by construction. The occupancy grid is dense over the boxes' joint extent and refused past 16.7 million cells.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry), `studs` (geometry)

**Examples:** [basics-pack-bricks.json](../graphs/basics-pack-bricks.json), [examples-brick-house.json](../graphs/examples-brick-house.json) — 2 total (`pcg graphs --node packBricks`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `minAttr` | string | `"boundsMin"` |  |  |  | POINT attribute (f32 or i32, tuple size 3) holding each box's minimum corner in the point's OWN frame, as every box node reads boundsMin: the world corner is P + this (the point must carry the identity rotation and scale [1, 1, 1]). Converted to lattice cells through `pitch` and `origin` and refused, naming the point, unless every component lands on a lattice plane. |
| `maxAttr` | string | `"boundsMax"` |  |  |  | POINT attribute (f32 or i32, tuple size 3) holding each box's maximum corner in the point's own frame, on the same terms as `minAttr`. A box with a maximum below its minimum on any axis is refused; one with zero extent on an axis covers no cells and is skipped. |
| `pitch` | vec3 | `[1,0.4,1]` |  |  |  | World size of one lattice cell: [stud, plate, stud]. The default is the proportion of the familiar toy brick, a plate being 0.4 of a stud's width and a full brick three plates. x and z must be EQUAL, because a stud is square and a brick turned a quarter turn has to land on the same lattice it left; every component must be positive. |
| `origin` | vec3 | `[0,0,0]` |  |  |  | World position of a lattice corner. Corners are read as origin + k * pitch for whole k on each axis, so a set of boxes built on integer studs but shifted by half a stud is packed by moving this, not the boxes. |
| `bricks` | numberList | `[2,8,3,2,6,3,2,4,3,2,3,3,2,2,3,1,8,3,1,6,3,1,4,3,1,3,3,1,2,3,1,1,3,2,16,1,2,12,1,2,10,1,2,8,1,2,6,1,2,4,1,2,3,1,2,2,1,1,12,1,1,10,1,1,8,1,1,6,1,1,4,1,1,3,1,1,2,1,1,1,1]` |  |  |  | The CATALOGUE, as a flat list of [w, d, h] triples: w studs along x, d studs along z, h plates tall, all whole numbers of at least 1, in the brick's own frame. Each entry may also be placed a quarter turn about y (d along x, w along z), so [1, 4, 3] and [4, 1, 3] are the same brick and listing both is refused. The ORDER is the last tie-break: two entries of equal height, footprint and seam cost go to the earlier one. The default holds the common full-height bricks (h 3) from 1x1 to 2x8, and plates (h 1) from 1x1 to 2x16. Without [1, 1, 1] some occupancies cannot be covered at all — a gap one plate tall and one stud wide — and the cook is refused at the first such cell rather than leaving it empty. To ADD to this list rather than replace it, leave it alone and use `extraBricks`. |
| `extraBricks` | numberList | `[]` |  |  |  | More catalogue entries, APPENDED to `bricks` — the default list or a given one — in the same flat [w, d, h] form and on the same terms: whole numbers of at least 1, either way round. This is how a graph asks for the default catalogue plus one baseplate, [32, 32, 1], without copying the 81 numbers of the default. Appended entries come AFTER every `bricks` entry, so they lose the last tie-break to it, and their `brickIndex` continues the count: the first is entry bricks.length / 3. AN ENTRY ALREADY IN THE CATALOGUE IS REFUSED, not skipped — one in `bricks` (either way round) or earlier in `extraBricks` — naming both entries, because a brick listed twice is a list that did not say what its author thought it said, and skipping it would move every later `brickIndex` silently. Empty (the default) adds nothing. |
| `groupBy` | stringList | `[]` |  |  |  | POINT attributes whose values a brick may not cross: two cells whose owning boxes differ in ANY listed attribute (any type, every component compared exactly; strings by value) never share a brick. Typically the colour and the kind — a window's glass is not one brick with the wall around it. Empty (the default) packs every cell as one material. A name the input does not carry is refused, listing what it does carry. |
| `stagger` | f32 | `3` | >= 0 |  |  | The cost, in studs of footprint, of one stud of JOINT in a placement's bottom course that sits directly on a seam in the course below — a joint edge where the two cells beneath it belong to different bricks. Only the joints the placement DECIDES count — where the cell across is the SAME material and not yet filled, so a different brick could still have bridged it: a joint against another colour, empty space or a brick already standing is one every candidate shares, and charging for it would only favour short bricks. Height is not traded against it — the tallest entry that fits is chosen first — so this decides among footprints of one height. At the default of 3 a 1x8 whose end continues a seam scores 8 - 3 = 5 and loses to an unbroken 1x6 at 6, and a 2x8 with both studs of its end on a seam scores 10 against a 2x6's 12; a 1x2 on a seam (-1) loses to a 1x1 (1). 0 packs largest-first and lets seams run straight up a wall. |
| `bond` | f32 | `16` | >= 0 |  |  | The reward, in studs of footprint, for every two separate PIECES a placement joins into one — pieces as stud clutch alone holds them, every piece already standing on the bottom course counting as one (the table holds those together). A plate laid over an empty room touches nothing below and starts a piece of its own; it is held only if something in a course above bridges it to the rest, and this is what makes the packer choose that bridge. Height is still chosen first and the join is weighed against `stagger` within it, so a wall, where everything below is already standing, packs exactly as with 0. The default of 16 is a 2x8 plate's worth: measured over forty generated houses, 0 left 378 bricks that no build order could attach and 5 houses in one piece; with the longer default plates 220 and 11; adding a bond of 16 brought that to 24 bricks and 34 houses, and no value above it did better than 22. 0 ignores what holds together. |
| `studMode` | enum | `"exposed"` |  | `exposed`, `all` |  | Which studs the `studs` output carries. 'exposed' (the default) is the finished build: only studs with nothing resting on them. 'all' is every stud of every brick's top face, whether or not a brick sits on it — what a PARTIAL build shows, since a stud is covered only once the brick above it is placed. Either way each stud carries `brickId`, the index in `out` of the brick it stands on, and `brickAbove`, the index of the brick resting on it or -1; wire this pin into brickConnectivity's `studs` input and it writes both steps onto each stud — `step`, of the brick it stands on, and `stepAbove`, of the brick resting on it (-1 for none or for one never attached) — so 'stud is showing after step t' is `step` >= 0 and `step` <= t and (`stepAbove` < 0 or `stepAbove` > t). |
| `islandsAttr` | string | `""` |  |  |  | Optional DETAIL attribute (u32) on `out` receiving how many separate pieces the bricks form when only stud clutch holds them together: a brick joins every brick sitting directly on its top face with an overlapping footprint, and side-by-side contact does not join. 1 is a build that lifts as one piece. Empty (the default) writes nothing. |

## partitionByAttribute

Splits the input into one point cloud per distinct value of an i32, u32, or string point attribute (tuple 1). The output collection holds the groups in order of each value's first occurrence; every group carries all point attributes and is tagged `<name>=<value>` (plus the input's tags) so downstream nodes can route by tag.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-partition-by-attribute.json](../graphs/basics-partition-by-attribute.json), [basics-foreach-per-group.json](../graphs/basics-foreach-per-group.json), [examples-rig.json](../graphs/examples-rig.json) — 3 total (`pcg graphs --node partitionByAttribute`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"name"` |  |  |  | Point attribute to partition by. Must be i32, u32, or string with tuple size 1. |

## pathClip

CUTS every polyline where `field` changes sign and keeps the pieces where it is >= 0, as polylines of their own — the path node that changes TOPOLOGY by value. pathRuns, pathScan and runFit write attributes over a path's runs and never cut it; a point filter drops points and the whole path's topology with them; this node cuts the path itself, at the place the value crosses zero rather than at the nearest vertex, so a road clipped by a region ends ON the region's edge. THE RULE: `field` is resolved at every vertex; a vertex whose value is >= 0 is KEPT (exactly 0 counts as kept), one whose value is < 0 is cut away. A segment whose two ends disagree is a CROSSING and gets exactly ONE cut point, found by a bracketed root search on the field along that segment — a secant step, falling back to bisection whenever the secant failed to halve the bracket — which is EXACT FOR A FIELD LINEAR ALONG THE SEGMENT (a plane, a slab face, an arc coordinate) and converges to a sign change for any other. The cut point is the last position the search found on the KEPT side, so every emitted point evaluates >= 0. A segment whose ends AGREE is never searched, so a field that dips below zero and back between two vertices is not seen: that is the vertex sampling's resolution, and pathResample first is the fix. A RUN is a maximal kept piece: [entry cut] + consecutive kept vertices + [exit cut]. A cut that lands exactly on its kept vertex is not emitted a second time, so a vertex at exactly 0 ends its run there. A run with fewer than 2 points, or whose length is < `minLength`, is DROPPED. CLOSED PATHS: a closed path with every vertex kept comes back CLOSED and whole; one with none kept disappears; otherwise every run is OPEN, and a run may CROSS THE SEAM — the closing segment is an ordinary segment of the ring, so a piece straddling the start is one run and not two. ORDER is deterministic: runs follow their source polylines in primitive order, and within one polyline they are ordered by the walk index of their first KEPT vertex (on a closed path the run that crosses the seam is therefore the one whose first kept vertex comes latest). WHAT THE POINTS CARRY: a kept vertex is copied with every point attribute it had, its seed included; a cut point takes P from the search and every f32 column LERPED between its segment's two ends at the cut, while integer, bool and string columns come from the segment's KEPT end — and its `seed` is re-drawn from this node's seed, the source primitive and the segment index, so a cut point never shares its kept neighbour's identity. (A lerped `rot` is not renormalised.) A point visited by two polylines is emitted once per run that visits it. Vertex attributes are not carried. PRIMITIVE ATTRIBUTES ARE CARRIED to every run cut from their polyline (primtype excepted, as everywhere), so a clipped road stays a road; DETAIL attributes are carried unchanged. Points on no polyline, and primitives that are not polylines, do not reach the output. OPT-IN REPORTS: `runIndexAttr` (i32 primitive: which surviving run of its source polyline this is, 0, 1, ...), `lengthAttr` (f32 primitive: the run's length) and `arcAttr` (f32 point: distance along the run from its first point). An input with points but no polyline is refused, as every path node refuses one; an input with no points cooks to an empty output. DETERMINISM is structural: nothing is random beyond the seeded cut-point identities, and each crossing's search reads only its own segment. Topology downstream is as fragile as everywhere: a node that can REMOVE points turns these runs back into a cloud.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-clip-a-path.json](../graphs/basics-clip-a-path.json) — 1 total (`pcg graphs --node pathClip`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `field` | f32 | `0` |  |  | yes | The signed value that decides what is kept: >= 0 is kept, < 0 is cut away. A plain number keeps everything (>= 0) or nothing (< 0), so this param only means something as a field — a half-space is dot(sub(position(), p0), n), a slab is sub(h, abs(sub(component(position(), 1), y0))), a ball is sub(r, length(sub(position(), c))), a window along a path is a comparison of an arc coordinate written by pathScan. RESOLVED ON POINTS, WITH POSITION FREE: at every input vertex it is resolved on the input itself; during the root search it is resolved on PROBE points the node builds, one per unsettled crossing, standing on the crossing segment — each probe carries exactly what the cut point there would carry (f32 columns lerped, the cut's own seed, the rest from the kept end), so attribute() reads the value AT the probe, randomField draws what it will draw on the emitted cut, and a position-only field sees only position. The two agree exactly at the vertices. `fraction` and `index` are REFUSED by name, because on a probe they measure the batch of crossings being searched rather than any place on the path. A field built with the code combinators carries no spec and cannot be screened; keeping it free of those two is then the author's promise. NaN or ±Infinity anywhere is refused, naming this param: a value that could not be computed says nothing about which side of a boundary it is on. The search is EXACT for a field linear along a segment and converges to a sign change for any other; for a noise, sample the path densely first (pathResample) — a sign change between two agreeing vertices is invisible to it. |
| `minLength` | f32 | `0` | >= 0 |  |  | Runs SHORTER than this, in world units along the run, are dropped — the stubs a boundary leaves where it grazes a path. 0 (the default) keeps every run of at least two points; a run of ONE point is never a polyline and is dropped whatever this says. Measured on the emitted run, cut points included, over the f32 positions it will carry, so it is the length a downstream node measures; a closed path kept whole is measured round its closing segment too. Must be finite and >= 0. |
| `runIndexAttr` | string | `""` |  |  |  | OPT-IN REPORT: name of an i32 PRIMITIVE attribute receiving each run's ordinal among the runs cut from its source polyline — 0, 1, 2 ... in emission order (walk order of each run's first kept vertex), counting only runs that survived `minLength`, so the numbers are dense. It answers 'which piece of this road am I', which the carried primitive attributes cannot, since every piece of one polyline carries the same ones. A reporting slot: an existing primitive column of the same name and shape (a carried one included) is reset; one of another shape is refused rather than deleted. May not equal `lengthAttr`. Empty (the default) writes none. |
| `lengthAttr` | string | `""` |  |  |  | OPT-IN REPORT: name of an f32 PRIMITIVE attribute receiving each run's LENGTH in world units, measured as `minLength` measures it — on the emitted f32 positions, the closing segment included for a path kept whole and closed. A reporting slot with the rules `runIndexAttr` states. Empty (the default) writes none. |
| `arcAttr` | string | `""` |  |  |  | OPT-IN REPORT: name of an f32 POINT attribute receiving each point's distance along its run from the run's FIRST point, in world units — 0 at every run's start (an entry cut, or the path's own first kept vertex), the run's length at its last point. It restarts per run, so it composes with pathPointAt's 'distance' mode, transferAlongPath and arcTile on each piece. On a closed path kept whole it reads from the path's first point and leaves out the closing segment, which ends where the coordinate is already 0. A reporting slot checked against the OUTPUT'S point columns — the input's, carried across — so a same-shape column is reset and another shape is refused. Empty (the default) writes none. |

## pathCoverage

Measures, at every point of the `path` input, whether that point is COVERED from some direction by any of the oriented boxes in the `boxes` input, and writes the answer as point attributes: coveredAttr gets a bool (did at least minHits rays hit anything), hitsAttr gets the u32 count of rays that did. The test is a FAN OF REAL RAYS IN WORLD SPACE — rayCount segments running from `near` to `far` along `direction`, offset evenly across the path over -spread..+spread — intersected against each box as an oriented box (position from P, orientation from rot, extent from boxSize times scale, the same columns spawnInstances reads), by the slab method in the BOX'S OWN frame. It casts rays rather than testing path-relative bounds because a bounds projection onto a folded centreline cannot tell 'above the path here' from 'near the path twice': that mistake put a single object near a hairpin in credit for 78 half-widths of lap on 6 half-widths of geometry, and the 32.3% figure it produced was simply wrong. Three cheaper proxies for the same question disagreed with each other by a factor of six; the ray cast is the one that converges as the far plane moves, because a fold is two different places in the world and one place in arc length. A FAR PLANE IS LOAD-BEARING: with no ceiling the sky is a tunnel, so `far` is a real distance and not a sentinel for infinity. Rays are counted DISTINCT, not per box — three boxes stacked over the same two rays is two hits, not six, because the question is whether cover spans the corridor and not how much of it there is. THIS NODE ADDS A COLUMN AND REMOVES NOTHING: points, vertices, primitives, the polyline topology and every existing attribute come through untouched, so a path goes in and the same path comes out one column wider. That is the opposite of the point filters (filterByAttribute, filterByExpression, filterByDensity, filterByBounds, selfPrune), which rebuild the point domain from the survivors and take the topology with it — measure first with this node, then filter on the attribute it wrote if dropping points is what you wanted. It is ORDER-INDEPENDENT by construction: no point's answer depends on any other point, no box's on any other box, and nothing is accumulated in floating point, so the output is identical whatever order the boxes arrive in and the node is EXACTLY CELL-INVARIANT under a partitioned cook given a halo of hypot(spread, max(|near|, |far|)) + the largest box's bounding-sphere radius (half the length of its boxSize*scale vector) — a cell that sees every box within that distance of it computes exactly what the whole world would. Cost is O(path points x candidate boxes): boxes are indexed in a two-tier structure, a uniform grid over the ones no larger than the ray reach (queried as a 3x3x3 block) plus a linear tier for the rest, bounded at half the cloud by splitting at the median radius.

**Category:** attribute

**Inputs:** `path` (geometry), `boxes` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-under-cover.json](../graphs/basics-under-cover.json) — 1 total (`pcg graphs --node pathCoverage`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `direction` | vec3 | `[0,1,0]` |  |  | yes | World direction the rays are cast along, from each path point; need not be unit length. The default [0, 1, 0] asks the question this node was built for — what is ABOVE the path — but the axis is free: cast along -Y to ask what the path stands on, or along a horizontal axis to ask what walls it in. As a FIELD it is PER PATH POINT, resolved on the path's own point domain, which is how a banked or rolled path asks about its own local up rather than the world's: pass attribute("N") or a curve frame's normal and each point casts along the surface it belongs to. A zero-length direction is REFUSED, naming the point — unlike orientAlongVector, where a zero direction has the honest reading 'leave this point alone', a coverage query with no cast direction has no answer at all, and reporting 'not covered' for it would be exactly the plausible-looking cook this library refuses to produce. |
| `near` | f32 | `0` |  |  | yes | Where each ray STARTS, as a distance along `direction` from the path point. This is the floor of the test, and it is what stops the path's own surface — and anything lying on it — from counting as cover over it: on a road, set it above the tallest kerb and below the lowest thing that could ever be a roof. Negative values start the ray behind the point. As a FIELD it is per path point. Together with `far` and `spread` it fixes the ray reach hypot(spread, max(\|near\|, \|far\|)), which is the halo this node needs under a partitioned cook. |
| `far` | f32 | `10` |  |  | yes | Where each ray ENDS, as a distance along `direction` from the path point. THE FAR PLANE IS LOAD-BEARING AND HAS NO 'UNLIMITED' SETTING: with an unbounded ray the sky is a tunnel and the answer is 100% everywhere, so this is a real distance chosen for the scene — the height above which something overhead has stopped being cover and started being scenery. A measurement whose value is that today's figure can be compared with yesterday's must not move when a placement rule is retuned, so prefer restating the number here to importing it from whatever placed the boxes. `far` less than `near` describes the same segment reversed and is legal; `far` equal to `near` collapses each ray to a point and asks pure containment. As a FIELD it is per path point. |
| `rayCount` | i32 | `6` | >= 1 |  |  | How many rays in the fan, spread evenly across -spread..+spread WITH BOTH EDGES INCLUDED. 1 casts a single ray straight through the point and ignores `spread`. A single centre ray is not enough for anything wider than a footpath: cover over a corridor is usually a shell with legs at the edges and a span in the middle, and one ray down the middle either sees the span and calls a bare gantry a tunnel, or sits in the gap between two panels and calls a tunnel bare. Six over three half-widths — the shipped default — puts rays at the corridor edges, where the legs are, without doubling up on the middle, where a single spanning panel already answers for everything. Cost is linear in this: each ray is one slab test per candidate box, minus the ones already hit. |
| `spread` | f32 | `1.5` | >= 0 |  | yes | HALF the lateral span of the fan, in world units: rays are placed from -spread to +spread across the path, so the full corridor tested is 2*spread wide. 'Across' is perpendicular to both the path's own direction of travel and to `direction` (see acrossAttr for where that comes from). Set it to the width you are willing to call covered — wider than the path itself if a partial overhang counts, narrower if only cover directly overhead does. 0 collapses the fan onto the centre line whatever rayCount says, which makes every ray identical and the hit count either 0 or rayCount. As a FIELD it is per path point, so a path that changes width can carry its own corridor; the ray reach, and therefore the partitioned-cook halo, is then set by the LARGEST value the field can return anywhere in the world, which is a bound to derive rather than measure. |
| `minHits` | i32 | `3` | >= 1 |  |  | How many of the fan's rays must hit before the point counts as covered, AT LEAST this many (the test is >=, so 3 of 6 is covered). This is the knob that decides what 'under cover' means, and it is a threshold rather than a fraction so that it reads the same when rayCount changes: half the rays is the shipped default and says 'art spans the corridor', 1 says 'anything at all overhead', rayCount says 'cover edge to edge'. Refused when it exceeds rayCount, because that test can never pass and a run of all-false is not a useful way to learn so. hitsAttr writes the raw count, so a graph that wants a different threshold later can write the count once and compare it downstream instead of re-casting. |
| `acrossAttr` | string | `""` |  |  |  | Name of a numeric point attribute (tuple 3) on the path giving the across direction directly, for paths that already carry their own frame. Empty (the default) derives it from the path's POLYLINE TOPOLOGY instead: the central-difference tangent at each point (the same one writeTangents and writeCurveFrame produce) crossed with `direction`. That derivation is why an empty acrossAttr requires real polyline primitives and refuses a bare point cloud. Prefer this param when the boxes were placed through a frame the path already stores: a second way of computing 'across' is a second chance to disagree with the geometry being measured, and the disagreement looks like a plausible number rather than like a bug. Whatever the source, the vector is made perpendicular to `direction` and normalized before use, so the fan stays a flat fan and the ray-reach bound stays exact. A point with no usable across direction — one no polyline visits, or one whose path neighbours all coincide, or a tangent parallel to `direction` — falls back to a deterministic axis perpendicular to `direction` (the same fallback orientAlongVector uses), so it is still measured and still reproducible, but its fan is not oriented by the path. |
| `boxSize` | vec3 | `[1,1,1]` |  |  | yes | Extent of one box along its own local X, Y and Z axes BEFORE the per-point `scale` is applied — the size of the asset the cloud stands for. The world half-extent is 0.5 * boxSize * scale componentwise, so the default [1, 1, 1] means 'the points carry unit cubes and `scale` IS the size', which is the common case. As a FIELD it is resolved ON THE BOXES CLOUD, not on the path, so attribute("...") inside it reads the boxes' own columns: a cloud carrying its extents in the standard bounds attributes is box("size") (boundsMax - boundsMin, an extent in the point's own frame, which `scale` then multiplies as here). GETTING THIS WRONG IS SILENT IN BOTH DIRECTIONS: scaling twice inflates every box and reports a tunnel over the whole path, forgetting `scale` shrinks them and reports no cover anywhere, and each produces a run that finishes cleanly with a wrong number in it. Boxes are CENTRED ON THEIR POINTS, so box("size") is the right extent only for a box centred on P: a point's bounds are an extent about P that need not be centred (setBounds "baseCenter" stands the box on P, and a grammar's pieces keep their root's P), and such a box is tested displaced by its centre offset. Run pivotBox (default pivot, the box's centre) first, which moves P to the box's centre and keeps the box where it is. A negative size is read as its magnitude, since a box of size -2 is the same set of points as one of size 2. |
| `coveredAttr` | string | `"covered"` |  |  |  | Name of the bool point attribute receiving the covered/not decision (hits >= minHits). Empty writes no flag (then hitsAttr must be set). The shape is this node's to pick (bool, tuple 1), so a name the path already holds under a DIFFERENT shape is REFUSED, not overwritten: writing it would delete that column outright and the cook would still look fine (coveredAttr "P" would leave a path with no positions). An existing bool tuple-1 column of the same name IS reused and reset, so re-running this node over its own output is fine. To write over something of another shape, removeAttribute it first, or pick another name. |
| `hitsAttr` | string | `""` |  |  |  | Name of the u32 point attribute receiving how many of the fan's rays hit at least one box, 0..rayCount. Empty (the default) writes no count. Worth writing when the threshold is still being chosen, or when the interesting quantity is HOW enclosed a point is rather than whether it passed: the count is what distinguishes a bare gantry from a tunnel, and a graph can compare it against several thresholds downstream without casting again. Same rule as coveredAttr: the shape is this node's to pick (u32, tuple 1), so a name held under a different shape is refused, while a same-shape column is reused and reset. |

## pathPointAt

Moves every point of every polyline to the position at a given parameter ALONG ITS OWN polyline, and writes the unit `tangent` and `curveU` it finds there. Points, attributes and topology all survive — this slides points along the curve they already sit on rather than building new ones, so a path stays the same path and only its parameterization changes. This is the evaluate-at-parameter the library otherwise lacks: pathResample and splineSample can only step a whole curve at even intervals, so 'where is this curve at u = 0.37' had no answer, and anything that needed one had to approximate by stepping along the tangent and hoping the curve was straight enough. mode 'fraction' reads the parameter as 0..1 of that polyline's arc length; mode 'distance' reads it as world units from the start. Both CLAMP out of range rather than wrapping or erroring — a parameter is usually computed, and a clamp is what keeps a point on the curve. The parameter is field-capable and resolves on the INPUT points BEFORE anything moves, so a field reading `curveU` sees where each point started and can be written as an offset from it: lerp(curveU, target, amount) slides each point partway toward a target. A point in several polylines is placed by the LAST one in primitive order, matching writeTangents, and a point in none is left exactly where it is with a zero tangent and curveU 0 — as is every point of a polyline whose length is zero, since it has no parameter to speak of. Because points can slide past each other, a path whose parameters are not monotonic comes back folded; that is the caller's to avoid, and it is legal geometry either way.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [examples-rig.json](../graphs/examples-rig.json) — 1 total (`pcg graphs --node pathPointAt`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"fraction"` |  | `fraction`, `distance` |  | How the parameter is read: 'fraction' is 0..1 of the polyline's own arc length, so the same value means the same relative place on curves of different lengths; 'distance' is world units from the polyline's start. Both clamp to the ends. |
| `parameter` | f32 | `0.5` |  |  | yes | Where along the polyline to place the point, read according to `mode`. Field-capable, resolved on the INPUT points before any of them move — so it can read `curveU` and express a move relative to where the point already is (for example lerp(attribute('curveU'), target, amount)), which is the usual way to use this node. A BARE attribute('curveU') is equally sound and is the re-seek: this node writes `tangent` and `curveU` afresh, and a resolved column that turns out to be the live storage of either is snapshotted before that write, so the parameter read is always the one this cook was HANDED and never a column this node has already reset. Values outside the range clamp. |

## pathResample

Resamples every polyline primitive at even arc-length steps and emits a PATH, not a cloud: the new points carry polyline topology, and a path that was closed comes back closed. Unlike splineSample, each polyline is resampled on its own arc length rather than as one concatenated curve, so a graph with several paths keeps them separate. mode 'count' places exactly `count` samples per path (endpoints included on an open path; a closed path divides its length without duplicating the start). mode 'spacing' steps every `spacing` world units, keeping that step exact rather than stretching it to fit: an open path always ends on its true endpoint, so it never comes back shorter than it went in, and a closed path closes with a REMAINDER segment at the seam that is shorter than `spacing` (use 'count' to divide a loop evenly — see the `spacing` param). Two params change that rule and default to it: `align` 'center' keeps the step exact but splits the remainder between both ends, and `fit` 'ceil', 'round' or 'floor' divides each path into that rounding of length / spacing EQUAL steps, with a whole number of steps recognised through f32 rounding of the input. Output points are new: they carry the standard point-cloud attributes plus the unit segment `tangent` (f32 tuple 3) and `curveU` (f32, normalized position within that path), and the input's point attributes are NOT carried across. Its PRIMITIVE attributes ARE, in both directions: every attribute of the polyline a sample came from lands on that sample, and each output polyline keeps the attributes of the input polyline it replaces (output primitive i resamples input polyline i and nothing else), so a road resampled here comes back still a road rather than a nameless polyline. `primtype` is the one exception, being a type tag rather than a value, and there is no opt-out: a carried name that collides with one this node writes (P, tangent, curveU, seed, ...) is refused with an error naming the attribute and the fix. FOUR OPT-IN REPORTS publish what the resampling already computed, so anything sized in units of the sampling can be stated as a multiple of it instead of retyped as a literal that the count knob then invalidates. Three are facts about a PATH and land on the PRIMITIVE domain: `lengthAttr` writes each path's TRUE ARC LENGTH — the INPUT curve's — `stepAttr` the distance between its samples, and `resampledLengthAttr` the length of the polyline this node actually EMITS. THE TWO LENGTHS ARE DIFFERENT NUMBERS and the difference is why the second exists: a resample CUTS CORNERS, so the polyline through the samples is always shorter than the curve it approximates, and it is the shorter one that anything stepping, tiling or scattering over THIS output is walking. The fourth, `sampleArcAttr`, is a fact about a SAMPLE and lands on the POINT domain: each sample's own arc position along its path, in world units on that emitted polyline, so it composes directly with pathPointAt's 'distance' mode, transferAlongPath and arcTile. All four are empty by default and the output is byte-identical to a cook without them. Downstream, any node that can REMOVE points drops topology — filterByDensity, filterByBounds, filterByAttribute, filterByExpression, selfPrune, partitionByAttribute — and so do mergePoints and repeatPoints, so a resampled path that passes through one stops being a path. Category is not the rule: projectToPlane is categorised `filter` but preserves topology, and filterByAttribute drops it even when its predicate keeps every point.

**Category:** sampler

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-path-resample.json](../graphs/basics-path-resample.json), [basics-clip-a-path.json](../graphs/basics-clip-a-path.json), [basics-scatter-along-a-path.json](../graphs/basics-scatter-along-a-path.json) — 12 total (`pcg graphs --node pathResample`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"count"` |  | `count`, `spacing` |  | How samples are placed: 'count' puts exactly `count` samples on each path; 'spacing' steps every `spacing` units along each path — exactly, from the start, by default, or as a centred row (`align`) or a whole number of equal steps sized from `spacing` (`fit`). |
| `count` | i32 | `10` | >= 2 |  |  | Samples per path when mode is 'count'. Minimum 2 for an open path and 3 for a closed one — below that the result would not be a path. Ignored in 'spacing' mode. |
| `spacing` | f32 | `1` | >= 0 |  | yes | Distance between samples in world units when mode is 'spacing'. The step is EXACT and is never stretched to make the samples come out even, so a CLOSED path ends on a REMAINDER: the last sample sits at floor(length / spacing) * spacing and the segment from it back to the start is SHORTER than `spacing` — a 43-unit loop at spacing 5 gets 9 samples and closes with a 3-unit segment at the seam. That remainder is whatever the loop's length leaves over, anywhere from a hair above 0 to just under `spacing`. To divide a loop EVENLY, switch mode to 'count': it splits the length into `count` equal steps and has no seam segment — or keep this mode and set `fit` to 'ceil', 'round' or 'floor', which picks the number of equal steps FROM this spacing. (All of this paragraph is fit 'exact' with align 'start', the defaults; `align` 'center' moves the remainder.) An open path is the same story at its far end — it always lands on its true endpoint, so its last segment is short in the same way. Must be > 0, small enough to leave at least 2 samples on each open path (3 on a closed one), and large enough that the whole input stays under 1048576 samples. Ignored in 'count' mode. AS A FIELD IT IS ONE SPACING PER PATH, resolved on the INPUT's PRIMITIVE domain: a wide road and a footpath in one geometry take different steps in ONE COOK, each path's count following its own value against its own arc length. That is why this param can be a field where splineSample's spacing cannot — this node resamples every polyline ON ITS OWN ARC LENGTH, so there is a primitive element to read one value per, while splineSample concatenates every polyline into ONE curve and reads its spacing exactly once, against no element at all. The field sees the PRIMITIVE domain, so what it can read is what a path carries: a primitive attribute (written with setAttribute domain 'primitive', or carried up from the points with promoteAttribute point → primitive), index() and fraction() over the paths, randomField(), and nodeSeed(). A POINT attribute is not in scope there, and position() is not either — a path has no one position. Both limits stay, and they are enforced differently on purpose. The MINIMUM is PER PATH: a path whose own resolved spacing is too coarse to leave 2 samples (3 when closed) is REFUSED, naming that primitive and the spacing it resolved to — never quietly dropped from the output, since a path missing from an otherwise fine-looking cook is the plausible failure this library exists to refuse. The BUDGET is on the TOTAL: samples are counted as they are placed, across every path in primitive order, and the cook is refused as soon as they add up past 1048576 — a per-path cap would pass ten paths of 200 000 samples each. A field is not range-checked the way a plain value is (a schema's min binds a number, not a recipe), so bound the expression itself — max(<expr>, <the smallest step you meant>) — and note that a NaN or infinite spacing is refused rather than read as a meaning. |
| `fit` | enum | `"exact"` |  | `exact`, `ceil`, `round`, `floor` |  | How 'spacing' mode turns a path's length L into samples. 'exact' (the default) is the rule described under `spacing`: every step is exactly `spacing`, and what is left over is a short last segment (or, with `align` 'center', split between both ends). 'ceil', 'round' and 'floor' instead divide each path into k EQUAL steps, k = ceil, round or floor(L / spacing), so the step becomes L / k — never more than `spacing` under 'ceil' (pieces meant to abut still do, as in arcTile's rule), never less under 'floor' (nothing closer than asked) — both up to the whole-step tolerance below, which may stretch or shrink a step by that tolerance over k, nearest under 'round' (the count a truss panel or a rivet row is drawn with) — and the samples land on both ends of an open path with no remainder anywhere; a closed path gets k samples and no seam segment, exactly as 'count' mode divides a loop. An open path gets k + 1 samples; k must leave at least 2 samples (3 on a closed path) or the cook is refused naming the path, the fit and a spacing that would do. WHOLE NUMBERS ARE ROBUST TO f32: a length within a tolerance of a whole number of steps counts as exactly that many, so a line authored (n - 1) pitches long in f64 — whose f32-stored endpoints measure a hair short or over — divides into n - 1 steps under every fit, not n - 2 under 'floor' or n under 'ceil'. The tolerance is 2^-20 × (S × M + L), S the path's segment count and M its largest absolute vertex coordinate — over four times what storing the vertices in f32 can move a measured length — capped at 1/256 of a step; under 'round' a length within it of a half step is the tie, which rounds up. Read only in mode 'spacing'; 'count' ignores it. `stepAttr` reports L / k under the three dividing fits. With a field `spacing`, k follows each path's own value. |
| `align` | enum | `"start"` |  | `start`, `center` |  | Where the remainder of an 'exact' fit goes. 'start' (the default) steps from the path's start, as `spacing` describes, so the remainder is at the end. 'center' places floor(L / spacing) + 1 samples exactly `spacing` apart on an open path and splits the remainder EQUALLY between both ends, so the row is centred on the path: a 10-unit line at spacing 3 gets samples at 0.5, 3.5, 6.5 and 9.5, and its ENDPOINTS ARE NOT SAMPLED unless the length is a whole number of steps (within the same f32 tolerance `fit` describes, which makes floor(L / spacing) robust here too). On a closed path it places the same samples 'start' does — floor(L / spacing) + 1, or exactly L / spacing when that is whole — shifted forward by half the remainder, so the short seam segment is CENTRED on the path's start point instead of ending at it: a 43-unit loop at spacing 5 gets 9 samples from 1.5 to 41.5 and a 3-unit segment across the start. An open path shorter than `spacing` would get ONE sample and is refused; a closed one needs 3. Read only in mode 'spacing' with fit 'exact' — the dividing fits leave no remainder, so under them both values place the same samples. |
| `lengthAttr` | string | `""` |  |  |  | Name of an f32 PRIMITIVE attribute receiving each path's TRUE ARC LENGTH in world units — the sum of its input polyline's segment lengths. Empty (the default) writes none. This is the number the graph cannot otherwise know: the straight-line span between a curve's endpoints is SHORTER than the curve, and no field can walk a polyline's vertices to find the difference, so a size derived from the length is authored today as a literal measured by hand elsewhere. It lands on the PRIMITIVE domain because a length is a fact about a PATH, one per path, exactly like `connectPoints.lengthAttr`; promote it (promoteAttribute, primitive to point) for a field to read per sample, or filter on it with filterPrimitivesByAttribute. The length reported is the INPUT polyline's, not the polyline through the new samples: a coarse resample of a curve cuts corners and comes back shorter, and reporting that would report the approximation rather than the curve — it is also what makes `stepAttr` times the divisions equal it exactly. The shape is this node's to pick (f32, tuple 1), so a name arriving on the output's primitive domain under a DIFFERENT shape is REFUSED rather than deleted and re-added; a same-shape column is RESET, which is what keeps resampling a resampled path under the same name ordinary. |
| `stepAttr` | string | `""` |  |  |  | Name of an f32 PRIMITIVE attribute receiving the ARC-LENGTH STEP between consecutive samples on that path. Empty (the default) writes none. Per path and so on the PRIMITIVE domain for the same reason as `lengthAttr`: in 'count' mode the step is that path's OWN length divided by its divisions (length / (count - 1) on an open path, length / count on a closed one, the divisor that leaves no duplicate at the seam), so two paths of different lengths get different steps and neither varies from sample to sample. In 'spacing' mode with fit 'exact' it reports `spacing` itself, unchanged — or, when `spacing` is a field, that path's OWN resolved value, which is the same statement once the param is read per path — not a tautology but the point of reporting it at all: a downstream size written as a multiple of this attribute follows the sampling when the mode or the knob changes under it, instead of silently meaning something else. Note that with fit 'exact' the LAST step (or, with align 'center', the two end pieces) is the remainder described under `spacing` and is SHORTER than the value reported here; this is the step the node takes, not what the path had left over. Under fit 'ceil', 'round' or 'floor' it reports that path's own equal step, length / k, computed by the same division that placed the samples. Same reporting-slot rule as `lengthAttr`, and no two of the per-path reports may name the same attribute — the second write would overwrite the first with no complaint, since the shapes agree. |
| `resampledLengthAttr` | string | `""` |  |  |  | Name of an f32 PRIMITIVE attribute receiving the length of the polyline this node EMITS for that path: the sum of the straight-line chords between consecutive samples, plus the closing chord from the last sample back to the first when the path is closed. Empty (the default) writes none. IT IS NOT `lengthAttr` AND THAT IS THE POINT. `lengthAttr` reports the INPUT curve, which is the right number to ask about the road and the wrong one to ask about this output: a resample CUTS CORNERS, so the polyline through the samples is always SHORTER than the curve it was cut from. On a closed lap of this scale the two read 3121.533 and 3121.366 — 0.0054% — which sounds ignorable until you notice it is NOT UNIFORM: every unit of it accrues over the bends and none of it over the straights, so no scale factor turns one into the other and a consumer that steps `lengthAttr` over these samples drifts, running off the end of the path or wrapping short of its own seam. Use `lengthAttr` when the question is about the CURVE (how long is this road, how many props does it deserve) and this one when the question is about THIS OUTPUT (how far can I walk on the polyline I am about to hand downstream). Measured from the f32 positions actually written, in the same order and with the same arithmetic `polylineArcTables` uses to re-measure them downstream, so the number a later pathResample, pathPointAt, arcTile or transferAlongPath computes for this path IS this number rather than a near miss — the column itself is f32 like every report here, so what a graph reads is that sum rounded to f32. Same reporting-slot rule as `lengthAttr` — a name on the output's primitive domain under a different shape is REFUSED rather than deleted and re-added, a same-shape one is RESET — and no two of the per-path reports may name the same attribute. |
| `sampleArcAttr` | string | `""` |  |  |  | Name of an f32 POINT attribute (tuple 1) receiving each sample's ARC POSITION from the start of ITS OWN path, measured along the EMITTED polyline: sample 0 of every path is 0, and each later sample adds the straight-line chord from the sample before it. Empty (the default) writes none. THE UNITS ARE WORLD UNITS, NOT A 0..1 FRACTION, and that is what makes it more than `curveU` under another name: `pathPointAt`'s 'distance' mode, `pointScatterOnPath.arcAttr`, `transferAlongPath.arcAttr` and `arcTile.startAttr` are all world-unit chord coordinates, so this column plugs into any of them with no multiply and nothing for the graph to get wrong. The fraction is one divide away (by `resampledLengthAttr`) while going back the other way needs the length anyway, so the coordinate that composes is the one written. `curveU` is still written beside it and still measures the INPUT curve's fraction; the two disagree by exactly the corner-cutting `resampledLengthAttr` reports. It lands on the POINT domain because it is a fact about a SAMPLE — a different number for every point — which is what makes it unlike the three per-path reports and why it is checked against the output's point domain rather than its primitive one. THE CLOSING CHORD OF A CLOSED PATH IS NOT IN THIS COLUMN: it runs from the last sample back to the first, so no sample holds it — it is in `resampledLengthAttr`, and the last sample's value plus that chord is the emitted length. On an open path the last sample's value IS the emitted length. The shape is this node's to pick (f32, tuple 1), so a name already on the OUTPUT's point domain under a different shape is REFUSED rather than deleted and re-added — P, scale, boundsMin, boundsMax and `tangent` (f32x3), rot and color (f32x4) and seed (u32) all reach that refusal — while `density` and `curveU` ARE f32 tuple 1, so naming either passes the shape check and RESETS it, silently overwriting a standard column with an arc length — and `curveU` is then gone rather than merely shadowed, since the two columns become one buffer and the arc is what stays in it. Give it a name of its own. TWO MORE NAMES ARE REFUSED OUTRIGHT. A name that is also a PRIMITIVE attribute of the INPUT is refused before the cook starts, whatever its shape: every primitive attribute is carried onto these samples, so it would land on this very column, and the refusal names this param rather than the carried attribute because renaming the report is the fix and moving the author's own value is not. And "primtype" is refused because it is a type tag rather than a value — this node stamps it on every path it emits, and an f32 point column under that name is a second meaning for a name the library resolves as a type, one promoteAttribute away from replacing the tag and hiding every path from the nodes that read it. |

## pathRuns

Writes a SEGMENTED running total of a numeric point attribute along every polyline: like pathScan, except the accumulator RESETS at points a boolean attribute flags, and on a closed path a run may cross the seam. `reduce` picks WHAT the accumulator is — a sum (the default), a running minimum or a running maximum over the same runs — because a segmented minimum is this same walk with a different fold, and the walk is the part that was hard. This is what answers 'how far since the last marker' and 'how far to the next one' — the two queries a prefix sum cannot express. pathScan accumulates monotonically from the seam and never resets, so emulating a segmented scan from it means subtracting the scan value at the most recent flagged point BEHIND you, and obtaining that value is itself a backward look-up along the path, which no field can perform: a field resolves each element from that element alone. This is the missing primitive, and wrapping is a property it needs rather than the whole of what was missing. IT ACCUMULATES A VALUE, NOT A COUNT, which is the whole ergonomic difference: scan a per-segment length for distance, a per-sample cost for cost, or a constant 1 for the vertex count, and one node covers all three. RUNS ARE HALF-OPEN AND ORIENTED. Forward, a run begins at a flagged point (inclusive) and continues until the next flagged point (exclusive), accumulating in the path's walk order; backward, a run ENDS at a flagged point (inclusive) and extends back to just after the previous one, accumulating against the walk order. Both exist because they answer different questions — 'distance since the corner behind me' is the forward run and 'distance to the corner ahead' is the backward one — and neither is recoverable from the other without knowing each run's total. THE SEAM IS NOT A BOUNDARY unless something flags it. On a CLOSED path with `wrap` on, the walk starts at the first flagged point rather than at vertex zero, so the run that straddles the start/finish line is one run and not two; that is the case a lap actually has, and a backward segmented scan built on an unwrapped prefix sum gets it wrong every time. A closed path with wrap on and NO flagged point anywhere has no place for a cyclic run to begin, so the seam stands in and the result is what `wrap` off would give. On an OPEN path `wrap` does nothing. Points in no polyline are left at the fold's IDENTITY — zero for a sum, which is what they have always read, and ±Infinity for a min or a max — and a point visited by several polylines takes the last one in primitive order, both matching pathScan and writeTangents. NaN CONTRIBUTES NOTHING rather than poisoning the rest of its run: zero to a sum, and no candidate to a min or a max. A NaN in the BOUNDARY column is not a boundary either — a column that could not be measured must not silently cut every run in the path.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-runs-along-a-path.json](../graphs/basics-runs-along-a-path.json) — 1 total (`pcg graphs --node pathRuns`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"density"` |  |  |  | Numeric POINT attribute to accumulate (f32/i32/u32/bool, tuple 1..4). Must exist. Tuples accumulate componentwise, each component its own independent running total, and all of them reset together at a boundary. Scan a per-segment length here for distance, or an attribute set to a constant 1 for the count of points since the boundary. |
| `boundary` | string | `"boundary"` |  |  |  | POINT attribute (tuple 1) whose NON-ZERO values mark where a run begins, forward, or ends, backward. Must exist. Any numeric type: a bool column is the obvious one, and an i32 marker column or an f32 written by a field works the same way, because the test is only 'is this nonzero'. NaN is NOT a boundary, deliberately: a boundary column carrying an unmeasurable value would otherwise cut every run in the path, and silently. A tuple wider than 1 is refused rather than reduced — a flag is one column, and which component would have decided is not a question this node should answer for you. |
| `outName` | string | `"run"` |  |  |  | POINT attribute receiving the running total (f32, at the source's tuple size). Must differ from `name`: scanning in place would read back values this node had already overwritten. 'P' is refused outright. Same reporting-slot rule as the rest of the library — a column of a different shape under this name is refused rather than deleted and re-added, and a same-shape one is reset. f32 whatever `reduce` is, and that is not a limitation for a min or a max: an extreme is one of the values that were handed in, never a combination of two, so it survives the trip at the same precision a sum's inputs did — and f32 carries the ±Infinity a run that has folded in nothing yet reads. |
| `reduce` | enum | `"sum"` |  | `sum`, `min`, `max` |  | WHAT THE ACCUMULATOR IS. 'sum' (the default, and everything this node did before this param existed) adds the values of a run; 'min' and 'max' keep the run's smallest or largest instead. Nothing else moves — `boundary`, `mode`, `direction`, `wrap` and componentwise tuple handling are the same walk, because a segmented minimum differs from a segmented sum only in the fold, and the fold was never the hard part: the rotation onto the first flagged point, the seam, and the reset are. IT IS A PARAM AND NOT A SECOND NODE because 'the tightest radius since this corner began' and 'the distance since this corner began' are ONE query asked twice, and the library could previously spell only the second — attributeReduce has min and max but collapses a WHOLE domain onto the detail domain and cannot group, so a grouped extreme had no expression at all and came out as a hand-written loop in whatever host needed it. EACH RUN OPENS ON ITS FOLD'S IDENTITY: 0 for a sum, +Infinity for a min, -Infinity for a max — attributeReduce's answer over an empty domain, and the same answer for the same reason. In 'exclusive' mode a run's FIRST point reads exactly that, since by definition its own value is not in its own total, so a min there reads +Infinity and a max -Infinity. That is the honest answer rather than a sentinel to remember: the minimum of no values IS +Infinity — it is the only x for which min(x, v) = v — the output column is f32 and represents both infinities exactly, and unlike a sum's 0 it can never be mistaken for a measurement, so `isFinite` on the column is a usable test for 'this run has folded in nothing yet' that a sum can never offer. Answering 0 instead would make an empty min compare TIGHTER than every real radius, which is precisely the false positive a threshold rule cannot survive. NaN IS SKIPPED, not propagated — the rule the sum already had, kept: both `<` and `>` are false against a NaN, so an unmeasurable value simply never becomes the record, and one bad sample costs its own point instead of the rest of its run. A RUN OF ONE POINT reads the identity in 'exclusive' and its own value in 'inclusive', which is the sum's 0-and-v said in the other monoid, since min(+Infinity, v) is v; a run of NO points is not observable, because a run is opened by a point. THE COMPARISON IS SIGNED, never a magnitude: a max over -5 and -1 is -1. WHAT `mode` COSTS DIFFERS BY FOLD: for a sum, 'inclusive' differs from 'exclusive' at EVERY point, by that point's own value; for a min or a max they differ only at the points that set a new record, because an extreme is idempotent and the running value therefore moves one way and then stays. `direction` IS UNAFFECTED — all three folds are commutative and associative, so over a FIXED set of points the order of traversal cannot change the answer, and what direction changes is which points form a run (half-open the other way) and where the run's answer lands, exactly as it always did. |
| `mode` | enum | `"exclusive"` |  | `inclusive`, `exclusive` |  | Whether a point's own value is part of its own running total. 'exclusive' (the default here, where pathScan defaults to 'inclusive') starts every run on its boundary point at the `reduce` fold's identity — zero for a sum, which is what 'distance since the marker' means, the marker itself being at distance zero, and ±Infinity for a min or a max, which is what 'the tightest thing strictly behind me' means when there is nothing behind me yet. 'inclusive' ends each run's last point on the run's whole total instead. Neither is more correct; pick by which end of the run you need exact. |
| `direction` | enum | `"forward"` |  | `forward`, `backward` |  | Which way the runs are oriented. 'forward' accumulates in the path's walk order, so a point reads what lies BEHIND it since the last boundary — the query a 'distance since the last corner' rule wants. 'backward' accumulates against the walk order, so a point reads what lies AHEAD of it up to the next boundary — the query a marker rule wants ('place an entry marker 3 to 6W before the corner'). The two are not each other's complement without the run's total, which is why both are built rather than one plus an instruction to reverse the path — and under `reduce` 'min' or 'max' not even WITH it, because an extreme discards everything that was not the record and no arithmetic recovers it. On a CLOSED path reversing also moves which side of the seam a run starts on, so 'reverse it yourself' is a trap exactly where wrapping matters. Note also that the two directions do not cut the path into the SAME runs: forward a flagged point opens its run and backward it closes one, so the partitions sit one point apart. That is true of every fold and is not something `reduce` changes. |
| `wrap` | bool | `true` |  |  |  | Whether a run may cross a CLOSED path's seam. True (the default) starts the walk at the first flagged point instead of at vertex zero, so a run straddling the start/finish line stays one run — the case a closed lap always has and the one a prefix sum cannot answer. False treats the seam as a run boundary, which is what you want when the vertex order carries meaning of its own, such as a lap whose start line IS a marker. No effect on an open path, and no effect on a closed path with nothing flagged, where there is no cyclic starting point to rotate to. |

## pathScan

Writes a RUNNING FOLD of a numeric point attribute along every polyline, in the path's own walk order — by default a prefix SUM, the accumulating counterpart to attributeReduce's collapse, and under `reduce` a running minimum or maximum over that same walk instead. This is the operation a field cannot express at any length: a field resolves each element from that element alone, so 'how much of this attribute lies BEHIND me along the curve' has no formulation in the grammar, and the quantities that need it are ordinary — distance travelled, accumulated cost, an inventory that fills as the path runs, and above all a CUMULATIVE DISTRIBUTION, which is what turns a per-sample density into placements. Order is the path's, which is why this is a path node rather than a domain-wide one: a scan without an order is not defined, and a polyline is where this library keeps one. A CLOSED path scans from its seam and does not count the repeated last vertex twice, under every fold — and the skip is not merely tidiness for the folds that could absorb it. A min or a max is idempotent, so folding the seam vertex's value in a second time could not move the path's answer; but the second VISIT would also re-WRITE the seam point's own column entry, with the fold over nearly the whole path rather than with what stands behind that point, and that is wrong under all three. One rule, one set of visited points, three folds. Points in no polyline are left at the fold's IDENTITY — zero for a sum, which is what they have always read, and ±Infinity for a min or a max — and a point visited by several polylines takes the last one in primitive order, both matching writeTangents and pathRuns. NaN CONTRIBUTES NOTHING rather than poisoning everything downstream of it — zero to a sum, and no candidate to a min or a max — which matters more here than in attributeReduce: there one bad element spoils one statistic, here it would spoil the whole tail of a column. INVERSE-TRANSFORM SAMPLING, the reason the SUM exists, is then TWO nodes — scan a per-sample density with `normalize` set, which writes the CDF in 0..1 directly, and transferAttribute 'nearest' from a cloud of N evenly spaced targets in CDF space back onto the frames. It was four before `normalize` existed, because the total landed on the primitive domain and had to be promoted back onto the points and divided by hand — with 'first' rather than the obvious 'average', which was correct only by the accident that a point usually belongs to one polyline. Each target lands on the sample whose CDF is nearest its own, which places exactly N points in proportion to the density, with no rejection and no approximate count. THAT IDIOM IS `reduce` 'sum' AND NOTHING ELSE, and the nearest-in-CDF lookup is the part that gives it away: a distribution is accumulated MASS, and a running extreme accumulates none — it opens at the first value rather than at zero and moves only where a record is set, so the buckets it lays out have width only at the samples that beat the record and ZERO width everywhere else. Evenly spaced targets in that space land on the records and nowhere else, which is not sampling in proportion to anything. WHAT THE OTHER FOLDS ARE FOR is the GROUPED REDUCTION the library otherwise cannot spell: pointsToPath with a `groupAttr` cuts a cloud into one path per group, `reduce` 'max' with `totalAttr` set writes each group's maximum onto the primitive domain, and promoteAttribute (primitive to point) hands it back to every point of its own group. attributeReduce has min and max but collapses a WHOLE domain onto the detail domain and cannot group, so 'the largest value in each group, on every member of that group' had no expression at all before this param and came out as a hand-written loop in whatever host needed it.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-density-along-a-path.json](../graphs/basics-density-along-a-path.json) — 1 total (`pcg graphs --node pathScan`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"density"` |  |  |  | Numeric POINT attribute to fold (f32/i32/u32/bool, tuple 1..4). Must exist. Tuples fold COMPONENTWISE, each component its own independent running value — which under `reduce` 'min' or 'max' means a per-component extreme and not the tuple that happened to hold the smallest component: comparing tuples would need an order on tuples, and there is none that is not an arbitrary choice made on the caller's behalf. |
| `outName` | string | `"scan"` |  |  |  | POINT attribute receiving the running value (f32, at the source's tuple size). Must differ from `name`: scanning in place would read back values this node had already overwritten, so every element after the first would fold in this node's own output instead of its input. 'P' is refused outright. Same reporting-slot rule as the rest of the library — a column of a different shape under this name is refused rather than deleted and re-added, and a same-shape one is reset. f32 whatever `reduce` is, and that is not a limitation for a min or a max: an extreme is one of the values that were handed in, never a combination of two, so it survives the trip at the same precision a sum's inputs did — and f32 carries the ±Infinity a path that has folded in nothing yet reads. |
| `reduce` | enum | `"sum"` |  | `sum`, `min`, `max` |  | WHAT THE ACCUMULATOR IS. 'sum' (the default, and everything this node did before this param existed) adds the values along a path; 'min' and 'max' keep the smallest or largest seen so far instead. Nothing else moves — `mode`, `totalAttr`, the walk order, the seam rule and componentwise tuple handling are the same scan, because a running minimum differs from a prefix sum only in the fold, and the fold was never the hard part: the ORDER is, and a polyline is where this library keeps one. EACH PATH OPENS ON ITS FOLD'S IDENTITY: 0 for a sum, +Infinity for a min, -Infinity for a max — attributeReduce's answer over an empty domain, and the same answer for the same reason. In 'exclusive' mode a path's FIRST point reads exactly that, since by definition its own value is not in its own total, so a min there reads +Infinity and a max -Infinity. That is the honest answer rather than a sentinel to remember: the minimum of no values IS +Infinity — it is the only x for which min(x, v) = v — the output column is f32 and represents both infinities exactly, and unlike a sum's 0 it can never be mistaken for a measurement, so `isFinite` on the column is a usable test for 'nothing has been folded in here' — which covers a path's first point in 'exclusive' AND a point on no polyline at all, the two elements that have nothing behind them — that a sum can never offer. Answering 0 instead would make an empty min compare TIGHTER than every real value, which is precisely the false positive a threshold rule cannot survive. NaN IS SKIPPED, not propagated — the rule the sum already had, kept: both `<` and `>` are false against a NaN, so an unmeasurable value simply never becomes the record, and one bad sample costs its own point instead of the whole tail of the column. A PATH OF ONE POINT is degenerate rather than unreachable — a polyline needs two vertices, but a CLOSED one whose two vertices are the same point walks exactly one — and it reads the identity in 'exclusive' and its own value in 'inclusive', which is the sum's 0-and-v said in the other monoid, since min(+Infinity, v) is v. THE COMPARISON IS SIGNED, never a magnitude: a max over -5 and -1 is -1. WHAT `mode` COSTS DIFFERS BY FOLD: for a sum the two modes differ at a point BY THAT POINT'S OWN VALUE, so they part company almost everywhere and agree only where the value is zero (or a NaN, which contributes zero); for a min or a max they differ only at the points that SET A NEW RECORD, because an extreme is idempotent and the running value therefore moves one way and then stays. IT IS A PARAM AND NOT A SECOND NODE for the reason pathRuns' `reduce` is one: 'the largest width so far along this lap' and 'the width so far along this lap' are one query asked twice, and this is that same param over a whole path where pathRuns spells it over segmented runs — one vocabulary, one identity, one NaN rule, so a graph that folds a minimum between markers and one that folds it along the whole path do not have to be read two different ways. |
| `mode` | enum | `"inclusive"` |  | `inclusive`, `exclusive` |  | Whether a point's own value is part of its own running value. 'inclusive' ends the last point of a path on the path's whole fold; 'exclusive' starts the first point at the `reduce` fold's identity — zero for a sum, which is the one that makes a CDF whose first bucket is reachable, and ±Infinity for a min or a max, which is what 'the smallest thing strictly behind me' means when there is nothing behind me yet. Neither is more correct — pick by which end you need exact. |
| `normalize` | bool | `false` |  |  |  | Divide every point's running value by its own path's TOTAL, so the column comes out as a 0..1 CUMULATIVE DISTRIBUTION rather than an accumulating quantity. That is what the sum exists for, and until this param it cost two more nodes and a hazard: `totalAttr` lands on the PRIMITIVE domain, so a graph had to promoteAttribute it back onto the points and then divide — and the promote had to be 'first' rather than the obvious 'average', which is correct only by the accident that a point usually belongs to one polyline. Both nodes and the accident go away here, because the total is already in hand at the moment the column is written. `reduce` MUST BE 'sum' when this is set, and the refusal is by name: a distribution is accumulated MASS, and a running extreme accumulates none — it opens at the first value rather than at zero and moves only where a record is set, so dividing by it produces a number with no meaning rather than a wrong CDF. A path whose total is 0, or not finite, writes 0 at every one of its points: there is no distribution to express, and 0 is the answer that stays inside the range this param promises rather than an infinity or a NaN travelling downstream. A total that is NEGATIVE is divided by as it stands, so a density that goes below zero does not give a CDF in 0..1 — that is a fact about the input rather than something to clamp away. `totalAttr` still reports the RAW total, never 1: the total is a fact about the path, and it would otherwise be the one thing normalizing destroys. With `mode` 'inclusive' the last point of each path reads exactly 1; with 'exclusive' the first reads exactly 0 and the last falls short of 1 by its own share, which is the end you want when the buckets have to be reachable. |
| `totalAttr` | string | `""` |  |  |  | OPT-IN REPORT: name of an f32 PRIMITIVE attribute receiving each path's WHOLE FOLD — its total under `reduce` 'sum', its minimum under 'min', its maximum under 'max' — the number both modes are heading for. Empty (the default) writes none and the output is byte-identical to a cook without it. On the PRIMITIVE domain because a fold is a fact about a PATH, exactly as pathResample's `lengthAttr` is; promote it (promoteAttribute, primitive to point) for a field to read it per sample, which is what normalizing a scan into a 0..1 CDF needs — and, with a `groupAttr` on the pointsToPath upstream, what makes this node the library's GROUPED REDUCTION: one path per group, that group's fold on its primitive, promoted back onto every point of it. Promote with 'first' rather than 'average' when the fold can be an infinity: with one path per point the two agree on the value, and where a point really does sit on two paths, averaging a +Infinity against a -Infinity gives NaN where 'first' still gives a number. REPORTED IN 'exclusive' MODE TOO, where a sum's total is otherwise unrecoverable from the column because no point holds it. Under a min or a max that sentence is nearly true, and the exception is the dangerous half: the last point's exclusive value IS the whole fold unless the last point is the one that set the record, and nothing in the column says which case you are in — so the report is the answer that is right every time rather than usually, which is a stronger reason to ask for it than the sum ever had. Primitives that are not polylines are left at the identity like any unwritten element, so a mesh in the same geometry reads the fold over no points rather than a zero that would beat every real minimum. May not name the same attribute as `outName` — a different domain, but one name, which is a coincidence worth refusing rather than explaining downstream. |

## pathSegments

Emits ONE POINT PER SEGMENT of every polyline primitive, placed and oriented so that spawning a unit-sized asset on it draws the path as solid geometry. This is the DISCRETE way to draw a curve: one asset per segment, which is what a chain of separate links, a row of sleepers or a string of beads is. For a continuous skin use sweepProfile instead — it emits a real triangle mesh, shares rings between segments, and needs no `extend` because it leaves no gap to fill. Each output point sits at its segment's MIDPOINT, with `rot` turning the chosen local `axis` onto the segment direction and `scale` holding the segment's length on that axis and `radius` on the other two — so a unit cylinder (height 1, radius 1) lands exactly on the segment. Also writes the unit `tangent` (f32 tuple 3, the segment direction), `curveU` (f32, the midpoint's normalized position along that path) and `seed`; the input's POINT attributes are not carried, its PRIMITIVE attributes are. An opt-in `segmentIndexAttr` adds the segment's 0-based index WITHIN ITS OWN PATH, which is otherwise unrecoverable here — a point attribute written upstream does not survive this node, and `curveU` is a fraction that needs the count back to become an index. It is empty by default and the output is byte-identical to a cook without it. The default axis is '+y', deliberately unlike orientAlongVector's '+z': the assets this feeds are cylinders and capsules, which are built along Y in three.js, whereas orientAlongVector points props at a heading. Roll around the segment is fixed by an up hint of [0, 1, 0] with the same deterministic fallbacks orientAlongVector uses ([0, 0, 1], then [1, 0, 0]) — a tube is rotationally symmetric so the roll is arbitrary, but it is never random; when it MATTERS (alternating chain links), re-orient downstream with orientAlongVector reading the `tangent` this node wrote. Segments of zero length are SKIPPED rather than emitted as degenerate instances, so the output can hold fewer points than the input had segments. THE OUTPUT IS A PLAIN CLOUD, not a path: the points are segment midpoints, not the curve, and no polyline topology is built over them — resampling or re-pathing this output describes the midpoints, not the original curve, so branch off the path itself for that. Closed paths need nothing special: their closing segment is a segment like any other.

**Category:** sampler

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-path-segments.json](../graphs/basics-path-segments.json), [examples-archipelago.json](../graphs/examples-archipelago.json), [examples-rig.json](../graphs/examples-rig.json) — 3 total (`pcg graphs --node pathSegments`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `axis` | enum | `"+y"` |  | `+x`, `-x`, `+y`, `-y`, `+z`, `-z` |  | Which local axis of the spawned asset runs along the segment, and therefore which `scale` component carries the segment length. Default '+y' — three.js CylinderGeometry and CapsuleGeometry are built along Y, and this node exists to feed them. The other two components carry `radius`. |
| `radius` | f32 | `0.05` | >= 0 |  | yes | Scale written to the two components that are not the axis; with a unit-radius asset this is the tube's radius in world units. Field-capable, but note WHERE it resolves: on the INPUT points (the path's own points), not on the segments this node emits — the output domain does not exist yet when the field runs. Each segment takes the AVERAGE of the values at its two endpoints, so a radius that tapers along a path tapers smoothly across the segments. That also means a field can only read attributes the input POINTS carry: a per-path radius living on the PRIMITIVE domain has to be promoted onto the points first (promoteAttribute, primitive to point) before a field can see it. Values below 0 are clamped to 0. |
| `extend` | f32 | `0` | >= 0 |  | yes | World units added to BOTH ends of every segment (the length on the axis becomes segment + 2 * extend; the midpoint does not move). This is the joint filler: consecutive segments meeting at a bend leave a wedge-shaped gap on the outside of the corner, and overlapping them closes it. About one radius is enough down to right-angle bends. Costs nothing but overlap, and with a capsule asset the rounded caps hide the seam entirely. Field-capable, and it resolves EXACTLY WHERE `radius` DOES — on the INPUT points (the path's own points, since the segments this node emits have no domain yet), then AVERAGED over the two points a segment runs between — so it is one filler PER SEGMENT and the two params take the same expression: a taper that thins the tube thins its joints with it, and 'about one radius' becomes a fill that follows the radius instead of a literal that stops matching the moment the radius moves. It follows that a field here reads what the input POINTS carry; a per-path extend living on the PRIMITIVE domain has to be promoted onto the points first (promoteAttribute, primitive to point), the same route `radius` documents. A PLAIN value must be finite and >= 0 and is refused otherwise. A FIELD's negative value is clamped to 0 per segment, exactly as `radius` is — a filler is a length, and a negative one would shorten the segment away from its own endpoints — while a NaN or infinite one is refused, naming this param. |
| `segmentIndexAttr` | string | `""` |  |  |  | Name of an i32 POINT attribute receiving each segment's 0-BASED INDEX WITHIN ITS OWN PATH, restarting at 0 for every polyline. Empty (the default) writes none. It is the per-path coordinate this node otherwise has no way to state: `curveU` is a fraction, and turning one back into an index needs the segment count again, while an index written upstream with setAttribute does not survive — this node emits a NEW point per segment and carries no point attributes. Without it, 'every other link of THIS chain' has to be spelled on the GLOBAL point index, which agrees with the per-path one only while every path has the same, EVEN, number of segments, and nothing reports when that stops being true. It counts the segments this node EMITTED, so a skipped zero-length segment leaves NO GAP and an alternation over it (index - 2 * floor(index / 2)) keeps its parity through a degenerate path; an index into the input's segment list would not, and would also address elements that are not in this output. The shape is this node's to pick (i32, tuple 1), so a name already among the columns written here — P, rot, scale, density, boundsMin, boundsMax, color, seed, tangent, curveU — under a DIFFERENT shape is REFUSED rather than deleted and re-added, and a carried PRIMITIVE attribute of the same name is refused too, with the fix. |

## pathShift

Reads one or more of a path's OWN point attributes from the point `offset` positions further along the polyline's walk order, and writes each into a column of its own — LEAD AND LAG on a path. `attributes` names the columns to read and `outNames` names where each shifted value lands; the two lists are parallel, entry for entry. This is the neighbour query a sequence has and a point cloud does not: 'what does the NEXT station carry', 'what did the PREVIOUS one carry', and every difference and chain rule those make possible. THE MOTIVATING CASE IS A GAP RING: on a closed path of stations ordered by arc position, shift each station's arc coordinate by +1 and subtract, and every point holds the distance to the next station; shift that gap by -1 and every point holds the gap behind it as well. Moving windows, run lengths between adjacent markers, 'is my successor the same archetype as me' — all of them are this shape. WHY NOT ANOTHER NODE: pathScan and pathRuns ACCUMULATE, and a neighbour's value is not a function of any accumulation of the values before it, in either direction. That holds under every `reduce` they offer and not just the sum they started as: a running minimum forgets everything that was not the record, so it cannot answer 'what did the previous point carry' any more than a running total can. They also fold NUMBERS, so a string or any other discrete id cannot pass through them at all. transferByIndex gathers at an ABSOLUTE point index, a position in the source's storage array, which is NOT the walk order: pointsToPath builds topology over points where they already lie and never reorders them, so with `orderAttr` set a path visits point 7 after point 2 and 'the next point along' has no expression as 'index + 1' — the rank that would let you spell it as one is itself only obtainable by walking the polyline, which is what this node does. transferAlongPath reads at an ARC POSITION and interpolates, a different question with a different answer: stations are unevenly spaced, so 'the next one' is at no fixed distance, and an interpolated value arrives as f32, which destroys exactly the discrete ids an ordinal neighbour is usually asked for. pathSegments emits a SEPARATE one-point-per-segment cloud and deliberately carries none of the input's point attributes. THE ORDER IS THE POLYLINE'S, NEVER THE POINT ARRAY'S. The walk is the primitive's vertex sequence, so `orderAttr` on pointsToPath decides what 'next' means and the storage order decides nothing at all. Two points adjacent in the point array are neighbours here only if the path happens to visit them in that order. A CLOSED PATH IS A RING OF N POINTS, NOT N+1: pointsToPath(closed) appends a trailing VERTEX that revisits the first point, so 5 points become 5 points and 6 vertices, and that repeat is the closure rather than a place. The ring this node walks has one entry per POINT, so on a closed path with `wrap` a +1 shift takes the last point to the first, every point is read exactly once, and no phantom entry reads itself. A POSITION THAT RAN OFF THE END is read by `outOfRange`, in transferByIndex's vocabulary: 'wrap' (the default) takes a EUCLIDEAN modulo over the polyline's point count, so -1 from the first point is the LAST point and not JavaScript's -1; 'clamp' pins to the first or last point of that same polyline; 'miss' leaves the destination column at its DEFAULT and flags the point through hitAttr. CLOSURE CHANGES THE COUNT AND NEVER THE POLICY: dropping the repeated vertex is what a closed path does to the ring's SIZE, and after that only 'wrap' comes round it, so a closed path under 'clamp' or 'miss' still has a first position and a last. WRAP APPLIES TO AN OPEN PATH TOO, which is a deliberate divergence from pathRuns' `wrap` ('no effect on an open path') and is explained in that param: the two share a word and not a question. OFFSET 0 IS LEGAL AND COPIES — it is not refused, because a shift of nothing is a well-defined shift and a graph that computes its offset should not fail when the number comes out zero. A POINT ON NO POLYLINE gets no neighbour: its destination columns keep their default and hitAttr flags it 0, matching pathScan and writeTangents, which leave such points at their own output column's DEFAULT — zero for writeTangents and for a pathScan summing, and the fold's identity under pathScan's `reduce`, which is the same rule and not a second one. It is never an error — a path built over part of a cloud is ordinary. A GEOMETRY WITH NO POLYLINE AT ALL IS THAT SAME RULE AND NOT A SECOND ONE: every point is then a point on no polyline, so every point misses, every destination column holds its default, hitAttr is all 0, and nothing throws. This node therefore does NOT refuse a pathless input the way pathScan, pathResample and writeTangents do, and the difference is that they have nothing to say without a path while this one has a defined answer — the one it already gives per point. Refusing would mean answering one question two ways depending on whether the number of stranded points happened to equal the total. It matters in practice: pointsToPath with shortGroups 'skip' legitimately emits no primitive for a group too small for the path being asked for, and a graph that shifts over the result must settle to 'nobody has a neighbour' rather than crash on a lap that held two placements. Neither `outOfRange` nor `offset` can change it — there is no range to be inside or outside of, and offset 0 is a copy only for a point that HAS a walk to be at position 0 of. A geometry with NO POINTS cooks to itself with the destination columns created and empty, so the shape of the output never depends on what this cook happened to be handed. What is still refused is MALFORMED input rather than EMPTY input: a missing pin, an attribute that does not exist, a param that contradicts itself. A POINT ON SEVERAL POLYLINES is answered by the LAST one in primitive order, the convention writeTangents, pathScan, pathRuns and pathPointAt all state; a MISS from that last polyline wins too, replacing an answer an earlier one had found, so the rule is 'the last polyline decides' and not 'the last polyline that found something'. THE VALUES ARE COPIED, NEVER BLENDED: each output column takes the SOURCE column's type, tuple size and default, so an i32 lane stays an i32 lane, a string asset id transfers intact, and every component of a tuple comes from the SAME neighbour rather than from a componentwise mixture. THE OUTPUT IS THE INPUT plus the new columns: same points, same order, same identities, same topology, and P is never written (see `outNames`) — this node moves no point, adds none and removes none, so a path goes in and the same path comes out. DETERMINISM IS STRUCTURAL: there is no randomness of any kind here, and a point's answer depends only on its polyline's own walk, so it does not change with cook order, partitioning, or how many points are in hand.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-shift-along-a-path.json](../graphs/basics-shift-along-a-path.json) — 1 total (`pcg graphs --node pathShift`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `attributes` | stringList | `[]` |  |  |  | POINT attributes of the path to read from the neighbour, in any order. Each must exist on the `in` input. AN EMPTY LIST IS AN ERROR rather than a default, which is where this param parts company with transferAlongPath's and transferByIndex's otherwise identical one: 'everything' cannot work here because every shifted value needs a DESTINATION NAME, and there is no rule that could invent one you would ever be able to grep for; and the one column every cloud carries is P, whose shift — 'the position of the next point' — is almost never what somebody reaching for this node meant. Say what you want: attributes ["station"], outNames ["nextStation"]. READING P IS ORDINARY and is the second-most common use after an arc coordinate: shift P into 'nextP' and subtract to get the vector to the next point along the path, which is the segment direction at every station without an arc table. Reading the standard bookkeeping columns is likewise allowed — there is no exclusion list here, because there is no 'everything' default for an exclusion list to trim. A name this node cannot find is refused with the input's point attributes listed, and an empty or repeated entry is refused too. |
| `outNames` | stringList | `[]` |  |  |  | Where each shifted value is written, PARALLEL to `attributes`: outNames[i] receives the neighbour's attributes[i]. Must be exactly as long as `attributes` — a mismatch is refused naming both lengths, because a shorter list is either a forgotten name or a name in the wrong slot and this node cannot tell which. EXPLICIT NAMES RATHER THAN A GENERATED PREFIX: a column called 'next_station' that no node in the graph mentions is a name nobody can grep for, and renaming the source silently renames a column three nodes downstream. AN ENTRY MAY NOT NAME A COLUMN `attributes` IS READING. Reading and writing one column in a single pass has two possible meanings — every point sees the values it arrived with, or every point sees whatever the walk has already overwritten — and they differ at the first point of every path, so it is refused rather than resolved. Shift into a new name and removeAttribute the original afterwards if the original is genuinely dead. EACH COLUMN TAKES THE SOURCE'S SHAPE — type, tuple size and default value — so this is a COPY TARGET and not a reporting slot: an existing column of another shape under one of these names is REPLACED rather than refused, exactly as transferAttribute replaces its destination, because overwriting is what a copy IS. 'P' IS THE ONE NAME REFUSED OUTRIGHT, same shape or not, and the reason is this node's miss rule rather than squeamishness: the destination column is RESET before the walk, so every point with no neighbour — a point on no polyline, or any point at all under outOfRange 'miss' — would be left at P's default and the cloud would collapse onto the origin while the cook still looked fine. Shift into a name of your own; if you really do want to move points onto their neighbours' positions, write that name into P deliberately with setAttribute, having decided first what the ends should do. |
| `offset` | i32 | `1` |  |  |  | How many positions along the path's walk order to look, counted in POINTS and not in distance — the neighbour, not the metre. +1 (the default) is the next point, +2 the one after it. NEGATIVE IS LEGAL and looks BACKWARDS: -1 is the previous point, which is the lag half of the pair and the thing that turns a column of forward gaps into a column of backward ones. 0 IS LEGAL AND COPIES the attribute into its new name unchanged; it is not refused, because a shift of nothing is a well-defined shift and a graph whose offset is computed should not fail the cook when the number comes out zero. Note that even at 0 this is not a plain attribute copy: a point on no polyline still gets the default rather than its own value, because it has no walk to be at position 0 of. AN OFFSET LARGER THAN A PATH'S POINT COUNT is not an error — it is exactly what `outOfRange` is for, and under 'wrap' it comes back round in a single modulo however far out it is. Must be a whole number; a fractional or non-finite offset is refused naming this param, because a position along a walk is an ordinal and there is no point half way between two of them (the value half way between them is transferAlongPath's question, asked in arc length). |
| `outOfRange` | enum | `"wrap"` |  | `wrap`, `clamp`, `miss` |  | How a position outside [0, pointsInThisPolyline-1] is read. Per POLYLINE, always: each path is its own sequence and nothing ever reaches out of one path into another, whatever this is set to. 'wrap' (the default) takes a EUCLIDEAN modulo over that polyline's point count — the remainder is made non-negative before use, so -1 from the FIRST point is the LAST point rather than the -1 that JavaScript's own % operator returns, and an offset many times the path's length comes back round in one step. On a CLOSED path this is simply the ring, and it is the default because a lap, a loop of stations and a cycle of archetypes are what paths in this library mostly are. ON AN OPEN PATH 'wrap' STILL WRAPS, and that is a deliberate divergence from pathRuns' `wrap`, whose description says 'no effect on an open path': the two share a word and not a question. pathRuns' wrap is about a SEAM — may a run cross the closing segment — and an open path has no seam to cross. This param is transferByIndex's `outOfRange`, a policy for an ORDINAL that ran off the end of a list, and the list is there whether or not a closing segment joins its ends. Reading it as 'clamp' on an open path would give one setting two answers depending on a flag the author may not control, and a clamped value is indistinguishable downstream from a real neighbour. If the ends of an open path should have NO neighbour, say that with 'miss', which is the setting that means it. 'clamp' pins the position to the polyline's first or last point, so the last point of an open path reads itself at +1 and nothing misses; it IGNORES CLOSURE, so a closed path under 'clamp' does not come round to its start — pick it when the vertex order carries meaning of its own and the ends are ends. 'miss' leaves the destination column at its DEFAULT (the source attribute's own default value, since these columns are this node's to create) and flags the point 0 through hitAttr. Use it when running off the end means 'no answer' rather than 'the nearest answer': the other two both invent one. It ignores closure exactly as 'clamp' does. CLOSURE CHANGES THE COUNT, NEVER THE POLICY is the whole rule here: a closed path's repeated last vertex is not a place, so the ring it forms has one entry per point — and after that, only 'wrap' comes round it. A closed path under 'clamp' or 'miss' still has a first position and a last, which is what lets a lap be walked as a sequence when that is what you meant. A polyline of ONE point — a closed primitive whose two vertices are the same point — is a ring of one under 'wrap' and 'clamp' alike, so it reads itself at every offset; under 'miss' it hits only at offset 0. A GEOMETRY WITH NO POLYLINE AT ALL is untouched by this param: every point misses under all three settings, because a point with no walk is not at a position that could be inside or outside a range. That is the same answer a stranded point in a partly-pathed cloud gets, and deliberately so. |
| `hitAttr` | string | `""` |  |  |  | When non-empty, writes a per-point flag of this name onto the OUTPUT'S POINT DOMAIN (bool, tuple 1). The polarity is the HIT: 1 means this point found a neighbour and received its values, 0 means it did not and its destination columns hold the source attribute's default. A 0 has exactly two causes, and telling them apart is what makes this worth writing: the point belongs to NO polyline (a geometry carrying no polyline at all makes every point that kind), or outOfRange is 'miss' and its neighbour ran off the end of its path. Under 'wrap' and 'clamp' the second cause cannot happen, so a 0 there means the point is on no path at all — which is the only per-point way to find such a point, since a default is a real value and looks like one. Every point is written, so the column never carries a stale value from an earlier cook. Feed it to filterByAttribute (comparison 'eq', value 1) to keep only the points that landed, then removeAttribute to clean it up. Three kinds of name are refused rather than written: any attribute named in `attributes`, which this node READS and the flag would destroy; any name in `outNames`, which the flag would overwrite with a bool after the shift had already written the value; and any point attribute the input already holds under a DIFFERENT shape — the flag's shape is this node's to pick, so writing it there would delete that column and everything in it while the cook still looked fine (hitAttr "P" would leave a point cloud with no positions). An existing bool tuple-1 column of the same name IS reused and reset, which is what keeps the flag describing THIS shift only. On a clash, give the flag a name of its own (a "__" prefix marks it internal, e.g. "__hit") or removeAttribute the existing column first. Empty = don't record. |

## pivotBox

MOVES every cell's P TO A POINT OF ITS BOX and re-expresses the box about it, so THE BOX STAYS WHERE IT IS IN THE WORLD: the hand-off from a grammar's cells to instances. A CELL IS A POINT WITH A BOX, as in splitBox: its standard `boundsMin`/`boundsMax`, an extent in the point's OWN frame (world = P + rot * (scale * x)), and every piece of one grammar root keeps that root's P, rot and scale, which is what lets neighbouring pieces meet exactly. copyToPoints and spawnInstances place a copy AT P, so a piece's P must first move to the piece: this node does that. THE MAP, per cell, with f the `pivot` fraction on each box axis: c = (1 - f) * min + f * max, held as an f32 (0 the min face, 0.5 the centre, 1 the max face, outside 0..1 past the face — placeBox's anchor reading); P becomes P + rot * (scale * c), the world position of that point; boundsMin and boundsMax become min - c and max - c. rot and scale are KEPT, so P + rot * (scale * x) gives every corner the world position it had: a rotated or mirrored cell keeps its oriented box. With the default [0.5, 0.5, 0.5] P lands at the box's centre and the box runs -size/2..size/2 about it; [0.5, 0, 0.5] puts P at the middle of the box's floor. THE CELL-TO-INSTANCE TAIL: pivotBox, then setAttribute scale = mul(attribute("scale", 3), box("size")) and setBounds boundsMin [-0.5, -0.5, -0.5], boundsMax [0.5, 0.5, 0.5] (the unit box the asset fills, about P), then copyToPoints or spawnInstances — or boxesToMesh straight from the cells, which needs no pivot, since it builds every face through the cell's transform. PIVOT AT THE END OF A GRAMMAR: pieces split after a pivot are pieces of DIFFERENT frames, so they lose boxContact's same-frame comparison and their shared faces stop being bit-exact. Rounding: the rotation is normalized in f64 first (as boxContact and boxesToMesh read it; a zero quaternion is the identity) and its matrix entries within 2^-40 of 0 or 1 are snapped to them, so a quarter or half turn stored in f32 moves a point exactly; P and the corners are computed in f64 and stored as f32, each -0 written +0. Because c is held as an f32, min - c and max - c are exact whenever c is within a factor of two of the corner, and the world box then moves only by the rounding of the new P — exact for dyadic boxes at dyadic P under no turn, quarter or half turns and dyadic scales. `pivot` is a vec3, plain or a FIELD resolved per cell on the INPUT (box names read the box as it arrived; a scalar broadcasts), held as f32. `where` passes chosen cells through EXACTLY as they arrived (0 = untouched). An input box that is inside out or not finite, a non-finite P, rot or scale, and a result past f32's range are refused naming the cell. Same points, same order, same SEEDS, every attribute (strings included), the topology and the detail attributes carried; only P, boundsMin and boundsMax are written. Point identity hashes P and the seed, so a randomField drawn after this node differs from one drawn before it (sibling pieces sharing one P still draw apart before it, since splitBox and shellSplit give each piece its own seed); a draw that must survive the move reads an attribute, as randomFrom(attribute("bay")). CPU only, as every box node.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-cells-to-instances.json](../graphs/basics-cells-to-instances.json) — 1 total (`pcg graphs --node pivotBox`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `pivot` | vec3 | `[0.5,0.5,0.5]` |  |  | yes | Where in its box each cell's P moves, as a FRACTION of the box per box axis — placeBox's anchor reading: 0 the min face, 0.5 the centre, 1 the max face, values outside 0..1 past the face. [0.5, 0.5, 0.5] (the default) puts P at the box's centre, [0.5, 0, 0.5] at the middle of its floor (where a building stands), [0, 0, 0] at its min corner. The box is re-expressed about the new P, so it does not move. As a FIELD it is resolved per cell on the INPUT (box names read the box as it arrived) and a scalar broadcasts to all three. Held as f32; must be finite. |
| `where` | f32 | `1` |  |  | yes | Which cells are pivoted: nonzero pivots the cell, 0 leaves it EXACTLY as it arrived — P and box untouched, and its box not checked (a FIELD param is still resolved, and refused if not finite, on every cell). As a field it is resolved per cell, e.g. attributeIs("kind", "window"). Must be finite. |

## placeBox

PLACES ONE BOX INSIDE, OR AGAINST, every cell's own box, by SIZE, ANCHOR and OFFSET on each axis, and writes it as the cell's new box: the scope operations of a shape grammar (size the scope, centre it, move it in its own frame) with a per-axis min / centre / max justify. It is for the box NO SPLIT MAKES — a chimney standing in the air beside a roof's upper layers, a stud of trim one in from a wall's left edge, a panel centred on a face — where a split can only divide what is there. A CELL IS A POINT WITH A BOX, as in splitBox: its standard `boundsMin`/`boundsMax`; the new box replaces it, and NOTHING ELSE CHANGES: the same points in the same order (a box of NO VOLUME is KEPT, never dropped), every attribute carried (strings included), the topology and the detail attributes carried, the SEED UNCHANGED, P, rotation and scale neither read nor written — the box is an extent in the point's OWN frame (world = P + rot * (scale * x)), so the placement is made along the box's own axes and the placed box turns and moves with its point, and the node drops in for the setBounds it replaces on a point cloud or a mesh. PER AXIS, in the cell's box: the placed box is `size` long (`units` "absolute", a length, or "relative", a fraction of the cell's extent on that axis: 1 fills it); its ANCHOR fraction lands on the cell's same fraction — anchor 0 puts its min side on the cell's min side, 1 its max side on the cell's max side, 0.5 its centre on the cell's centre, any value between them in proportion, so min = cellMin + anchor * (cellLength - size) — and then it moves by `offset` (`offsetUnits` "absolute", "relative" to the cell's extent, or "self", multiples of the placed box's own size). An anchor in 0..1 with a size no larger than the cell is INSIDE it; "self" makes AGAINST easy: anchor 1 with offset 1 self stands the box just outside the max side, its min on the cell's max — a box on top of its cell is anchor [0.5, 1, 0.5], offset [0, 1, 0], offsetUnits ["absolute", "self", "absolute"], fit "allow". THE FRAME is `frame`, offsetBox's, decided once per cook, never guessed: "box" reads every vec3 here as [x, y, z] along the box's own axes; "face" reads them as [ALONG, UP, OUT] in the frame shellSplit writes on every face and splitBox carries onto every piece cut from one — along from `alongAxisAttr`/`alongSignAttr`, out from the `outwardAttr` normal, and up DERIVED as the axis that keeps along x up = out (shellSplit's right-handed frame), so a facade that writes no up still has one. Min along is the LEFT as seen from outside, min up the bottom, and max out the OUTER FACE, so "one stud in from the left, flush to the outer face, one stud deep" is the same text on all four walls: anchor [0, 0, 1], offset [1, 0, 0], size [1, <height>, 1]. Offsets are along the frame's signed axes. The box names in a field keep the box's own axes (box("sx") is the x extent on every face), but "relative" units read the cell's extent on the FRAME axis. Under "face" a missing frame attribute is refused, naming every one that is missing; a cell with no frame (a shellSplit pass-through has axis -1; its interior has a zero normal) is refused naming the cell — skip it with `where`. EVERY VEC3 HERE (size, anchor, offset) is plain or a FIELD resolved on the cell, one value or three per cell, with the cell's box names, so a decision drawn once (a randomField in an offset, or an attribute set upstream) places the box — and the same decision read by two placeBox nodes places two boxes consistently, which is how a chimney and its shadow agree. A negative size counts as 0. SNAP (`snap`, a step per box axis, 0 = none) then puts the box on a lattice, by offsetBox's rule: `snapTo` "lattice" moves both corners onto the lattice anchored at 0 of the box's coordinates — the cell's P, in its own units — (splitBox's lattice, to f32 precision), "size" rounds the size to whole steps keeping the centre; `snapMode` "round" (the default) is the nearest line, "floor" and "ceil" down and up the axis, "out" GROWS the box onto the lattice and "in" SHRINKS it — a box with no whole step inside it shrinks to a box of no volume at its centre. Anchor 0.5 with snap 1 and snapMode "floor" is "as nearly centred as whole studs allow". FLUSH MEANS FLUSH: on an axis that is not snapped, a corner within two f32 ulps at the cell's coordinates (and, for a box with size, within a quarter of that size) of one of the cell's planes is put ON the nearer one; a snapped corner stays on its lattice line, and whether it is past the cell is judged on the stored f32 numbers. `fit` settles a box past its cell, axis by axis, after the snap: "error" (the default) refuses, naming the cell, the axis and the numbers; "allow" keeps the overhang (a box against the outside, a probe reaching past a face); "clamp" slides the box inside, keeping its size, and caps a box larger than its cell at the cell's extent; "clip" cuts away what overhangs — a chimney's shadow grown two studs every way and kept inside its roof — and a box wholly outside is cut to no volume on the plane it passed. Every box goes through `fit`, a box of no volume included. FIT GLOSSARY, one meaning per word across splitBox, shellSplit, placeBox and offsetBox: "error" refuses the cook, naming the cell and the numbers; "allow" writes the result as computed; "scale" rescales what does not fit, in proportion, until it fits exactly; "clamp" slides the box back inside, keeping its size, and cuts a box larger than its limit to the limit; "clip" cuts away what passes the limit and keeps the rest, nothing moved or rescaled. This node takes "error", "allow", "clamp", "clip". `where` passes chosen cells through with their box unchanged. `labelAttr` (opt-in) names a string attribute that receives `label` on every placed box, which is how one node both places a part and names it for applyRules or a material. CPU only: which cells are refused, and which lattice line a corner lands on, are comparisons per cell.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [examples-floorplan.json](../graphs/examples-floorplan.json), [examples-brick-house.json](../graphs/examples-brick-house.json) — 2 total (`pcg graphs --node placeBox`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `frame` | enum | `"box"` |  | `box`, `face` |  | The axes `size`, `anchor`, `offset`, `units` and `offsetUnits` are written in — offsetBox's `frame`, with its meaning. "box" (the default): [x, y, z] along the box's own axes, positive up each axis, min the box's min corner; the frame attributes are not read ("box" was called "world"; that word is refused with the rename stated). "face": [along, up, out] in each cell's own frame, read from `alongAxisAttr`, `alongSignAttr` and `outwardAttr` — the frame shellSplit writes on every face — with up derived so that along x up = out. On a wall that makes component 0 run LEFT TO RIGHT AS SEEN FROM OUTSIDE, component 1 bottom to top, component 2 from the inner face to the OUTER face, so anchor 0 is the left, the bottom and the inner face, and anchor 1 the right, the top and the outer face. Under "face" a missing frame attribute is refused, naming every one missing. Decided once per cook. `snap` is always per box axis, whichever frame. |
| `alongAxisAttr` | string | `"alongAxis"` |  |  |  | Read only with frame "face": the numeric tuple-1 point attribute holding each cell's ALONG axis code, 0 = x, 1 = y, 2 = z — shellSplit's `alongAxisAttr` default, carried by splitBox onto every piece. Any other value (shellSplit writes -1 on a cell it passed through), or the out axis itself, is refused naming the cell; `where` skips cells that have no frame. |
| `alongSignAttr` | string | `"alongSign"` |  |  |  | Read only with frame "face": the numeric tuple-1 point attribute holding the direction along runs, +1 or -1 (its sign is read; 0 or non-finite is refused naming the cell) — shellSplit's `alongSignAttr` default, which makes along run left to right as seen from outside every wall. |
| `outwardAttr` | string | `"outward"` |  |  |  | Read only with frame "face": the numeric tuple-3 point attribute holding each cell's OUTWARD normal — shellSplit's `outwardAttr` default. It must be ONE signed axis (exactly one nonzero component, its sign the side): that is the out axis, and up is derived from it and along. shellSplit's interior, whose normal is [0, 0, 0], and a tilted normal are refused naming the cell. |
| `size` | vec3 | `[1,1,1]` |  |  | yes | The placed box's size per axis of the frame, read by `units`: a LENGTH ("absolute") or a FRACTION of the cell's extent on that axis ("relative"; 1 fills it). AS A FIELD it is resolved on the CELL, three components or one broadcast to all three, and the box names read the cell's box: vec(2, box("sy") - 3, 1). A negative size counts as 0, and a box with no size on an axis is KEPT as a box of no volume there. A non-finite value is refused naming the cell. |
| `units` | stringList | `["absolute"]` |  |  |  | How `size` is read: ONE entry for all three axes, or three, one per axis of the frame. "absolute" is a length; "relative" is a fraction of the cell's extent on that axis — on a frame axis, the extent along it — so ["relative", "absolute", "relative"] with size [1, 2, 1] is a slab 2 tall over the cell's whole footprint. Decided once per cook. |
| `anchor` | vec3 | `[0.5,0.5,0.5]` |  |  | yes | Where the placed box sits in the cell, per axis of the frame, as a FRACTION: 0 lines its MIN side up with the cell's min side, 1 its MAX side with the cell's max side, 0.5 its centre with the cell's centre (the default: centred), and any fraction between in proportion — min = cellMin + anchor * (cellLength - size), a min / centre / max justify. In the "face" frame min is the left seen from outside, the bottom, and the inner face, so [0, 0, 1] is bottom left, flush to the outer face. A value outside 0..1 extrapolates, and `fit` settles any overhang. As a FIELD it is resolved on the cell, three components or one broadcast: vec(select(attribute("back"), 1, 0), 0, 0) hangs a box from the max side or the min side by a flag. A non-finite value is refused naming the cell. |
| `offset` | vec3 | `[0,0,0]` |  |  | yes | A move per axis of the frame after the anchor, read by `offsetUnits`, POSITIVE UP THE FRAME'S SIGNED AXIS — in the "face" frame, rightward seen from outside, upward, and outward — so "one stud in from the left" is anchor 0 with offset 1, and one stud in from the right is anchor 1 with offset -1. AS A FIELD it is resolved on the cell, three components or one broadcast; a placement drawn once upstream (an attribute) or here (a randomField) lands here. A non-finite value is refused naming the cell. |
| `offsetUnits` | stringList | `["absolute"]` |  |  |  | How `offset` is read: ONE entry for all three axes, or three. "absolute" is a length; "relative" a fraction of the cell's extent on that axis; "self" multiples of the PLACED box's own size there — so anchor 1 with offset 1 "self" stands the box just outside the cell's max side, touching it, and anchor 0 with -1 "self" just outside the min side: placing AGAINST the cell rather than in it (with fit "allow"). Decided once per cook. |
| `fit` | enum | `"error"` |  | `error`, `allow`, `clamp`, `clip` |  | What a placed box past its cell does, axis by axis, after `snap`. "error" (the default) refuses the cook, naming the cell, the axis (and its frame name), the box and the cell: a placement that leaves the cell by accident is the defect worth refusing. "allow" keeps it as placed — a box against the outside, a sill standing out of a wall. "clamp" slides it back inside keeping its size, and a box larger than the cell on an axis is cut to the cell's extent there. "clip" cuts away what overhangs and keeps the rest; a box wholly outside is cut to no volume on the plane it passed, and kept. "Past" is to f32 precision: on an unsnapped axis a corner within two f32 ulps at the cell's coordinates of a plane is ON the plane; on a snapped one, the stored f32 corner is compared with the plane. Every box is checked, a box of no volume included. FIT GLOSSARY, one meaning per word across splitBox, shellSplit, placeBox and offsetBox: "error" refuses the cook, naming the cell and the numbers; "allow" writes the result as computed; "scale" rescales what does not fit, in proportion, until it fits exactly; "clamp" slides the box back inside, keeping its size, and cuts a box larger than its limit to the limit; "clip" cuts away what passes the limit and keeps the rest, nothing moved or rescaled. This node takes "error", "allow", "clamp", "clip". Decided once per cook. |
| `snap` | vec3 | `[0,0,0]` | >= 0 |  |  | A LATTICE STEP per box axis [x, y, z] (whichever `frame`), 0 for none — offsetBox's `snap`. How the placed box lands on it is `snapTo` and `snapMode`, applied after the placement and before `fit`; under `snapTo` "lattice" the lattice is anchored at 0 of the box's coordinates — the cell's P, in its own units — splitBox's `snap` lattice, so a cut and a placement on the same lattice share its lines. A corner within f32 precision of a line counts as on it. A snap can move a corner outside the cell (refused under fit "error"). On an integer lattice whose cells are integer, anchor 0.5 with snap [1, 1, 1] and snapMode "floor" places a box as nearly centred as whole units allow. |
| `snapTo` | enum | `"lattice"` |  | `lattice`, `size` |  | What `snap` rounds — offsetBox's `snapTo`. "lattice" (the default): both corners onto the ABSOLUTE lattice anchored at 0, so neighbouring boxes share lines. "size": the placed box's SIZE on the axis to a whole number of steps, keeping its CENTRE, so a centred box of a stock size stays centred where it was placed. Decided once per cook. |
| `snapMode` | enum | `"round"` |  | `round`, `floor`, `ceil`, `out`, `in` |  | How the box lands on the `snap` lattice — the same five words on every box node. "round" (the default): each corner to the nearest line (a half rounds up), or the size to the nearest whole step. "floor" / "ceil": each corner down / up the axis, both the same way, so a box a whole number of steps long keeps its size (the size rounds down / up). "out": the box GROWS onto the lattice — its min corner down, its max corner up (the size up). "in": it SHRINKS onto it, the reverse (the size down); a box with no whole step inside it becomes a box of no volume at its centre. Ignored where the step is 0. Decided once per cook. |
| `where` | f32 | `1` |  |  | yes | Which cells are PLACED: nonzero places the box, 0 PASSES THE CELL THROUGH with its box, and everything else, unchanged (and no label written; a label column this node creates gives it ""). As a field it is resolved per cell, e.g. attributeIs("piece", "wall"). Under frame "face" the frame attributes must exist, but their values are read only where it is nonzero, so it is how cells with no frame are skipped. A non-finite value is refused naming the cell. A field `size`, `anchor` or `offset` is still resolved on EVERY cell, passed-through ones included, so it must be finite there too. |
| `labelAttr` | string | `""` |  |  |  | OPT-IN: name of a STRING point attribute (tuple 1) receiving `label` on every placed box — the part's name for applyRules, attributeIs or a material. Empty (the default) writes none. A REPORTING SLOT: an input column of the same shape is rewritten on placed boxes and kept on cells `where` passes through, one of another shape is refused, and a standard point attribute is refused by name. |
| `label` | string | `""` |  |  |  | The label written to `labelAttr` on every placed box (ignored when `labelAttr` is empty), e.g. "chimney". One string for the node; a label that varies per cell is a setAttribute with `values` after this. |

## pointGrid

Creates a regular grid of points: countX * countY * countZ points starting at origin, stepped by spacing per axis. Point order is X fastest, then Y, then Z. Emits a standard point cloud; per-point seed is hashed from the node seed and point index.

**Category:** source

**Inputs:** *(none)*

**Outputs:** `out` (geometry)

**Examples:** [basics-point-grid.json](../graphs/basics-point-grid.json), [basics-inline-field-params.json](../graphs/basics-inline-field-params.json), [basics-jitter-points.json](../graphs/basics-jitter-points.json) — 29 total (`pcg graphs --node pointGrid`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `countX` | i32 | `10` | >= 1 |  |  | Number of points along X. Minimum 1. |
| `countY` | i32 | `1` | >= 1 |  |  | Number of points along Y. Minimum 1. |
| `countZ` | i32 | `10` | >= 1 |  |  | Number of points along Z. Minimum 1. |
| `spacing` | vec3 | `[1,1,1]` |  |  |  | Distance between neighboring points along each axis, in world units. |
| `origin` | vec3 | `[0,0,0]` |  |  |  | World position of the first point (index 0,0,0). |

## pointLine

Creates `count` evenly spaced points on a straight line. mode 'endpoints' (the default) pins both ends: the points spread between start and end, so the STEP is derived and changes whenever the count does. mode 'spacing' states the step instead: the points run from start toward end, exactly `spacing` world units apart, so the FAR END is derived (start + spacing * (count - 1) along the direction) and raising the count APPENDS points rather than re-spacing the ones already there — which is what any consumer keyed on position needs (a forEach item key, a nearest-neighbour transfer), and what forces an author of the default mode to restate count - 1 inside `end` to keep a known step. In 'endpoints' mode both endpoints are included by default, so the last point sits exactly on end; set includeEnd false to sample the half-open range instead, stopping one step short of end — which is what a sweep that wraps back on itself needs so its first and last samples are not the same place. count 1 places a single point at start in every mode. Emits a standard point cloud; per-point seed is hashed from the node seed and point index.

**Category:** source

**Inputs:** *(none)*

**Outputs:** `out` (geometry)

**Examples:** [basics-phyllotaxis.json](../graphs/basics-phyllotaxis.json), [basics-self-similar-frond.json](../graphs/basics-self-similar-frond.json), [basics-spiral-stair.json](../graphs/basics-spiral-stair.json) — 23 total (`pcg graphs --node pointLine`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"endpoints"` |  | `endpoints`, `spacing` |  | Which end of the line the author states: 'endpoints' places `count` points between start and end, deriving the step; 'spacing' places `count` points stepping `spacing` units from start toward end, deriving the far end. `count` is read in both. |
| `count` | i32 | `10` | >= 1 |  |  | Number of points to place, in both modes — it is never the derived quantity here. Minimum 1. |
| `start` | vec3 | `[0,0,0]` |  |  |  | World position of the first point, in both modes. |
| `end` | vec3 | `[10,0,0]` |  |  |  | World position of the last point in 'endpoints' mode. In 'spacing' mode only the DIRECTION from start to end is read: the line runs that way and its far end is derived as start + spacing * (count - 1) along it, so the distance from start is not read and the last point generally does NOT sit on end — put end anywhere along the direction you want (one unit away is the clearest way to write it). Must not coincide with start in 'spacing' mode: two identical positions name no direction to step along. |
| `includeEnd` | bool | `true` |  |  |  | Whether `end` is one of the emitted positions, in 'endpoints' mode. true (the default) samples the closed range [start, end]: `count` points stepping (end - start) / (count - 1), the first on start and the last exactly on end — use it for a run of points with both ends pinned, such as a fence between two posts. false samples the half-open range [start, end): `count` points stepping (end - start) / count, the last one step short of end — use it when the segment is a parameter that wraps, so a closed shape gets `count` distinct positions and no duplicate seam. count 1 emits a single point at start in both modes; count 0 emits nothing. 'spacing' mode has no authored endpoint to include or exclude — its derived far end IS the last point, and the same run is equally the half-open sampling of [start, start + count * spacing) — so the choice does not arise there and false is REFUSED rather than accepted as a setting that moves nothing. |
| `spacing` | f32 | `1` | >= 0 |  |  | Distance between consecutive points in world units when mode is 'spacing'. The step is EXACT and independent of the count: point i sits at start + i * spacing along the direction, a function of i alone, so raising `count` leaves every point already placed byte-identical and appends the new ones. That is the whole difference from 'endpoints' mode, where the count and the step are one number seen from two sides and one more point re-spaces the entire line. Must be > 0 and finite. Ignored in 'endpoints' mode. |

## pointList

Creates one point per [x, y, z] triple in `positions`, in list order, and writes named per-point columns from literal values: a TABLE of points carried in the graph file itself. Use it for authored or surveyed coordinates — a measured outline, a star catalogue, the stations a drawing gives — that no rule produces. Use pointGrid, pointLine or a scatter when a rule places the points (they cost a few params, not one number per point), and dataInput when the host supplies points at runtime (its item list is injected per cook and serializes empty; this node's values ARE the graph). Columns are three parallel lists: `columnNames`, `columnTypes` (f32, i32, u32, bool, or vec2 / vec3 / vec4 for f32 vectors; empty means every column is f32) and `columnValues`, which holds the columns one after another in `columnNames` order, each as count * tupleSize numbers (a vec3 column is x0, y0, z0, x1, ...). P stores the f32 of each literal, a column stores its value in its type, and per-point seed is hashCombine(node seed, point index) — the SAME formula as pointGrid, so a pointGrid with countX = n plus one setAttribute per column reading ramp(index(), [[0, v0], [1, v1], ...]) cooks to the same data bytes as this node with the same id, every column and P included: a ramp read exactly on a stop answers the f32 of that stop's value, which is what this node stores. The one exception is an integer column holding a value an f32 cannot (past 2^24): a ramp writes an f32 column, so i32 2147483647 wraps to -2147483648 through it, where this node stores the literal itself, so it is the exact one of the two. A standard attribute it overwrites also keeps its standard default (color [1, 1, 1, 1], density 1), where setAttribute resets the default to 0. Refused by name rather than stored wrong: `positions` not whole triples; a column name that is empty, repeated, "P" (write positions) or "seed" (computed, as on every source); a standard attribute (rot, scale, density, boundsMin, boundsMax, color) declared with a type other than its own; an unknown column type; a `columnValues` length that is not what the columns declare (the message lists every column's slice); and a value its column cannot hold (non-finite, past the f32 range, a fractional or out-of-range integer, a bool other than 0 or 1), naming the column and the point. Not field-capable: every param is data, so there is nothing per element to evaluate. Emits a standard point cloud with no primitives; pointsToPath turns it into a polyline.

**Category:** source

**Inputs:** *(none)*

**Outputs:** `out` (geometry)

**Examples:** [basics-a-table-of-points.json](../graphs/basics-a-table-of-points.json), [basics-pack-bricks.json](../graphs/basics-pack-bricks.json), [basics-cells-to-instances.json](../graphs/basics-cells-to-instances.json) — 3 total (`pcg graphs --node pointList`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `positions` | numberList | `[]` |  |  |  | Point positions as a flat list [x0, y0, z0, x1, y1, z1, ...]: one point per triple, in list order, stored as f32. The length must be a multiple of 3; the point count is length / 3, and an empty list emits an empty cloud. Every value must be finite and within the f32 range. |
| `columnNames` | stringList | `[]` |  |  |  | Names of the per-point columns to write, in the order their values appear in `columnValues`. Each name is non-empty and unique. "P" is refused (the positions are `positions`) and so is "seed" (computed per point from the node seed, as on every source — keep an authored id under another name). The standard attributes rot, scale, density, boundsMin, boundsMax and color may be named, which OVERWRITES their defaults, but only with their own type: rot and color are vec4, scale, boundsMin and boundsMax vec3, density f32. Empty (the default) writes positions only. |
| `columnTypes` | stringList | `[]` |  |  |  | One type per entry of `columnNames`: f32, i32, u32 or bool (one number per point), or vec2, vec3, vec4 (an f32 column of that many components per point). Empty (the default) means every column is f32; otherwise the list must be exactly as long as `columnNames`. i32 and u32 values must be whole numbers in their type's range, and bool values 0 or 1, since a literal the column cannot hold is refused rather than wrapped or rounded. |
| `columnValues` | numberList | `[]` |  |  |  | Every column's values, one column after another in `columnNames` order. A column takes count * tupleSize numbers (count = positions.length / 3; tupleSize 1 for f32, i32, u32 and bool, 2, 3 or 4 for the vectors), point-major within the column, so a vec3 column is [x0, y0, z0, x1, y1, z1, ...]. The total must be exactly the sum over the columns — a length that is not is refused with each column's expected slice, which is where to look. |

## pointNeighborhood

Measures each point's neighborhood inside the same cloud and writes the result as point attributes: countAttr receives how many other points lie within radius (u32), and averageAttr/averageOutAttr average a numeric point attribute over those neighbors (f32, same tuple size — averaging "P" gives each point the centroid of its neighbors, which is one Lloyd relaxation step away from even spacing). Distances are 3D over P and boundary-inclusive. A point with no neighbors gets count 0 and keeps its OWN value as the average, so a displacement built from the average is zero for isolated points instead of undefined. Points with a non-finite coordinate are nobody's neighbor and have none themselves. Both places where this node has to pick an order — which neighbors a maxCount cap keeps, and the order their values are summed — are keyed on point IDENTITY (position bits plus the `seed` point attribute), never on the array index, so reordering the input cannot move a count, a kept set, or a single bit of an average. Uses a uniform spatial grid, so it stays fast well beyond a few thousand points. Output is the input with the new attributes added; nothing is moved or removed — countAttr and averageOutAttr are reporting slots whose shape this node picks, so pointing either at an existing attribute of a DIFFERENT shape is refused rather than silently deleting it (a same-shape column is reused and reset).

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-neighborhood-count.json](../graphs/basics-neighborhood-count.json), [basics-neighborhood-varying-radius.json](../graphs/basics-neighborhood-varying-radius.json), [examples-streamed-terrain.json](../graphs/examples-streamed-terrain.json) — 3 total (`pcg graphs --node pointNeighborhood`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `radius` | f32 | `1` | >= 0 |  | yes | Neighborhood radius in world units, boundary included. 0 searches nothing: every count is 0 and every average falls back to the point's own value, and a radius that is negative or NaN is read the same way. As a FIELD it is a PER-POINT radius, evaluated on the input's points, so each point measures the neighborhood it asks for — a count of what is within reach of THIS point rather than within one distance shared by the cloud. The reading it enables is 'how crowded am I, at my own scale': a radius read from an attribute lets a big point survey a big neighborhood and a small one a small neighborhood in the same cook. NEIGHBORHOOD IS THEN NOT SYMMETRIC, and that is the point rather than a defect — with a per-point radius, B lying inside A's radius does NOT put A inside B's, so `countAttr` counts what each point can see and two points can disagree about whether they are neighbors. That asymmetry is exactly what a per-point radius means, and it is why this param needs no pair rule where connectPoints' radius does: an EDGE is one thing shared by two points, so a per-point reach there has to say which of the two governs — it takes the LARGER — while a count is one point's own measurement and belongs to it alone. Cost, not correctness, is what a mixed set of radii affects: the grid is sized from the largest FINITE radius, and a query wider than that scans more cells rather than returning a different answer. An infinite radius is legal and means the whole cloud — the query falls back to a full scan, so it is O(n) per point. Under a partitioned cook the halo a cell needs is the GLOBAL MAXIMUM this field can return anywhere in the world, which is a bound to be derived and not measured: the cloud a cell sees has already been clipped by the halo being sized, so the far neighbor that would have set it is the one it cannot see. Take a constant times the range of whatever drives it (a noise field is in [-1, 1], so `2 + 3 * noise` maxes at 5) and pass that. Underestimating does not throw — it silently misses neighbors, at the seams only. |
| `maxCount` | i32 | `0` | >= 0 |  |  | Cap on how many neighbors each point keeps: the nearest maxCount of them, distance ties resolved toward the lower point IDENTITY (a hash of the neighbor's position bits and its `seed` attribute) so the kept set is a property of the points and not of the order they arrived in. 0 (the default) keeps every neighbor within the radius. Use it to bound the cost in dense clouds. |
| `includeSelf` | bool | `false` |  |  |  | Count the point itself as one of its neighbors (and include its own value in the average). False (the default) measures the OTHER points, so an isolated point counts 0. |
| `countAttr` | string | `"nbrCount"` |  |  |  | Name of the u32 point attribute receiving the neighbor count. Empty writes no count (then averageAttr must be set). The shape is this node's to pick (u32, tuple 1), so a name the input already holds under a DIFFERENT shape is REFUSED, not overwritten: writing it would delete that column outright and the cook would still look fine (countAttr "P" would leave a point cloud with no positions). An existing u32 tuple-1 column of the same name IS reused and reset, so re-running this node over its own output is fine. To write over something of another shape, removeAttribute it first, or pick another name. |
| `averageAttr` | string | `""` |  |  |  | Numeric point attribute (tuple 1..4) to average over each point's neighbors, for example "P". Empty (the default) computes no average. |
| `averageOutAttr` | string | `"nbrAvg"` |  |  |  | Name of the f32 point attribute receiving the neighbor average; it takes averageAttr's tuple size. Required when averageAttr is set, ignored otherwise. Naming it the same as averageAttr overwrites in place — allowed whenever that attribute is ALREADY f32 at the same tuple size, which "P" is. Otherwise the shape is this node's to pick, and a name the input holds under a DIFFERENT shape is REFUSED rather than deleted and re-added: averaging an i32, u32 or bool attribute needs an output name of its own, since the average is always f32. An existing column of the matching f32 shape IS reused and reset. |

## pointScatterInBounds

Scatters `count` points uniformly inside the axis-aligned box [boundsMin, boundsMax]. Each coordinate is an independent deterministic hash of (seed, point index, axis) — same seed always reproduces the same points, independent of evaluation order. Emits a standard point cloud.

**Category:** source

**Inputs:** *(none)*

**Outputs:** `out` (geometry)

**Examples:** [basics-scatter-in-bounds.json](../graphs/basics-scatter-in-bounds.json), [basics-attribute-from-noise.json](../graphs/basics-attribute-from-noise.json), [basics-even-spacing.json](../graphs/basics-even-spacing.json) — 42 total (`pcg graphs --node pointScatterInBounds`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `count` | i32 | `100` | >= 0 |  |  | Number of points to scatter. Minimum 0. |
| `boundsMin` | vec3 | `[0,0,0]` |  |  |  | Minimum corner of the box, in world units. |
| `boundsMax` | vec3 | `[1,1,1]` |  |  |  | Maximum corner of the box, in world units. Should be >= boundsMin per component. |
| `seed` | u32 | `0` |  |  |  | Extra seed folded into the node seed; change it to re-roll the scatter. |

## pointScatterInWorld

Scatters points over an INFINITE lattice anchored to world coordinates, then returns the ones inside the query window [boundsMin, boundsMax). A point's position and per-point seed are a pure function of (seed, latticeMode, cellSize) and its own lattice cell and index — never of the window, and density only decides how many points a cell holds — so the same world position always yields the same point under ANY query. Note what is NOT in that list: the graph seed. Alone among the nodes here, this one ignores it (see the `seed` param), because a lattice that moved with the graph seed could be de-anchored silently by an author reseeding a level graph per cell. That is what makes a halo just a wider query, lets a region cooked whole and the same region cooked in pieces agree byte for byte, and lets two cells on a boundary agree on what is there; pointScatterInBounds computes positions from the bounds and can promise none of it. Expected population is exactly `density * area` of the window in "xz" mode and `density * volume` in "xyz" mode, so an author can predict the count without cooking. Points are ordered by lattice cell (Z outer, then Y, then X) and by index within a cell, so any two windows list their shared points in the same relative order. Windows need not align to the lattice: partial cells are generated whole and clipped per point. The clip is half-open — a point on the min face belongs to this window, a point on the max face belongs to the next one — so abutting windows partition the world with no gap and no duplicate. The coordinate the clip tests is the f32 the point cloud STORES, not the wider intermediate it was computed from, so "inside the window" is a statement about the position you can actually read back: far from the origin, where the f32 spacing grows toward the lattice spacing, the two differ, and testing the intermediate would emit points whose stored position lies outside the window and have two abutting windows both disown the same point. Emits a standard point cloud.

**Category:** source

**Inputs:** *(none)*

**Outputs:** `out` (geometry)

**Examples:** [basics-scatter-in-world.json](../graphs/basics-scatter-in-world.json), [examples-streamed-terrain.json](../graphs/examples-streamed-terrain.json) — 2 total (`pcg graphs --node pointScatterInWorld`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `density` | f32 | `0.01` | >= 0 |  |  | Points per square world unit in "xz" mode, per cubic world unit in "xyz" mode. The expected number of points in a window is exactly density * area (or density * volume), for any window: a cell holds floor(lambda) points plus one more with probability frac(lambda), where lambda = density * cellSize^2 (or ^3). Raising density only ADDS points — the ones already there keep their positions and their per-point seeds — so it is safe to tune against a fixed layout. 0 emits nothing. |
| `cellSize` | f32 | `10` | >= 0 |  |  | Edge length, in world units, of this node's own lattice cell — the patch over which the point count is quantized. It controls clumping, not population: population is set by density alone, while cellSize decides how evenly the points are spread (small cells spread them out, large cells let counts vary more). Must be > 0. Set it from the content's scale and NEVER from a World level's cellSize: tying the two would make the generated content a function of the runtime's partitioning, so re-tuning a level's streaming, or cooking the same region at two levels, would change the world. |
| `latticeMode` | enum | `"xz"` |  | `xz`, `xyz` |  | "xz" (default): a 2D lattice on the XZ plane, every point at Y = height, with the Y components of boundsMin/boundsMax IGNORED (they may be infinite, matching an "xz" World cell, which is unbounded in Y). "xyz": a 3D lattice, with Y coming from the lattice and the full box clipped. The two modes are independent point sets, not slices of one — switching modes re-rolls the layout. |
| `height` | f32 | `0` |  |  |  | World Y of every point in "xz" mode. Ignored in "xyz" mode. The 2D lattice is deliberately flat rather than spread over the query's Y range: deriving Y from the window is exactly what makes a source non-anchored. To put points on a surface, displace Y afterwards from a position-anchored field (e.g. setAttribute on P with a noise field) — that stays a function of world position, so it survives any query window. |
| `boundsMin` | vec3 | `[0,0,0]` | (±Infinity ok, but never serializes) |  |  | Minimum corner of the query window, in world units — INCLUSIVE. Read only to choose which lattice cells to visit and to clip; it never moves a point. In "xz" mode the Y component is ignored, and -Infinity is the honest thing to write there: a World "xz" cell is a column with no vertical extent. An axis this mode DOES read must still be finite — the window chooses which cells to visit, so it has to be bounded — and an infinity never survives JSON, so a graph that must serialize needs a finite window. |
| `boundsMax` | vec3 | `[100,100,100]` | (±Infinity ok, but never serializes) |  |  | Maximum corner of the query window, in world units — EXCLUSIVE, so abutting windows neither drop nor duplicate a point on their shared face. Read only to choose which lattice cells to visit and to clip. In "xz" mode the Y component is ignored and may be +Infinity, subject to the notes on boundsMin. A window with max <= min on a read axis emits nothing. |
| `seed` | u32 | `0` |  |  |  | THE seed of the world this node lays down, and its ONLY source of randomness: the graph seed does not reach it, which is unlike every other node in this library and is the point. Change THIS to re-roll the world; changing the graph seed, calling graph.setSeed inside a level's bind, passing a CLI seed override, or renaming the node all leave the lattice byte-identical, so anchoring cannot be lost by accident. It must be the SAME for every query that has to agree — in a World, bind it from the cell-INVARIANT `ctx.worldSeed` or `ctx.levelSeed`, never from the per-cell `ctx.seed`, which would make each cell an unrelated world and the guarantee empty. The cost of all this, which you have to plan for: two nodes of this type with identical params scatter IDENTICAL points, exactly as two noise fields with one spec are one field — so give each layer its own value here (e.g. hashCombine(ctx.worldSeed, 1) for trees and hashCombine(ctx.worldSeed, 2) for rocks) rather than relying on the node id to separate them. |

## pointScatterOnPath

Scatters `count` points at UNIFORMLY RANDOM ARC POSITIONS along EVERY polyline primitive of the `path` input and emits them as a NEW point cloud lying exactly ON the path. It is the random counterpart of pathResample and splineSample, which place their samples evenly: an even sampler answers 'where do the mile markers go', this one answers 'where do the twenty trees along this road stand'. THE COUNT IS FIELD-CAPABLE AND THAT IS THE WHOLE POINT. The four source nodes (pointGrid, pointLine, pointScatterInBounds, pointScatterInWorld) take no geometry at all, so their counts are read before any domain exists to resolve a field against and can never be fields. This node takes a path, so `count` resolves on the INPUT'S OWN PRIMITIVE DOMAIN — one count per polyline — and mul(0.05, attribute("pathLength")) places one prop per twenty units on every road of a network in ONE cook, whatever their lengths. Feed that column with pathResample's `resampledLengthAttr`, or with connectPoints' `lengthAttr` per edge. THE LENGTH TO FEED IT IS `resampledLengthAttr` AND NOT `lengthAttr`, which is the same distinction the next sentence makes about the coordinate: `lengthAttr` reports the length of the CURVE that was resampled, and this node scatters on the CHORD length of the polyline it is handed, which is shorter wherever that polyline bends. Sizing a population from the first and then placing it on the second means every count is quietly for a path longer than the one the points land on — small, but it accrues entirely over bends and not at all over straights, so it is not a constant a spacing can absorb. THE ARC COORDINATE IS THE CHORD ONE: the running sum of the straight-line distances between consecutive path points, INCLUDING the closing segment when the polyline is closed, which is the same table pathResample steps, pathPointAt's 'distance' mode reads, arcTile tiles over and transferAlongPath gathers on. It is not the length of any curve fitted through those points and is shorter than one. EACH POSITION IS UNIFORM ON THE HALF-OPEN RANGE [0, length): half-open because on a CLOSED path arc 0 and arc `length` are the same place, so a closed range would make the start line twice as likely as anywhere else, and on an OPEN path the far endpoint is one position out of a continuum and no more deserving than any other. Every polyline is scattered ON ITS OWN ARC LENGTH — the polylines are never concatenated into one curve, unlike splineSample — so a long road gets no share of a short road's points. THE COUNT IS ROUNDED TO NEAREST with Math.round (which rounds a half UP, toward +Infinity: 2.5 becomes 3) and then CLAMPED AT 0, so a resolved 99.5 places 100 points and a resolved -3 places none. Rounding is DETERMINISTIC on purpose and is not a stochastic round: a caller who wants 4.3 to mean 'four points, and a fifth three times in ten' writes that themselves as floor(add(<the count field>, randomField())), which says out loud which seed decides it. A count field that resolves to NaN or +/-Infinity is REFUSED naming the param, not read as a meaning — see `count`. WHAT COMES OUT is a standard point cloud (P, rot, scale, density, boundsMin, boundsMax, color, seed) plus the f32 `arcAttr` column holding each point's own arc position, and NOTHING ELSE: no tangent, no frame, no lateral offset. writeTangents and writeCurveFrame own the frame, and transferAlongPath reads anything else the path carries at these stations — including a half-width to push a point sideways by — because a second node computing a tangent is a second node free to disagree about which way the road points. The output has NO TOPOLOGY: it is a cloud, not a path, and a random ordering of positions describes no curve to rebuild one over. Each point ALSO carries every attribute of the polyline PRIMITIVE it landed on, so a per-road `roadWidth` or `kind` survives the scatter; `primtype` is the one exception, being a type tag rather than a value, and there is no opt-out — a carried name colliding with one this node writes is refused with an error naming the attribute and the fix. DETERMINISM IS A HASH, NOT A STREAM: a point's arc position and its per-point seed are hashed from (seed, the SOURCE PRIMITIVE INDEX, its index within that polyline, a channel), never drawn from a running generator, so the same seed reproduces the same points in any cook order, at any budget, on any platform, and raising one polyline's count leaves every point on every OTHER polyline byte-identical. The key is the primitive INDEX, so reordering or filtering the polylines upstream re-rolls the scatter — the same caveat pointScatterInBounds carries about its point index, and the reason pointScatterInWorld exists for content that must be anchored to the world instead. OUTPUT ORDER is grouped by polyline in PRIMITIVE ORDER, then by index within each polyline. EVERY POLYLINE GETS ITS POINTS, including a ZERO-LENGTH one (all of its points at the same position), which places its whole count at that one position rather than being dropped: the arc range is empty, every draw resolves to 0, and the shared locate reports the only place the path has. The emitted count is therefore exactly the sum of the resolved per-polyline counts, always — no path is ever silently missing from a cook that otherwise looks fine. A primitive that is not a polyline, or has fewer than 2 vertices, is not a path and is skipped; an input with no usable polyline at all is REFUSED, naming the node that ate the topology.

**Category:** sampler

**Inputs:** `path` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-scatter-along-a-path.json](../graphs/basics-scatter-along-a-path.json), [basics-shift-along-a-path.json](../graphs/basics-shift-along-a-path.json) — 2 total (`pcg graphs --node pointScatterOnPath`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `count` | f32 | `100` | >= 0 |  | yes | How many points to place on EACH polyline. AS A FIELD IT IS ONE COUNT PER PATH, resolved on the INPUT's PRIMITIVE domain, which is what this param exists for: a wide road and a footpath in one geometry take different counts in ONE COOK, each following its own value. mul(0.05, attribute("pathLength")) is the idiom — a fixed number of props per unit of arc — where "pathLength" is whatever pathResample's `resampledLengthAttr` wrote (or connectPoints' `lengthAttr`, per edge). On a resampled path it is `resampledLengthAttr` and not `lengthAttr`: the second measures the curve that was resampled and this node scatters on the chord length of the polyline it is handed, which is shorter wherever that polyline bends. The field sees the PRIMITIVE domain, so what it can read is what a PATH carries: a primitive attribute (setAttribute with domain 'primitive', or promoteAttribute point -> primitive), index() and fraction() over the paths, randomField(), and nodeSeed(). A POINT attribute is not in scope there, and position() is not either — a path has no one position. THE RESOLVED VALUE IS ROUNDED TO NEAREST with Math.round, which rounds a half UP (toward +Infinity), and then CLAMPED AT 0: 99.5 places 100 points, 99.4 places 99, and a negative places none rather than erroring, since "fewer than none" has exactly one reading. The rounding is DETERMINISTIC and deliberately not stochastic. A caller who wants 4.3 points to mean "four, and a fifth three times in ten" writes floor(add(<the count field>, randomField())) themselves, which states out loud which seed decides it — this node inventing that draw would hide a second source of randomness inside a param that reads like arithmetic. A NON-FINITE resolved value is REFUSED, naming this param: a field is not range-checked the way a plain number is (a schema's min binds a number, and a field is a recipe with no number to check until it lands on a domain), so a division by zero or an overflow arrives here as NaN and has no reading as a population. Bound the expression itself — max(<expr>, 0), or a guard under the div. THE CAP IS ON THE TOTAL, not per path: the resolved counts are summed across every polyline and the cook is refused past 1048576 points, because a per-path cap would pass ten paths of a million each. 0 on a path places nothing on it and is not an error — a road with no trees is a road. |
| `arcAttr` | string | `"station"` |  |  |  | Name of the f32 POINT attribute (tuple 1) each emitted point's ARC POSITION is written to, in WORLD UNITS along its own polyline — the same coordinate pathPointAt's 'distance' mode reads, arcTile's `startAttr` carries, and transferAlongPath's `arcAttr` gathers at, which is what makes this the column you hand straight to that node to read the path's other attributes here. Always written; there is no empty spelling, because a scattered point whose position along the path is unrecoverable is a point nothing downstream can ask a second question about, and recovering it from P would mean measuring the path a second time. THE UNITS ARE THE TRAP, not the name: a track measured in half-widths, a route in fractions of the whole and a scan in samples are all called a station by somebody, and this column is none of those — it is metres (or whatever unit the positions are in) from the start of that polyline. Divide by the path's own length with setAttribute for a fraction. The shape is this node's to pick (f32, tuple 1), so a name already on the OUTPUT's point domain under a different shape is REFUSED rather than deleted and re-added — SEVEN of the eight columns a standard cloud starts with reach that refusal, because their shapes differ from this one: P, scale, boundsMin and boundsMax (f32x3), rot and color (f32x4), and seed (u32). "density" is the eighth and the exception — it is f32 tuple 1, exactly this column's shape, so naming it passes the shape check and is RESET rather than refused, silently overwriting a standard column with an arc length. Give it a name of its own. Must be non-empty. |
| `seed` | u32 | `0` |  |  |  | Extra seed folded into the node seed (hashCombine(nodeSeed, seed)); change it to re-roll the scatter without touching the graph seed or anything upstream. The folded value is what every per-point draw hashes from AND what a `count` field is resolved with, so a randomField() in the count re-rolls with it too — one knob for one node's randomness. Eager by the library's rule: a seed is folded in at cook start, when there is no element in hand to evaluate a field against. |

## pointsToPath

Turns a point cloud into one or more paths by building `polyline` primitives over the SAME points, so every point attribute survives — this is the only way to produce a path from a serialized graph. Ordering is fixed and deterministic: within a path the points are visited in ascending point index (the order they arrive on this node's input) unless orderAttr names a sort key, and ties in that key always break to the lower point index. With groupAttr set, the cloud splits into one path per distinct group key — a whole-number id or a string name — emitted in ascending key order. A group with too few points for the path being asked for — fewer than 2, or fewer than 3 when `closed` — is an error by default; `shortGroups "skip"` emits no primitive for it instead and leaves its points in the cloud belonging to no path, which is what makes a DATA-DEPENDENT grouping (a key computed from a scatter, a cell, a copyToPoints target index) cookable at all, since nobody can know at graph-build time how many points land in each group. It governs the WHOLE INPUT by the same rule: a cloud of fewer than 2 points is an error by default and passes straight through under "skip", because one point in one cloud is the same nothing-to-draw as one point in one group and a caller that has excused the second has already excused the first. `closed` appends a trailing vertex referencing the path's first point — closure is structural, exactly what createPolyline produces and what splineSample detects; no `closed` attribute is written. Any existing topology on the input is replaced, and its vertex and primitive attributes are dropped with it. Downstream: any node that can REMOVE points drops topology — filterByDensity, filterByBounds, filterByAttribute, filterByExpression, selfPrune, partitionByAttribute — and so do mergePoints and repeatPoints, so a path that passes through one stops being a path; put this node after them, not before. Category is not the rule: projectToPlane is categorised `filter` but preserves topology, and filterByAttribute drops it even when its predicate keeps every point.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-points-to-path.json](../graphs/basics-points-to-path.json), [basics-path-resample.json](../graphs/basics-path-resample.json), [basics-paths-by-group.json](../graphs/basics-paths-by-group.json) — 27 total (`pcg graphs --node pointsToPath`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `closed` | bool | `false` |  |  |  | Close each path by appending a trailing vertex back to its first point (structural closure — no attribute is written). A closed path needs at least 3 points; 2 would fold the path back onto itself and is an error by default (`shortGroups "skip"` drops such a path instead). This param is therefore what decides which groups count as SHORT: the same 2-point group is a perfectly good open path and an impossible closed one. |
| `groupAttr` | string | `""` |  |  |  | Name of a scalar point attribute holding a group key, splitting the cloud into one path per distinct key. A NUMERIC key must be a whole number (write one with setAttribute type 'i32', or have copyToPoints write the target index with `targetIndexAttr`) and paths are emitted in ascending key; a STRING key names the group instead — the usual thing a group is — and paths are emitted in ascending code-unit order of the word, never of its table index, so the same names produce the same paths in every geometry and every cell. Fractional numbers are refused rather than grouped: a key is an identity, two values a ULP apart would be two paths, and CPU/GPU parity is a tolerance rather than an equality. Leave empty to build a single path over every point. |
| `orderAttr` | string | `""` |  |  |  | Name of a scalar numeric point attribute to order each path by, ascending; ties break to the lower point index, so the result never depends on sort implementation. Values must be finite. Leave empty to use point index order. |
| `shortGroups` | enum | `"error"` |  | `error`, `skip` |  | What happens to a group that has too few points for the path being asked for — fewer than 2, or fewer than 3 when `closed` is true, so the SAME 2-point group is short only when it is being closed. 'error' (the default) refuses the cook and names the group, which is the right answer when the groups are AUTHORED: an id you wrote by hand belongs to a population you can predict, so a group of one is a mistake in the graph and a cook that quietly emitted one path fewer would hide it. 'skip' emits NO primitive for that group and leaves its points exactly where they are — same indices, every attribute intact, simply belonging to no path — which is the only workable answer when the groups are DATA: a key computed from a scatter, a grid cell, or a copyToPoints target index has a population nobody can know at graph-build time, so a sparse cell that drops a single point into one lane is not an authoring error and must not fail the whole cook. Nothing else moves under 'skip': the surviving groups are the same paths, over the same point indices, emitted in the same ascending-key order they would have had if the short group had never been in the input, so turning this on can only remove a path that could not be built — it can never change one that could. With `groupAttr` EMPTY the whole cloud is a single implicit group and this param still applies to it, because a group is a group however it was formed and a second rule for the unnamed one would be a trap: the only way to be short there is exactly 2 points with `closed` true, and under 'skip' such a cloud comes back with its points and no polyline instead of failing. What that case does NOT cover is a cloud of fewer than 2 points, which is refused under both settings by a different check — a node handed one point has nothing to do at all, and no grouping question was ever asked. Downstream, points belonging to no path are invisible to every path node (pathResample, splineSample, writeTangents, pathScan and pathSegments all walk primitives, not points), so a skipped group's points still filter, transfer and merge like any other points but never become a path on their own; if that is not what you want, fix the population upstream — scatter more points, widen the cell, or merge the sparse groups — rather than leaving them stranded. |

## polygonBoolean

Planar boolean of closed polylines: the UNION, INTERSECTION or DIFFERENCE of the polygons on `in` (the subject) and the polygons on `clip`, computed in a plane (`plane`, 'xz' by default). This is what turns a floor plate and its stair wells into a floor with holes, a site less its buildings into the open ground, and a pile of overlapping footprints into one outline — geometry that otherwise has to be computed in TypeScript before a graph ever sees it. Reads every CLOSED polyline (last vertex back on the first point, as pointsToPath `closed: true` and voronoiCells build them) and every 'poly' face; an OPEN polyline is refused by name. Each loop is a filled region whichever way it winds — except a loop whose `holeOf` primitive attribute is 0 or more, which is a HOLE and subtracts, so this node's own output (and an extrudePolygon-ready outline with holes from anywhere else) reads back as what it is. Overlapping loops of one set simply union; a self-intersecting loop is oriented by its net signed area and read by the nonzero rule. `clip` is optional: unconnected it is the EMPTY set, so 'union' and 'difference' dissolve `in` into its own outline and 'intersection' is empty. With `groupAttr` set, each group is its own boolean — the subject polygons of group k against the clip polygons of group k — and the key is written onto every result loop; without it, everything is one group. Primitive attributes other than the group key are NOT carried (a union of two polygons has no single source to carry from) — group by the attribute you need to keep, or use splitPolygons, which does carry. Output: closed polylines (one fresh run of points per loop, the last vertex back on the first point), each OUTER loop immediately followed by its HOLES, with an i32 primitive attribute `holeOf` — -1 on an outer, and on a hole the output primitive index of its outer — which is the convention extrudePolygon's hole support reads. Loops start at their lexicographically smallest vertex in the plane and outers are sorted the same way, so the output order depends on the geometry and never on input order. Robust by construction rather than by luck: shared vertices, collinear and overlapping edges, polygons touching along an edge or at a corner, and holes pinched against their outer are all ordinary input (see `snapDistance`). The algorithm is a planar overlay (snap, split to a fixed point, label faces by integer winding numbers, keep the boundary) and costs up to quadratic time in the edges of a group; a facade or a floor plan is a few hundred edges.

**Category:** surface

**Inputs:** `in` (geometry), `clip` (geometry, optional)

**Outputs:** `out` (geometry)

**Examples:** [basics-cut-a-courtyard.json](../graphs/basics-cut-a-courtyard.json) — 1 total (`pcg graphs --node polygonBoolean`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `operation` | enum | `"difference"` |  | `union`, `intersection`, `difference` |  | 'difference' (the default) keeps what is inside `in` and outside `clip` — a floor less its stair wells, a wall less its openings. 'intersection' keeps what is inside both — a footprint clipped to its lot. 'union' keeps what is inside either — overlapping footprints merged into one outline. Inside means winding number > 0 after every input outer loop is turned counter-clockwise and every `holeOf` hole clockwise, so overlapping loops within one set count once. |
| `plane` | enum | `"xz"` |  | `xz`, `xy`, `yz` |  | The plane the polygons are read in. 'xz' (the default) is the ground plane — the plane `extrudePolygon`'s default direction '+y' builds up from; 'xy' and 'yz' are the two walls. Input points are PROJECTED onto it (the off-plane coordinate is ignored while computing), and each result loop is written back at the off-plane coordinate of the first input point that fed it — for a floor plate at y = 3, y = 3. Outer loops come out counter-clockwise seen from the plane's positive axis (+y for 'xz', +z for 'xy', +x for 'yz'), holes clockwise. |
| `groupAttr` | string | `""` |  |  |  | Name of a scalar PRIMITIVE attribute on both pins that partitions the boolean: each group's subject polygons meet only that group's clip polygons — one floor's stair wells cut only that floor, one window's openings only that wall. Empty (the default) makes everything one group. A string key compares by its text; a numeric key must be a whole number (a key is an identity; write it as i32 with setAttribute). Both pins must carry it with the same kind (string or numeric); a group present on only one pin is still computed (its other set is empty). Every result loop carries the key, in a column of the `in` pin's type, and groups come out in the order their key first appears on `in`, then on `clip`. |
| `snapDistance` | f32 | `0.0001` |  |  |  | The documented epsilon, in world units: two vertices closer than this are ONE vertex, and a vertex closer than this to an edge splits that edge — so corners that should coincide but differ by f32 rounding weld, a vertex lying on another polygon's edge is treated as ON it, and collinear or shared edges merge. Features smaller than this are not preserved: a result loop whose area is at most snapDistance squared is dropped as degenerate, and a vertex within snapDistance / 1000 of the straight line through its neighbours is removed. The default 0.0001 is a tenth of a millimetre at metre scale, a few f32 steps at a kilometre from the origin. Must be greater than 0. |

## projectToPlane

Projects every point orthogonally onto the plane through `origin` with normal `normal` (normalized internally). As plain vectors they describe ONE plane and the normal must be non-zero; as fields they are read per point, so each point falls onto the plane IT was given and a zero normal there is not a plane at all — that point is left exactly where it stands. With keepOffset enabled, the signed distance each point moved (positive along the normal) is stored in a `planeOffset` point attribute (f32, tuple 1) before projecting, so the flattening is invertible. This node is categorised as a filter but removes nothing: the point count, the attributes and the topology all come out as they went in.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-flatten-and-remember.json](../graphs/basics-flatten-and-remember.json) — 1 total (`pcg graphs --node projectToPlane`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `origin` | vec3 | `[0,0,0]` |  |  | yes | A point on the plane, in world units. As a FIELD it is a PER-POINT origin, evaluated on the input's points, so each point is projected onto a plane sliding with it — with a constant normal that is a per-point OFFSET along that normal, which is how a stepped or terraced flattening is written (floor the height, feed it back as the origin) rather than one flat sheet. Build it with vec(x, y, z); a scalar field broadcasts to all three axes. Only the component along the normal can matter, since the projection subtracts (P - origin) . n: two origins differing by anything perpendicular to the normal name the same plane and move nothing. Non-finite values are REFUSED rather than read, naming this param — a plane through NaN has no meaning, and the resulting positions would draw nothing downstream. |
| `normal` | vec3 | `[0,1,0]` |  |  | yes | Plane normal; any non-zero vector (normalized internally). As a FIELD it is a PER-POINT normal, evaluated on the input's points, so each point is projected along the direction IT carries — attribute("N") flattens every point onto its own surface plane, and a varying normal collapses a cloud onto a fan of planes rather than one. A ZERO-LENGTH NORMAL IS THE ONE REFUSAL THAT CHANGES SHAPE HERE, and it changes only for a field: a plain zero vector is still refused outright, because one plane that does not exist is an authoring mistake with nothing to salvage, while a field's zero is a per-point answer — that point has no plane, so it is left exactly where it stands and its planeOffset is 0 (it moved nothing). Nothing is invented for it and nothing is dropped; a point that did not move is visible as an offset of 0. Scale is free either way, since the vector is normalized before use, and a scalar field broadcasts to all three axes — note that vec(1,1,1) is a diagonal plane, not an axis one. Non-finite components are REFUSED rather than read, naming this param: a NaN normal would normalize to NaN and send every coordinate of that point to NaN. |
| `keepOffset` | bool | `false` |  |  |  | When true, store each point's signed pre-projection distance to the plane in a `planeOffset` point attribute (f32). |

## promoteAttribute

Moves an attribute between domains using the geometry's topology, creating or overwriting it on the target domain. Modes: 'first' keeps the first contribution in scan order (the only mode valid for string attributes); 'average', 'sum', 'min', 'max' aggregate all contributions. 'detail' broadcasts (from) or reduces over everything (to). Elements with no contributors keep the attribute default.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-promote-attribute.json](../graphs/basics-promote-attribute.json), [basics-runs-along-a-path.json](../graphs/basics-runs-along-a-path.json), [basics-density-along-a-path.json](../graphs/basics-density-along-a-path.json) — 7 total (`pcg graphs --node promoteAttribute`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"density"` |  |  |  | Name of the attribute to promote. Must exist on the `from` domain. |
| `from` | enum | `"point"` |  | `point`, `vertex`, `primitive`, `detail` |  | Domain the attribute currently lives on. |
| `to` | enum | `"primitive"` |  | `point`, `vertex`, `primitive`, `detail` |  | Domain to create the attribute on. |
| `mode` | enum | `"average"` |  | `first`, `average`, `sum`, `min`, `max` |  | How multiple contributions collapse: first (scan order), average, sum, min, or max. String attributes support only 'first'. |

## quotaRebalance

Reads a CATEGORY per point and a stated SHARE BAND per category, and writes down the minimum set of points that must change category for every share to land inside its band — which category each should join, and nothing else. This is the node for 'these six kinds, in these proportions', where the proportions are a REQUIREMENT rather than a hope: drawing each element from a weighted table gives the mix in expectation, and any particular population still misses, which is exactly what a stated proportion exists to rule out. `min` and `max` are two lists of the same length, one entry per category, in shares of the counted population (0.1 is a tenth); the list length IS the number of categories, so there is no second param to disagree with them. IT MOVES TO THE NEAREST EDGE AND STOPS, never to the middle of a band, and that is the whole of its restraint: a category a tenth below its floor is lifted to its floor and left there. Driving every category to the centre of its range would make a generated population markedly more uniform than a real one — populations reach a stated aggregate through variation between them, not by every one of them hitting the same number, so a generator that lands on the middle every time scores better against the rule and is worse. IT DECIDES AND DOES NOT ACT. Nothing here knows what an element of a different category looks like: whatever turns a 'mid' into an 'over' is a redraw only the caller can perform. So the output is a per-point DESTINATION, and a setAttribute, copyToPoints or transferByIndex downstream does the changing — usually inside a repeatUntil, so that a redraw which lands in the wrong category is simply seen again on the next round. WHICH ELEMENTS GO is `priority` ascending: the lowest-priority eligible member of an over-full category leaves first. That param is the one worth thinking about, because the obvious choice is usually wrong — priority by a POSITION coordinate takes the first members along that axis and concentrates every change in one stretch, which reads as a patch of different-looking work rather than as a mix. A hash (randomField) spreads them; a measure of how badly each element fits where it is concentrates them where they were least right. `include` and `eligible` are two different exclusions and both are needed: an element with `include` off is not counted in any share and cannot move (it is not part of the scheme being stated), while an element with `eligible` off still COUNTS toward its category's share but is never chosen to leave (it is part of the population and is pinned where it is — a landmark, a reserved marker, anything a stronger rule already placed). DETERMINISM: ties in `priority` are broken by point IDENTITY — the bits of the stored position plus the per-point `seed` attribute — never by array index, so shuffling the input or filtering something upstream yields the identical decision. HALO: none, and unlike the rest of the library that is not a number but an absence. A share is a fact about the WHOLE population, so this node has no partitioned form at all: cooked over half the points it reads half the denominator and decides a different set. It belongs on an unbounded level, or before a split. OUTPUT is the input geometry with one i32 point attribute added, `targetAttr`: the category index each moving point should join, and -1 on every point that stays — including every point `include` switched off, whose category is therefore never even read. No point is added, removed or moved, and topology survives untouched. A SHARE IS A RATIO OF WHOLE POINTS, and that is checked rather than hoped for. A category can only hold ceil(min*n) to floor(max*n) of n counted points, so bands that are legal as real numbers can still be unreachable by this particular population: five points against a band of [0.04, 0.12] need at least 1 and allow at most 0, and two categories banded [0, 0.1] and [0, 0.9] over 13 points admit no arrangement at all, since 1/13 is under the first ceiling and 12/13 is over the second. Measured over 312,581 band lists that pass the two SUM checks, better than one in five are unreachable this way, and every one of them used to drive this node into a ping-pong that spent its whole budget and emitted moves a caller would have redrawn assets for. WHEN THE BANDS ARE UNREACHABLE NO MOVE IS MADE — no arrangement is right, so none is chosen, and a best effort would be a different node, since 'minimum change' has no meaning once the target cannot be hit. That is reported and not thrown, and the distinction is deliberate: a band list no population could satisfy is an authoring error and the two SUM checks refuse it outright, while a band list this population cannot satisfy is DATA — a cell holding five points, a lap a cull has thinned — and a node that throws on data cannot sit inside the repair loop it exists for. IT CAN ALSO STOP EARLY for a second reason: a category whose members are all ineligible has nothing to give up. `unmetAttr` is how a caller hears about either. COST is one pass over the points per move, and on a reachable set of bands every point that moves moves exactly once — so the pass count IS the move count, the move count is the minimum, and a mix put right by moving a tenth of the population costs a tenth of the passes.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-quota-rebalance.json](../graphs/basics-quota-rebalance.json) — 1 total (`pcg graphs --node quotaRebalance`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `category` | f32 | `0` |  |  | yes | Which category each point is IN, as an index into `min`/`max`: 0 for the first entry, 1 for the second, and so on. Read as floor(value), and a point whose index lands outside [0, min.length) is refused naming the point — not clamped, because a category the author did not list is a scheme the author did not state, and folding it into the first or last one would balance a mix nobody asked for. Field-capable and evaluated on the point domain, which is the usual way it arrives: a band decided from a position and a size is an expression, not a column somebody wrote. Only read for points `include` leaves in, so an element outside the scheme needs no category at all. Resolved against the INPUT geometry INCLUDING the column `targetAttr` names, which this node does not reset until all four of its field-capable params have resolved — so a category derived from the previous round's destination reads that round. |
| `min` | numberList | `[]` |  |  |  | The FLOOR of each category's share, in order, as a fraction of the counted population: [0.1, 0.04, 0.23] says the first category must hold at least a tenth. Each entry is in [0, 1] and must not exceed the matching `max`. THE LIST'S LENGTH IS THE NUMBER OF CATEGORIES, and `max` must be the same length — a count param beside them would be a third thing to keep in agreement. A floor of 0 is a category with no lower requirement, which is how 'this kind may be absent' is written. The floors are refused if they sum above 1: no population can satisfy them, and finding that out as a cook that never settles is the failure this check exists to replace. |
| `max` | numberList | `[]` |  |  |  | The CEILING of each category's share, in order, on the same scale as `min` and with the same length. A ceiling of 1 is a category with no upper limit. The ceilings are refused if they sum below 1, for the mirror of `min`'s reason: the population has to go somewhere, so ceilings that leave less than the whole of it unallocated cannot all hold at once. A share landing EXACTLY on a floor or a ceiling is INSIDE the band — the comparisons are strict, so a category at exactly its ceiling is not over it, and a caller checking the same thing afterwards should use the same strictness or a slack coarser than the arithmetic (a share is a ratio of whole counts, so landing exactly on a two-decimal bound is the ordinary case rather than a coincidence). |
| `include` | f32 | `1` |  |  | yes | Nonzero (the default) puts the point IN the scheme: it is counted in its category's share and it may be chosen to move. Zero takes it out of both — not counted in any share, never moved, and its `category` never even read, so an element outside the scheme needs no category to be given one. This is the exclusion for elements that are STRUCTURE rather than population: a tunnel's ribs are all one category by geometry and a lap can carry forty of them, which would take that category from a tenth of the population to a quarter and make the stated mix unreachable on any track that has a tunnel. Compare `eligible`, which is the other exclusion and does the opposite thing to the denominator. Resolved on the same terms as the other three field-capable params: against the input, `targetAttr`'s column included, before this cook writes anything — so an exclusion decided by what the previous round did reads that round and not a column of -1. |
| `eligible` | f32 | `1` |  |  | yes | Nonzero (the default) allows this point to be chosen to LEAVE its category. Zero pins it: it still counts toward its category's share — it is part of the population — but is never selected to move. This is the exclusion for elements a STRONGER RULE already placed, and the distinction from `include` is the whole reason there are two params. Switching `include` off would hide the element from the shares as well, so the mix would be balanced against a population that is not the one on screen; switching `eligible` off leaves the arithmetic honest and takes only the element off the table. A category whose members are all ineligible simply cannot give any up, and the rebalance stops when it runs out of donors rather than looping. IT MAY READ THE PREVIOUS ROUND'S DESTINATIONS, and that is the sharpest thing to put here inside the repeatUntil this node is written for: `lt(attribute("quotaTarget"), 0)` pins whatever the last round already redrew, so the changes spread over the population instead of falling on the same elements twice. The column `targetAttr` names is resolved against BEFORE it is reset, so a field here sees the round before and never the -1s this cook is about to write. ROUND ONE HAS TO SEED IT: attribute() refuses a column that is not there, naming it, rather than resolving to a silent -1, so a loop whose first pass reads the destination writes it once upstream (a setAttribute of -1) instead of relying on this node to have been round zero. |
| `priority` | f32 | `0` |  |  | yes | Which members of an over-full category leave FIRST: lowest value first, ties broken by point identity. The default of 0 makes every point tie, so the whole decision falls to identity — a stable, position-derived order that is the right answer when the choice genuinely does not matter. IT USUALLY DOES MATTER, and in a way that is invisible in the counts: priority by a position or arc coordinate takes the first k members along that axis, and since a category's members are spread over the whole population, 'the first k' is a CONTIGUOUS PATCH. Every change then lands in one stretch and the result reads as a repair rather than a mix, while every share is exactly right. randomField spreads them instead; a measure of how poorly each element suits its current category concentrates the changes where they were least deserved, which is usually what 'minimum change' was meant to mean. THE PREVIOUS ROUND is available to it on the same guarantee the other three field-capable params get — the column `targetAttr` names is resolved against before it is reset — so sending whatever moved last time to the back of the queue is an expression over attribute("quotaTarget"), not a second column the caller has to carry. |
| `unmetAttr` | string | `""` |  |  |  | Optional DETAIL attribute (u32) receiving how many categories are still outside their band when this node stops — 0 when every band was met. Empty (the default) writes nothing. IT EXISTS BECAUSE STOPPING EARLY IS LEGAL AND SILENT. A category whose members are all `eligible`-off cannot give any up, so the rebalance runs out of donors and returns; the geometry it returns looks exactly like the geometry it would have returned on success, and a caller looping until nothing moves would spin on the difference. Name a column here and that caller can tell 'the mix is right' from 'the mix is still wrong and I stopped trying'. It is a count of CATEGORIES rather than of points because that is the question the bands ask; the number of points that moved is already readable as how many of `targetAttr` are >= 0. Same family as transferByIndex's and transferAttribute's `missCountAttr`, and written on the detail domain for their reason: it is one fact about the whole geometry, not one per element. |
| `targetAttr` | string | `"quotaTarget"` |  |  |  | POINT attribute (i32) receiving the category each point should JOIN: an index into `min`/`max` for a point that must move, and -1 for every point that stays where it is, including every point `include` switched off. So the test for 'did this point move' is `>= 0` and needs no comparison against the category column — which matters, because a point outside the scheme has no category this node ever read. May not be empty: a quotaRebalance that writes nothing is a cook that looks like it worked. Same reporting-slot rule as the rest of the library — an existing column of a different shape under this name is refused rather than silently deleted and re-added, and a same-shape one is reset. THE COLUMN THIS NAMES IS ALSO AN INPUT, which matters exactly where this node is meant to sit. It is an ordinary point attribute, so the geometry handed in may already carry one, and inside a repeatUntil that one IS the previous round's decision. All four field-capable params — `category`, `include`, `eligible`, `priority` — are resolved against it BEFORE it is reset, so a field naming it reads the round that came before and never the -1s this cook is about to write. On the FIRST round no such column exists yet and a field naming it is REFUSED by name — see `eligible`, which is where that idiom is written down. The reset is still total: whatever the round before left is gone from the OUTPUT, which carries this cook's decision alone. |

## removeAttribute

Deletes named attributes from one domain. Every idiom that carries a value between nodes — a scratch column feeding a filter, a parameter attribute read back by a field, a hit marker recovered from a transfer — leaves that column on the output forever; this is the only way to take it off again. Unknown names are an error by default, so a typo does not silently leave the debris it was meant to remove; set strict false when a name may legitimately be absent. Removing the point attribute "P" is refused: it is the position every downstream node reads, and dropping it turns a clear failure here into an obscure one later.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-report-to-the-host.json](../graphs/basics-report-to-the-host.json) — 1 total (`pcg graphs --node removeAttribute`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `names` | stringList | `[]` |  |  |  | Attribute names to delete, in any order. An empty list removes nothing (and is not an error, so a graph can leave the node in place with nothing to clean). |
| `domain` | enum | `"point"` |  | `point`, `vertex`, `primitive`, `detail` |  | Domain to delete from: point, vertex, primitive, or detail. |
| `strict` | bool | `true` |  |  |  | Error when a listed name does not exist on the domain, naming the available attributes. False makes removal best-effort and skips missing names. |

## repeatPoints

Emits every input point `count` times — a PER-POINT number of times when `count` is a field — and numbers the copies 0, 1, ..., count - 1 in `indexAttr`. This is the fan-out a split grammar, a stack of storeys or a row of bays needs: a cell that becomes N children, a wall that becomes N courses, a bay that becomes N panes, where N is the point's own value. OUTPUT ORDER IS POINT-MAJOR: all the copies of input point 0 (copy 0 first), then all the copies of point 1, and so on, so copy k of a point sits next to copy k + 1 and the input order is kept between points. EVERY POINT ATTRIBUTE IS CARRIED onto every copy — the standard columns and every custom one, of every type, strings included (re-interned, so each copy says the word its point said) — with no carry list to keep, and the DETAIL attributes come through unchanged. The copies are COINCIDENT: nothing is moved, so a copy is placed by what reads the index downstream (a transformPoints or setAttribute whose field reads `attribute("copy")`), not by this node. EACH COPY GETS ITS OWN SEED, and that is not optional, because a point's identity is its position bits plus its `seed` and coincident copies with one seed would be ONE point to every identity-keyed decision (jitter, random fields, selfPrune ties): copy k of a point carrying seed s gets seed hashCombine(s, k) — the source point's own seed and the copy index, never the output slot, in the spirit of copyToPoints' hashCombine(sourceSeed, targetSeed). COPY 0 IS RE-SEEDED TOO, deliberately: if copy 0 kept s, then repeating twice in a row would give copy (0 of copy 1) and copy (1 of copy 0) the same seed hashCombine(s, 1) at the same position — two different copies merged into one point. Hashing every copy makes chained repeats distinct; the cost is that count 1 is not a byte-identical pass-through (the seeds change, the index column is added, and topology is dropped). A cloud with no `seed` column contributes 0, exactly as point identity reads it (copyToPoints falls back to the point INDEX there instead, which would tie the copies' seeds to the slot), so copies of different seedless points still differ by position. COUNT 0 DROPS THE POINT, and a point dropped here leaves no trace — which is how a fan-out wider for some points than others costs only what is kept. TOPOLOGY IS DROPPED: the output is a point cloud, and the input's vertices, primitives and their attributes are gone — what the point filters do by default and what mergePoints does. To repeat a path or a mesh as a SHAPE — every primitive once per copy — use copyToPoints with `topology "keep"`, which re-emits the source's primitives onto each target. CPU only: `count` is a comparison-like decision (it is rounded to a whole number) and the GPU's published tolerance cannot bound which side of a .5 a value lands on.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-repeat-points.json](../graphs/basics-repeat-points.json) — 1 total (`pcg graphs --node repeatPoints`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `count` | f32 | `2` | >= 0 |  | yes | How many times to emit each point. AS A FIELD IT IS ONE COUNT PER INPUT POINT, resolved on the input's point domain, so it reads what the point carries: attribute("storeys") stacks each block its own number of storeys, floor(div(attribute("length"), 1.2)) gives each wall as many bays as fit, and randomField() varies it per point. THE RESOLVED VALUE IS ROUNDED TO NEAREST with Math.round, which rounds a half UP (toward +Infinity), and then CLAMPED AT 0 — the rule pointScatterOnPath's `count` states, so a count field means the same thing on both nodes: 2.5 emits 3 copies, 2.4 emits 2, and a negative emits none rather than erroring, since "fewer than none" has exactly one reading. To get a FLOOR (as many whole copies as fit), say so: floor(<expr>). COUNT 0 DROPS THE POINT. A NON-FINITE resolved value is REFUSED, naming this param and the point: a field is not range-checked the way a plain number is, so a division by zero arrives here as NaN and has no reading as a population — bound the expression, e.g. max(<expr>, 0) or a guard under the div. THE CAP IS ON THE TOTAL: the rounded counts are summed over every input point and the cook is refused past 4194304 output points, naming the point the total ran out on — bound the expression with min(<expr>, <the most copies you meant>). |
| `indexAttr` | string | `"copy"` |  |  |  | Name of the i32 POINT attribute (tuple 1) receiving each copy's index within its own point's copies: 0 for the first copy of every point, up to count - 1. This is the number a downstream field places the copies by — add(attribute("lo"), mul(attribute("copy"), 3)) stacks them 3 apart — and the one copyToPoints' rule-cloud pattern used to recover from a `slot` attribute. The column's default is -1, the value no copy gets, so an element appended later reads as no copy at all. It is a REPORTING SLOT: an input point attribute of the same shape (i32, tuple 1) under this name is overwritten, which is what re-running the node over its own output does — so give a SECOND repeatPoints in a chain a different name, or the outer copy index replaces the inner one — and one of any other shape is refused rather than destroyed. The standard point attributes ("P", "seed", "color" and the rest) are refused by name whatever the input holds. Empty writes no index column. |
| `countAttr` | string | `""` |  |  |  | OPT-IN: name of an i32 POINT attribute (tuple 1) receiving, on every copy, how many copies its point was emitted — the rounded, clamped count, so a copy can ask where it stands in its run (sub(attribute("n"), attribute("copy")) counts down to 1 on the last copy; div(attribute("copy"), attribute("n")) is a 0-based fraction). Empty (the default) writes none. A reporting slot under the same rule as `indexAttr`: a same-shape input column is overwritten, any other shape refused, and a standard point attribute refused by name. Naming the same attribute as `indexAttr` is refused — the two are different numbers and one would silently overwrite the other. |

## repeatUntil

Composite node that cooks an inner graph REPEATEDLY, feeding each round's output back into its own input until the body stops changing anything — a bounded fixed point, in a graph where a cycle cannot be wired. Exactly one exposed input AND exactly one exposed output must be named "carry": round 1 gets the outer "carry" input, round k+1 gets round k's "carry" output, and every other exposed input is broadcast whole to every round. This is the loop that relaxation needs and that "forEach" cannot express, because the number of rounds is not known before the first one runs: push overlapping props apart and a new pair now overlaps; snap a dangling edge and the snap creates another dangler. TERMINATION is a scalar the body publishes on the DETAIL domain of the carried geometry, named by "settleAttr" — attributeReduce is what normally writes it. All zero means settled: the loop stops and that round counts. Absent is REFUSED by name rather than read as zero, because reading it as zero turns a typo into "converged on round one". Two synthetic outputs the body never declared report what happened: "rounds" (how many cooks) and "converged" (did the settle signal reach zero, or did it hit maxRounds), both value items. THE SEED IS NOT ROTATED PER ROUND, and that is the design: a fixed point exists only if the body is the SAME function every round, so a body whose seed varies with the round number is a different function each time and has no fixed point to converge to — it re-rolls whatever the last round settled, runs the full budget every time, and reports converged false forever, with no error to say why. Pass a constant seed and let the DATA change between rounds. The payoff is the mirror of forEach's cost: a constant inner seed means inner nodes whose inputs did not change between rounds serve their caches, so a broadcast branch is computed once for the whole loop. Pins are per-instance exactly as for "subgraph" and the serialized form is the same payload plus this node's own two params: create instances with repeatUntilNode(innerGraph, exposedInputs, exposedOutputs, exposedParams), or deserialize a graph containing one.

**Category:** composite

**Meters the cook budget itself:** under `cook(graph, { budgetMs })` this node yields to the event loop inside its own execute, so its `NodeDoneInfo.elapsedMs` is wall time spanning those yields — not an uninterrupted block. Derive a longest-block figure from a cook with the budget unset.

**Inputs:** *(none)*

**Outputs:** *(none)*

**Examples:** [basics-repeat-until-settled.json](../graphs/basics-repeat-until-settled.json), [examples-coral.json](../graphs/examples-coral.json), [examples-tree.json](../graphs/examples-tree.json) — 3 total (`pcg graphs --node repeatUntil`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `maxRounds` | u32 | `12` | 1..1024 |  |  | Hard ceiling on how many times the body cooks. Reaching it WITHOUT the settle signal going to zero is not an error and is not silent: the loop stops, "rounds" reports this number and "converged" reports false, so a host or a downstream branch can tell a settled result from a truncated one. This is a budget, not a target — a body with a fixed point normally reaches it in a handful of rounds, and a body that reliably needs the whole ceiling is telling you it has no fixed point (the usual cause being a seed that varies per round, which this node deliberately does not do; see the node description). Raising it is the wrong first response to a false `converged`: find out whether the body is converging slowly or not at all, because those need opposite fixes. Minimum 1 — one round means cook the body exactly once and report whether that one round settled, which is a legitimate way to ASK the question without paying for the loop. |
| `settleAttr` | string | `"moves"` |  |  |  | Name of the DETAIL-domain attribute the body writes to say whether anything still changed. Read after every round from every geometry item on the carry output: all zero means settled (stop, and that round counts), anything else means loop. The detail domain is used because it is the one domain that holds exactly one value per geometry, and because a subgraph wrapper has no non-geometry output pin a scalar could ride out on — attributeReduce is what normally writes it (mode 'count' over a filtered cloud, or 'sum' of a per-point moved flag). The attribute MUST exist on the carry geometry every round: an absent one is refused by name rather than treated as zero, because treating it as zero turns a typo here, or a body that never wired the reduction, into 'converged on round one' — a wrong answer that cooks cleanly and saves cleanly. A tuple attribute settles only when every component is zero, and NaN never settles (so unmeasurable data runs the budget out and reports converged false, instead of stopping on garbage). |

## runFit

Cuts every polyline into RUNS at along-arc GAPS, least-squares fits a numeric point attribute against arc position WITHIN each run, and writes the fit back onto every point of the run it belongs to. This is the node that turns 'those things line up' into numbers a filter can act on: a slope (how fast the value drifts per unit of arc), a worst-case residual (how far the furthest member sits off the fitted line) and a span (how much arc the run covers). Detection is the first use and CONSTRUCTION is the second — a run detected here has a start and a span, which are exactly what arcTile lays a repeated piece over, and the default names line up on purpose (`runStart`, `runSpan`). WHY A NODE AND NOT A FIELD: a gap is a fact about two points at once, and a field resolves each element from that element alone, so neither the grouping nor the fit has any formulation in the grammar. pathRuns cuts runs too, but at points something already FLAGGED — and nothing flags a barrier: what separates one row of posts from the next is empty arc, which is the thing no upstream column knows. IT FITS AGAINST RUN-LOCAL ARC, NOT THE PATH'S, and that is a numerical decision worth stating because it is invisible when it goes wrong. A least-squares fit only ever uses `s - mean(s)`, so fitting an O(1) quantity against an O(300) lap coordinate subtracts away every leading digit it was written with: in f64 that costs about four of seventeen digits and nobody notices, but in f32 there are seven digits and the spacing at 300 is ~3e-5, so a 40-unit run keeps about two digits of deviation — against divergence thresholds that live in the third. The detector would be reading its own quantisation. Subtracting the run's own start first is THE SAME LINE THROUGH THE SAME POINTS (a fit is translation-invariant in the abscissa; slope and residual are unchanged) computed where the numbers are small, so the fit is exactly translation-invariant here rather than approximately. It is also what makes the degenerate-run guard a plain `den > 0` rather than an epsilon: at lap arc those squared deviations were pure cancellation of the same order as any epsilon anyone would pick. THE FIT LANDS ON THE POINT DOMAIN, REPEATED ACROSS EACH RUN, and the alternative was considered and refused. A run is NOT a primitive — one path holds many runs, so the primitive domain has no element to hold one — and giving each run a primitive would mean re-topologising the path into fragments, which destroys the path to describe it. Repeated per point is also the shape the answer is USED in: every consumer is a per-point decision ('drop the middle member of every straight run longer than 4 units', filterByExpression), and a per-point decision needs the run's verdict AT the point. THE RESIDUAL IS THE WORST MEMBER, not an RMS: the rule these exist to serve is 'no member sits further than X off the line', and an RMS lets one outlier hide behind five good members, which is precisely the case that reads as a line to a human eye and passes as scatter to a mean. THE SEAM IS NOT A BREAK unless a gap makes it one. On a CLOSED path with `wrap` on, the walk starts at the first REAL break rather than at vertex zero, so a run straddling the start/finish line stays one run — the same rotation, the same fallback and the same reasoning as pathRuns, because a lap is the case this keeps meeting and one node disagreeing about where a lap begins is a bug nobody sees. A closed path with wrap on and NO gap anywhere is one cyclic run with nowhere to begin, so the seam stands in and the result is what `wrap` off gives. On an OPEN path `wrap` does nothing. TWO-POINT RUNS FIT EXACTLY AND REPORT A ZERO RESIDUAL (or the rounding noise left of one, ~1e-16 of the values' own size), which is the mistake this node most wants you to avoid: a line through two points is always perfect, so 'straight' is only evidence above three, and `countAttr` exists to be filtered on. Compare residuals against a threshold rather than against zero for the same reason every float is. NaN VALUES ARE EXCLUDED FROM THE FIT but stay members of their run (they hold their place along the arc; dropping them would join the two runs they separate), so `countAttr` reports what the line was actually fitted to. A NaN or infinite ARC is refused outright, naming the point — a point with no place along the path cannot be assigned to a run at all, and silently dropping it would merge its neighbours. Points in no polyline keep the defaults (-1 for the id and index, 0 elsewhere), and a point in several polylines takes the last in primitive order, both matching pathScan and pathRuns. TOPOLOGY SURVIVES: this node removes no points, so a path arrives a path and leaves a path — unlike anything downstream that can drop a point (filterByDensity, filterByBounds, filterByAttribute, filterByExpression, selfPrune, partitionByAttribute, mergePoints), which rebuilds the point domain and takes the primitives with it. It emits no points either, so it needs no ceiling: the output is exactly as big as the input.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-fit-runs.json](../graphs/basics-fit-runs.json) — 1 total (`pcg graphs --node runFit`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `arcAttr` | string | `""` |  |  |  | POINT attribute (tuple 1, numeric) holding each point's ALONG-ARC coordinate — the axis runs are cut on and the fit is made against. EMPTY (the default) MEASURES IT: the path's own cumulative arc length, in world units, walked from its first vertex. Name a column instead when the coordinate is not the path's own geometry, which is the usual case for detection: props threaded into a path in station order are separated along the ROAD, and the 3D chord between two of them also carries their lateral offsets, so a row alternating between two sides measures gaps longer than the road ever had and a run is cut where there is no gap. The coordinate must not DECREASE along the walk — this node refuses a decrease rather than reading it as a huge gap, because a path walked against its own coordinate produces a fit through a sequence running backwards and every number it reports is then a plausible-looking lie. Equal values are fine (two props at the same station). NaN and ±Infinity are refused, naming the point. |
| `valueAttr` | string | `"density"` |  |  |  | POINT attribute (tuple 1, numeric) that is FITTED against the arc coordinate — the quantity whose drift the slope reports. Must exist. THE SIGN IS YOURS TO DECIDE, and it decides what the detector can see: a lateral offset fitted signed gives the two sides of a road opposite slopes for the same defect and halves the sensitivity of any threshold written for one of them, so fit the ABSOLUTE offset (setAttribute with an abs() field) when 'drifting away from the centre' is the question. A NaN value is EXCLUDED from the fit rather than poisoning it, and stays a member of its run — it still holds its place along the arc, and dropping it would merge the runs on either side of it. `countAttr` reports how many members survived into the fit, which is the number to filter on. |
| `gap` | f32 | `1` | >= 0 |  | yes | The along-arc distance that SEPARATES runs, in the units of the arc coordinate: consecutive members closer than this belong to the same run, and a gap GREATER THAN OR EQUAL to it starts a new one. Must be > 0. The comparison is closed on the break side deliberately — 'members closer than `gap` belong together' is the sentence the number is chosen from, so an exactly-`gap` spacing is a break rather than a coincidence to argue about. AS A FIELD IT IS ONE GAP PER PATH, resolved on the input's PRIMITIVE domain, for the same reason pathResample's spacing is: each polyline is cut on its OWN arc, so there is a primitive element to read one value per, and a motorway and a footpath in one geometry can take different gaps in ONE cook. The field sees the primitive domain, so it can read a primitive attribute (setAttribute domain 'primitive', or promoteAttribute point → primitive), index(), fraction(), randomField() and nodeSeed(); a POINT attribute is not in scope there and position() has no meaning for a path. A field is not range-checked the way a plain value is — a schema's min binds a number, and a field is a recipe with no number until it lands on a domain — so bound the expression itself with max(<expr>, <the smallest gap you meant>); a NaN or infinite gap is refused, naming this param. |
| `period` | f32 | `0` | >= 0 |  | yes | The value the arc coordinate WRAPS AT on a closed path — the lap length, in the arc coordinate's own units. 0 (the default) means the path's OWN MEASURED ARC LENGTH, which is correct whenever `arcAttr` is empty or holds a measured world-unit arc. IT IS READ ONLY WHERE IT MATTERS: a closed path with `wrap` on, where the gap across the seam is `arc(first) + period - arc(last)` and nothing else can supply it. THE MISTAKE IT EXISTS TO PREVENT: `arcAttr: "curveU"` is a 0..1 coordinate, so its period is 1, and leaving this at 0 hands it a period of a few hundred world units — the seam gap then dwarfs every real gap, no break is ever found there, and the lap silently becomes one run. A period SMALLER than the coordinate's own extent is caught (the seam gap goes negative and the cook is refused naming this param). A period LARGER than it cannot be caught by arithmetic — which is why the combination that produces one is REFUSED instead: a wrapping closed path that reads a non-empty `arcAttr` must state its period, because 0 would hand it a world-unit length for a coordinate that is not in world units, and the run crossing the seam would split with nothing in the output to show it. Clear `arcAttr` to use the measured arc, or set `wrap` false, or say what the coordinate wraps at. One value per PATH as a field, resolved on the PRIMITIVE domain exactly as `gap` is. |
| `wrap` | bool | `true` |  |  |  | Whether a run may cross a CLOSED path's seam. True (the default) rotates the walk onto the first REAL break — the first point whose gap-before is at least `gap`, measured the long way round through the seam — so a run straddling the start/finish line stays one run. This is pathRuns' rule and the same code shape, because a lap is the case that keeps arriving and a line of eight objects laid across the start line must not read as two lines of four, each too short to be anything. False treats the seam as a break, which is what you want when vertex order carries meaning of its own. A closed path with NO break anywhere is one cyclic run with no place to begin, so the seam stands in and the answer is identical under both settings. No effect on an open path. |
| `slopeAttr` | string | `"runSlope"` |  |  |  | POINT attribute (f32) receiving the fitted SLOPE of the run each point belongs to: the change in `valueAttr` per unit of arc, signed, and the same number on every member of a run. This is the divergence figure — 'this line drifts 0.03 units of lateral per unit of lap' — and it is what separates a line running PARALLEL to the path (slope ~0, ordinary dressing) from one converging on it (a false edge a driver would steer to). A run whose members all sit at one arc position has no slope to fit and reports 0, as does a run with fewer than two fittable members. May not be empty: a runFit that writes no fit is a cook that looks like it worked. Same reporting-slot rule as the rest of the library — a column of a different shape under this name is refused rather than deleted and re-added, and a same-shape one is reset. |
| `residualAttr` | string | `"runResidual"` |  |  |  | POINT attribute (f32) receiving the run's WORST residual: the largest absolute distance from any fitted member to the fitted line, in the units of `valueAttr`, repeated on every member. Worst rather than RMS on purpose — the rule this serves is 'no member sits further than X off the line', and an RMS lets one outlier hide behind five good members, which is exactly the arrangement that reads as a straight line to the eye and as scatter to a mean. THE NUMBER TO DISTRUST IS A ZERO ON A SHORT RUN: two points define a line, so a two-member run always reports 0 — or the rounding noise left of it, which is why a threshold and not an equality is what to test — and always looks perfectly assembled. Filter on `countAttr` before believing a residual. May not be empty, and the reporting-slot rule applies. |
| `spanAttr` | string | `"runSpan"` |  |  |  | POINT attribute (f32) receiving the run's SPAN: the arc distance from its first member to its last, in the arc coordinate's units, repeated on every member. Zero for a single-member run. This is the length threshold every rule about runs eventually needs — a line has to be long enough to read as one — and, with `startAttr`, it is exactly the range arcTile tiles: the pair's default names (`runStart`, `runSpan`) are that node's default `startAttr` and `lengthAttr` so the two wire together without renaming. Note it is the span of the MEMBERS, not of the arc they were cut from: a run ends at its last member, not half a gap later. May not be empty, and the reporting-slot rule applies. |
| `idAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (i32) receiving a run's INDEX, numbered from 0 across the whole geometry in primitive order and then in walk order, with -1 left on every point no polyline reaches. Empty (the default) writes none and the output is byte-identical to a cook without it. It is the GROUP KEY the rest of the library takes: partitionByAttribute splits one item per run, pointsToPath's `groupAttr` builds one path per run, and attributeReduce collapses per run. Numbered across the geometry rather than per path so those nodes see distinct groups without having to combine two columns; the path a run came from is recoverable from any carried primitive attribute. |
| `indexAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (i32) receiving each point's 0-BASED POSITION WITHIN ITS OWN RUN, restarting at 0 for every run, -1 on points no polyline reaches. Empty (the default) writes none. Two things need it. ALTERNATION along a run ('every other post a different asset') has no other spelling: the global point index agrees with the per-run one only while every run has the same, even, length, and nothing reports when that stops being true. And index 0 is the FIRST MEMBER, which is how a run becomes ONE element: filterByExpression on it leaves one point per run carrying that run's start, span and fit — a ranges cloud, which is what arcTile consumes. It counts in the WALK order the runs were cut in, so on a closed path with `wrap` on, index 0 of the seam-straddling run sits before the seam. |
| `countAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (i32) receiving how many members of the run WERE FITTED — members whose `valueAttr` was finite — repeated on every member of the run, including any that were excluded. Empty (the default) writes none. FITTED rather than total because the only reason to ask is to distrust a fit made from too few points, and a run of eight whose values are six NaNs is a two-point fit however many members it has. Two is the number to watch: a line through two points is exact, so both the residual and any 'how straight is it' rule are meaningless below three, and this is the column that says so. |
| `startAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (f32) receiving the arc coordinate of the run's FIRST MEMBER, repeated on every member. Empty (the default) writes none. Reported in the path's OWN coordinate rather than the unwrapped one the fit used, so a run that began before a closed path's seam still starts where it starts — with `spanAttr` it is the range arcTile tiles, and a range that reported a start past the end of the lap would be a range no other node could read. It is also the origin `interceptAttr` is measured at: to evaluate the fitted line at an arbitrary arc a, take intercept + slope * ((a - start) wrapped into [0, period)) on a closed path, or intercept + slope * (a - start) on an open one. |
| `interceptAttr` | string | `""` |  |  |  | OPT-IN: POINT attribute (f32) receiving the fitted line's value AT THE RUN'S OWN START (arc offset zero, the position `startAttr` reports), repeated on every member. Empty (the default) writes none. This is the half of the fit that RECONSTRUCTS it: slope alone says how fast the line drifts and nothing about where it is, so anything that wants to place along the fitted line — snap a straggler onto it, continue it with fresh pieces, draw it for a debug overlay — needs this too. At the run's start rather than at the arc origin for the reason the node's description gives about cancellation: an intercept extrapolated back to lap arc zero is a number computed hundreds of units away from any data, and its error is the slope's error times that distance. |

## sampleNearestPoint

For every point of `in`, finds the nearest point of the `source` cloud in 3D (positions from P, ties resolved toward the lowest source index) and records what it found on the output's point domain: distanceAttr gets the distance (f32), indexAttr the source point index (i32), and `attribute`/`outAttribute` copy one of the source's point attributes across. This is the node that answers HOW FAR — transferAttribute's 'nearest' mapping copies a value but never reveals the distance, so banding by proximity to a road, a river or a set of landmarks needs this one. A point that finds nothing (an empty source, a non-finite position, or nothing within maxDistance) is a miss: its distance is Infinity, its index is -1, and a copied attribute keeps its prior value (the attribute default when it did not exist), so a miss is testable per point rather than only as a total. distanceAttr and indexAttr are reporting slots whose shape this node picks, so pointing either at an existing attribute of a DIFFERENT shape is refused rather than silently deleting it (a same-shape column is reused and reset); `outAttribute` is exempt, since a copy takes its shape from the source. Uses a uniform spatial grid, so large clouds are fine.

**Category:** attribute

**Inputs:** `in` (geometry), `source` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-density-along-a-path.json](../graphs/basics-density-along-a-path.json), [examples-coral.json](../graphs/examples-coral.json), [pipeline-2-districts.json](../graphs/pipeline-2-districts.json) — 10 total (`pcg graphs --node sampleNearestPoint`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `distanceAttr` | string | `"nearDist"` |  |  |  | Name of the f32 point attribute receiving the distance to the nearest source point, in world units (Infinity on a miss). Empty writes no distance. The shape is this node's to pick (f32, tuple 1), so a name the input already holds under a DIFFERENT shape is REFUSED, not overwritten — writing it would delete that column and the cook would still look fine. A same-shape column IS reused and reset; to write over another shape, removeAttribute it first or pick another name. |
| `indexAttr` | string | `""` |  |  |  | Name of the i32 point attribute receiving the nearest source point's index, or -1 on a miss. Empty (the default) writes no index. Same rule as distanceAttr: the shape is this node's to pick (i32, tuple 1), so a name the input holds under a DIFFERENT shape is REFUSED rather than deleted and re-added, while a same-shape column is reused and reset. `attribute`/`outAttribute` are exempt — a copy takes its shape from the source and overwriting is the point. |
| `attribute` | string | `""` |  |  |  | Point attribute of the `source` geometry to copy from the nearest source point. Empty (the default) copies nothing. Any type, including string. |
| `outAttribute` | string | `""` |  |  |  | Name to store the copied attribute under on the output. Empty (the default) reuses `attribute`'s own name. Ignored when `attribute` is empty. |
| `maxDistance` | f32 | `0` | >= 0 |  | yes | Largest distance that still counts as a find, in world units. 0 (the default) means unlimited; beyond it a point is a miss. As a FIELD it is PER POINT, evaluated on the points being sampled rather than on the source, so each point can accept a find at its own reach — a small prop giving up on a far road while a large one still finds it, in one cook. The unlimited sentinel is per point too, and it is 0 OR LESS: a field returning 0 — or a negative, which a subtraction easily produces — makes THOSE points unlimited rather than making them miss. So 'find nothing' is a small POSITIVE distance, never 0 and never a negative one, which would do the opposite of what it looks like. This param does not size the spatial index — cell size comes from the source cloud — so a mixed set of reaches costs nothing extra and changes no answer. |

## segmentCrossings

Emits ONE POINT PER CROSSING among the input's SEGMENTS — its 2-vertex primitives (whatever their primtype: connectPoints' edges, connectByIndex's bars, pathClip or pathResample output made of two-point pieces) — carrying the two primitive ids and the crossing's directions, as a plain point cloud (no topology). This is 'where do these bars cross', which the geometry states and nothing else in the library could ask: the middle of a braced panel's X, the knot where two lattice webs meet, the rivet or gusset that belongs there. WHAT COUNTS AS A CROSSING: two distinct segments whose CLOSEST APPROACH is within `tolerance` world units, at a place INTERIOR to both. Closest approach rather than exact intersection, so one rule covers both cases people mean: COPLANAR segments that cross (distance 0, give or take f32 rounding — the default tolerance absorbs it) and 3D segments that pass within a tolerance of each other (a lattice whose bars were built a hair apart, or two bars deliberately offset by their thickness — set `tolerance` to the offset). The point is placed at the MIDPOINT of the two closest points, so for a true intersection it is the intersection. INTERIOR means the closest point on EACH segment is farther than `tolerance` from both of that segment's ends; a meeting within `tolerance` of an end is an ENDPOINT TOUCH — an L corner, a T junction, a bar ending on another — and two segments that SHARE a point are always touching there, whatever the arithmetic says. Touches are EXCLUDED by default and included with `endpoints` 'include' (at a shared point the crossing is placed exactly on it). NEVER REPORTED: PARALLEL pairs (directions within 1e-6 rad) — an overlapping collinear pair has a whole interval of closest points and no plane, so there is no one place to put a point, under either `endpoints` setting — a segment with itself, and zero-length segments. Primitives with other vertex counts are ignored rather than refused, so a mesh and its edges can share a geometry; a geometry with no segment at all cooks to an empty cloud — zero crossings is an answer, not an error. EACH PAIR IS REPORTED AT MOST ONCE, and the OUTPUT ORDER is fixed: by the lower primitive id, then the higher (primAAttr < primBAttr always), so the cloud is the same whatever order the segments were hashed in. THE POINT CARRIES: P; the two primitive ids (i32, `primAAttr` and `primBAttr`); the unit BISECTOR of the two directions (`bisectorAttr`, f32 x3) — with B's direction flipped if needed so the two make an ACUTE angle, so it bisects the acute pair of angles and points along A's own direction (vertex 0 to vertex 1); and, opt-in, the unit NORMAL of the crossing's plane (`normalAttr`: cross(A, B) with B flipped as for the bisector) and the closest-approach DISTANCE (`distanceAttr`). Every name it writes must be its own: one of the standard columns the cloud already carries (P, rot, scale, density, boundsMin, boundsMax, color, seed) is refused, as is one name for two reports. Its `seed` is hashed from this node's seed and the two primitive ids, so a crossing keeps its identity if other crossings come and go. Primitive ids are ORDINALS in the input's primitive storage, with transferByIndex's caveat: a node that drops or reorders primitives upstream renumbers them. SCALE: segments are binned by their tolerance-grown bounding boxes into an adaptive spatial hash, and a pair is tested in exactly one cell, so tens of thousands of segments cook in time proportional to the pairs that are actually near each other. More than 1,048,576 crossings is refused, naming `tolerance` — a tolerance as large as the lattice makes every pair a crossing.

**Category:** sampler

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-where-bars-cross.json](../graphs/basics-where-bars-cross.json) — 1 total (`pcg graphs --node segmentCrossings`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `tolerance` | f32 | `0.001` | >= 0 |  |  | World units. Two segments cross when their closest approach is at most this — and a meeting counts as an ENDPOINT TOUCH (see `endpoints`) when it is within this of either segment's end. The default 0.001 absorbs the f32 rounding of coplanar geometry at the scale of a building (an f32 at 300 is good to about 3e-5); raise it to find bars that pass NEAR each other in 3D — a lattice built with its webs offset by their thickness crosses at that offset. 0 asks for exact intersections, which f32 geometry off the axis planes rarely has. Must be finite and >= 0. |
| `endpoints` | enum | `"exclude"` |  | `exclude`, `include` |  | What a meeting AT A SEGMENT'S END is. 'exclude' (the default) reports interior crossings only — an X, not an L or a T — which is what 'where do the bars cross' means on a lattice, where every bar also touches its neighbours at the joints. 'include' reports touches too: two segments sharing a point meet ON that point, and one whose end lies within `tolerance` of another is reported at the midpoint of the two closest points. A touch is the closest point on EITHER segment lying within `tolerance` of one of its ends, so with `tolerance` 0 only an exact end or a shared point is a touch. Parallel pairs are excluded under both settings. |
| `primAAttr` | string | `"primA"` |  |  |  | Name of the i32 POINT attribute receiving the LOWER of the two crossing primitives' ids — its ordinal in the input's primitive storage. Always less than the `primBAttr` value on the same point. Required: the pair is what a crossing IS. May not equal any other name this node writes. |
| `primBAttr` | string | `"primB"` |  |  |  | Name of the i32 POINT attribute receiving the HIGHER of the two crossing primitives' ids. Required, and distinct from every other name this node writes. |
| `bisectorAttr` | string | `"bisector"` |  |  |  | Name of the f32 x3 POINT attribute receiving the unit BISECTOR of the two segments' directions. Each direction runs from its primitive's vertex 0 to vertex 1; B's is flipped when the two make an obtuse angle, so the bisector halves the ACUTE angle between the bars and has a positive component along A. At a right angle, where either choice is acute, B keeps its own direction. It is the axis a part set into an X lies along. Empty = don't write. |
| `normalAttr` | string | `""` |  |  |  | OPT-IN: name of an f32 x3 POINT attribute receiving the unit NORMAL of the crossing — the cross product of A's direction and B's (flipped as for the bisector), so bisector, normal and their cross product make an orthonormal frame at the crossing, which is how a rivet's axis or a gusset plate is oriented. Empty (the default) = don't write. |
| `distanceAttr` | string | `""` |  |  |  | OPT-IN: name of an f32 POINT attribute receiving the closest-approach DISTANCE between the two segments, in world units — 0 for an exact intersection, up to `tolerance` otherwise. The number to read when tuning `tolerance` against a lattice. Empty (the default) = don't write. |

## selfPrune

Enforces a minimum distance between points, under one of two rules chosen by `mode`. The default 'greedy' considers points one at a time and keeps a point only when every already-kept point is at least minDistance away; it packs points densely, and it CANNOT BE SPLIT ACROSS CELLS — a point's fate depends on whether its neighbour survived, which depends on ITS neighbour, an unbounded chain that no halo width covers, so running it per cell in a partitioned or World cook silently produces survivors that differ with the cell size and seam pairs closer than minDistance (measured: 1.41 apart where 3 was asked for) that read as a rendering artifact rather than as this node. Use mode 'localMaximum' there: it decides each point from its immediate neighbours alone, which makes a halo of minDistance exactly sufficient, at the price of keeping fewer points. Both rules settle every contest the same way — `priority` DESCENDING (higher priority survives) with ties broken by the LOWER point IDENTITY, a hash of the point's stored position bits and its `seed` point attribute, NOT its array index. That is what makes the survivors a property of the points rather than of the order they arrived in: shuffle the input, filter something upstream, or derive the same region inside another cell's halo, and the same points survive. With priority left alone every point ties, so identity alone decides, and the result is a spatially unbiased thinning rather than the front-of-the-array-wins prune an index order gives. Points that are indistinguishable — same position AND same seed — fall back to the lower index, since nothing else separates them. Both params are field-capable: a field `minDistance` is a PER-POINT radius (scale-aware declutter — big trees claim more room than bushes), and a pair then conflicts when it is closer than the LARGER of the two radii, so no kept point ever has another kept point inside its own radius. Survivors always come out in ascending INPUT index order; priority chooses who survives, never the order of the output. Uses a uniform spatial grid, so it stays fast well beyond a few thousand points. Output is a point cloud of the survivors with all attributes carried — unless `topology` is set to 'keep', which also preserves every primitive ALL of whose points survived, renumbered onto them.

**Category:** filter

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-even-spacing.json](../graphs/basics-even-spacing.json), [basics-subgraph-exposed-params.json](../graphs/basics-subgraph-exposed-params.json), [pipeline-2-districts.json](../graphs/pipeline-2-districts.json) — 11 total (`pcg graphs --node selfPrune`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"greedy"` |  | `greedy`, `localMaximum` |  | Which rule picks the survivors — the two disagree by design, and what separates them is how far one decision reaches. 'greedy' (the default) considers the points in order and keeps one whenever every ALREADY-KEPT point is at least minDistance away. It packs points about as densely as the order allows, and it is the right rule for cooking a region in one piece. Its decisions chain, though: this point survives because that neighbour did not, which happened because ITS neighbour did, and so on with no bound — so a cell cannot reproduce it from any halo, however wide. MEASURED, not argued: over one 60x60 world of 2000 points at minDistance 3, where a whole-region cook keeps 238, cooking in cells of 10, 15, 20 and 30 (each with a full 3-unit halo) kept 4, 4, 2 and 1 point the whole cook had pruned and dropped 7, 5, 2 and 3 it had kept — every cell size wrong in its own way, none agreeing with another — and three of the four left a surviving pair closer than the 3 that was asked for (1.41, 2.18 and 1.41; the worst of them under half of it). 'localMaximum' is the rule to reach for under partitioned or per-cell (World) cooking: a point survives only when it OUTRANKS EVERY point within minDistance of it, consulting nothing further. That is ONE hop, so a cell holding everything within minDistance of its own points computes exactly the whole-region answer — all four cell sizes above: identical survivors, and no pair under minDistance anywhere, seams included. The honest cost is density. A local-maximum survivor is always a greedy survivor too, never the reverse, so this rule keeps strictly FEWER points — 122 against 238 on that same world, about half — and leaves gaps a greedy pass would have filled. It is not the better rule; it is the correct one where the greedy is wrong. |
| `minDistance` | f32 | `1` | >= 0 |  | yes | Minimum allowed distance between two kept points, in world units. As a FIELD it is a per-point radius, evaluated on the input's points, and two points conflict when they are closer than the LARGER of their two radii (never the smaller, which would let a big point be crowded by a small one, and never the sum, which would double the spacing of an evenly-sized cloud and so disagree with the same number passed plainly). A per-point radius that is 0, negative or NaN claims no room of its own, but such a point can still be pruned by a bigger neighbour. A minDistance of 0 or less turns the node off: every point survives, topology included, and `priority` is not evaluated, whichever mode is set. That is a property of the VALUE, so both spellings of it get there — a plain 0 and a `constant` field of 0 are one graph literal written two ways, and they cook to the same geometry. A field that READS anything (an attribute, a position, a random) never takes that shortcut, even when every value it returns is 0: it always outputs a point cloud, so what the output IS depends on the graph and never on the numbers that come back. This is also the HALO WIDTH a cell needs under mode 'localMaximum', and as a field that width is the GLOBAL MAXIMUM the field can return anywhere in the world — not each point's own radius, since a big point reaches that far into its neighbours, and NOT the largest radius present in the cell's cloud, which is circular: the cloud a cell sees has already been clipped by the very halo you are trying to size, so the big neighbour that would have set the width is precisely the one it cannot see. Bound the field instead of measuring it — a constant times the range of whatever drives it (e.g. a noise field is in [-1, 1], so `2 + 3 * noise` maxes at 5; a radius read from an attribute maxes at that attribute's maximum over the WHOLE world, not over this cell) — and pass that bound as the halo. Overestimating costs a wider query; underestimating silently keeps pairs closer than the field asked for, at the seams only. |
| `priority` | f32 | `0` |  |  | yes | Per-point survival priority: HIGHER WINS. Points are considered in descending priority, so a point at priority 1 survives against a neighbour at priority 0 whichever of them the tiebreak would have preferred — this is how authored points beat procedural ones by SAYING so, instead of by being merged onto an earlier pin. Field-capable and evaluated on the input's points: attribute("locked") ranks by a flag written upstream (merge the layers with mergePoints first — an attribute missing on one input fills with its default there), and randomField("key") re-rolls the thinning when the key changes. Equal priorities break to the LOWER point IDENTITY (position bits plus the `seed` attribute), and NaN ranks lowest. The default 0 ties every point, so identity alone picks the survivors — which is already unbiased, so a random priority is for re-rolling, not for undoing an ordering bias. This decides WHO survives, never the output order. |
| `topology` | enum | `"drop"` |  | `drop`, `keep` |  | What happens to the input's TOPOLOGY — the vertices and primitives built over these points. 'drop' (the default) outputs a point cloud: the survivors are rebuilt as points and EVERY primitive goes with them, whether or not the filter touched one of its points, which is why a filtered network has to be rebuilt downstream (pointsToPath over a grouping attribute, or connectPoints again). 'keep' preserves the primitives ALL of whose points survive, carrying their vertices, their vertex and primitive attributes, and the detail domain, renumbered onto the surviving points. A primitive that loses even ONE point is dropped whole: there is no truncation of a polyline or a poly that means anything — closing the gap invents a segment nobody authored and splitting the primitive in two invents a primitive, and neither is a filter's job. A primitive is never SHORTENED, so one that comes out with fewer than two vertices is one that went in that way — this node cannot manufacture a degenerate primitive, and it does not delete one either (setPolylineTopology already refuses a polyline under two vertices, so such a primitive can only have come from bare setTopology, deliberately). The POINT domain is IDENTICAL under both settings — same points, same order, same attributes, same identities — so this param only ever ADDS information and nothing reading a point can tell which was set; the one thing 'keep' carries beyond topology is the DETAIL attributes, which a point cloud has no room for. A predicate that keeps every point reproduces the input's topology, with one inherited caveat it shares with filterPrimitivesByBounds and filterPrimitivesByAttribute: surviving primitives are laid out into contiguous vertex runs, so a geometry whose primitive ranges do not TILE its vertex array (only bare setTopology can build one — nothing checks more than start + count <= vertexCount) loses the vertices no primitive references, and their vertex attribute values with them. This is the point-domain mirror of the primitive filters' `unreferencedPoints`, and it is what lets mergePrimitives find something to preserve downstream of a filter. |

## setAttribute

Creates or overwrites an attribute on the chosen domain. Numeric types fill from `value`, which is field-capable and resolves per element of that domain (so it can read position, other attributes, or noise); the evaluated field must be scalar (broadcast across the tuple) or match tupleSize exactly, and stores with the target type's conversion: i32/u32 truncate, bool stores nonzero as 1. Type 'string' writes through the geometry's string table in three modes, and the mode is decided by which params are set. With `values` empty, the constant `stringValue` is written to every element. With a non-empty `values` list there are two SELECTORS, and exactly one of them may be set: `value` is the INDEX selector — floor(selector), then clamped into [0, values.length - 1]; NaN selects 0 — while `select` is the FRACTION selector, a number in [0, 1) spread across the table, weighted by `weights` when that is set. The two conventions live in two params on purpose: a fraction read as an index (or the reverse) is a wrong distribution with nothing to report it, so the convention is named by the slot the expression sits in and setting both is refused. `select` with `weights` is what says 'these four kinds, in a 4:2:1:2 mix' in one place — the alternative is repeating table entries and scaling the selector by the table's own length. Either way one entry lands per element (e.g. per-point asset ids consumed by spawnInstances assetAttr).

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-attribute-from-noise.json](../graphs/basics-attribute-from-noise.json), [basics-mask-by-species.json](../graphs/basics-mask-by-species.json), [basics-attribute-remap.json](../graphs/basics-attribute-remap.json) — 72 total (`pcg graphs --node setAttribute`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"value"` |  |  |  | Attribute name to create or overwrite (an existing attribute of any shape is replaced). |
| `domain` | enum | `"point"` |  | `point`, `vertex`, `primitive`, `detail` |  | Domain the attribute lives on: point, vertex, primitive, or detail (one element). |
| `type` | enum | `"f32"` |  | `f32`, `i32`, `u32`, `bool`, `string` |  | Storage type. f32 keeps fractions; i32/u32 truncate toward zero; bool stores 0/1 (nonzero field values become 1); string interns into the geometry's string table and writes via `values` plus one selector (`value` by index, or `select` by fraction with optional `weights`), or via `stringValue` (see those params). |
| `tupleSize` | i32 | `1` | 1..4 |  |  | Components per element (1 = scalar, 3 = vector, 4 = color/quaternion). Range 1..4. |
| `value` | f32 | `0` |  |  | yes | Numeric value written to every element — or, for type 'string' with a non-empty `values` list, the per-element INDEX selector into it: floor(selector) clamped into [0, values.length - 1], NaN selects 0 (a total function; out-of-range never errors per element). Field-capable: evaluated on the target domain; scalar results broadcast across the tuple, otherwise the tuple size must match tupleSize. Ignored for type 'string' with `values` empty, and refused alongside `select`, which selects the same table by fraction instead. |
| `select` | f32 | `0` |  |  | yes | The other selector for type 'string' with a non-empty `values` list: a FRACTION in [0, 1) spread across the table, weighted by `weights` when that is set and in equal shares otherwise. This is what randomField produces natively, so `select` = randomField('part') needs no scaling by the table's length — which is the whole reason it exists beside `value`, whose index convention makes the author restate values.length in the expression. Total, like `value`: the fractional part is what is read (an integer part is discarded, so a selector accidentally left scaled still draws the same PROPORTIONS), NaN and -Infinity land on the first entry with a nonzero weight and +Infinity on the last, and no element ever throws. Field-capable, evaluated on the target domain; a scalar result broadcasts across the tuple. 0 (the default) means UNSET — a selector that is constantly 0 is a constant string, which is what `stringValue` is for. Setting it with a numeric type, with an empty `values`, or alongside a nonzero `value` is an error. |
| `values` | stringList | `[]` |  |  |  | String values to choose among when type is 'string': `value` selects per element by index (floor, then clamp into range), or `select` by fraction (optionally weighted by `weights`). Leave empty to write the constant `stringValue` instead. Setting this with a numeric type is an error. Note: when the attribute feeds spawnInstances via assetAttr, an empty-string entry never names an asset — the spawner falls back to its assetId param for those elements. |
| `weights` | numberList | `[]` |  |  |  | How often each entry of `values` is drawn, one weight per value in the same order: values ['rod','bar','panel','clamp'] with weights [4, 2, 1, 2] is a 4:2:1:2 mix. Each weight is a non-negative whole number (it stands for the repeated table rows it replaces, and only the ratio matters, so [0.7, 0.3] is spelled [7, 3]); 0 switches one entry off without taking it out of the table, and an all-zero list is refused because nothing would be left to draw. Empty (the default) means equal shares. Requires the `select` selector — with `value`'s index convention a weight would silently change what the same number means, so the combination is refused rather than reinterpreted. Setting it with a numeric type or with an empty `values` is an error. |
| `stringValue` | string | `""` |  |  |  | Constant written to every element when type is 'string' and `values` is empty. Must stay "" for numeric types. |
| `seed` | u32 | `0` |  |  |  | Extra seed for evaluating whichever selector is set, `value` or `select`: 0 (the default) uses the node's derived seed unchanged, so pre-existing graphs keep bit-identical output; any nonzero value folds in as hashCombine(nodeSeed, seed). This re-rolls randomness drawn from the EVALUATION CONTEXT — randomField, and the per-point seed attribute — but a noise only if it ASKS: a noise field carries its own seed inside its spec, so `valueNoise`, `perlinNoise`, `simplexNoise`, `worleyNoise` and `fbm` are unaffected here while that seed is a LITERAL. Two spellings ask. `opts.seed: {"from": "node", "variant": N}` is the one to write: the seed derives as hashCombine(the evaluation seed, variant), so this param moves the noise itself. The older spelling folds `nodeSeed` into `opts.position`, which moves WHERE the noise is sampled rather than which noise it is; no graph writes it any more, but a hand-written expression may. Bind a per-cell value (such as ctx.seed) here for per-cell variation in a World level — and note that a noise reached either way then differs in every cell, so it must not feed anything that has to agree across a seam. |

## setBounds

Sets the standard per-point bounds attributes: writes boundsMin and boundsMax (f32 tuple 3) on every point, creating the attributes when missing. THE ONE MEANING OF BOUNDS: an axis-aligned extent in the point's OWN frame, placed in the world by the point's transform, world = P + rot * (scale * x) — what spawnInstances and copyToPoints place a mesh by, and how every box node (splitBox, shellSplit, placeBox, offsetBox, transformBox, applyRules, boxContact, boxesToMesh, packBricks) reads a box; [0, 0, 0] is the point itself. TWO WAYS TO SAY THE BOX, chosen by `anchor` once per cook: "corners" (the default) writes `boundsMin` and `boundsMax` as given; "center", "baseCenter" and "min" size a `size` box ABOUT the point — centred on P (min = -size / 2, max = size / 2), STANDING on it (centred in x and z, its min y at P: min = [-x / 2, 0, -z / 2], max = [x / 2, y, z / 2], a block on its lot point), or with its min corner at P (min = [0, 0, 0], max = size). Neither way reads P, rot or scale: the anchor says where the box is relative to the point, and the point's transform says where the point is, so a rotated point's box turns with it and a scaled point's box scales with it (a box sized by the point's scale is a field: size attribute("scale", 3) * 4, which then counts the scale twice — set the size in units instead and leave scale 1, the convention for a grammar's root). That is how A GRAMMAR'S FIRST CELL is made from points fresh from a sampler or a scatter, whose zero box sits AT each point: pointScatterInBounds -> setBounds anchor "baseCenter", size [8, 12, 6] -> splitBox cuts an 8 x 12 x 6 block standing on every scattered point, and boxesToMesh builds it there. `size` is a vec3, one number (a cube), or a FIELD resolved per point (three components, or one broadcast to all three), each a length >= 0 — a negative one is refused naming the point. The corners an anchor writes are exact (f32 sizes, halved or not, short of half an odd subnormal size; a -0 written +0). The params the chosen way does not read must stay at their defaults: a corner set under an anchor, or a size set under "corners", is refused rather than silently ignored.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-two-kinds-of-bounds.json](../graphs/basics-two-kinds-of-bounds.json), [basics-split-box.json](../graphs/basics-split-box.json), [basics-cells-to-instances.json](../graphs/basics-cells-to-instances.json) — 6 total (`pcg graphs --node setBounds`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `boundsMin` | vec3 | `[0,0,0]` |  |  | yes | Minimum corner written to every point's boundsMin, in the point's own frame (world = P + rot * (scale * x); [0, 0, 0] is the point). As a FIELD it is PER POINT, which is the reading that makes this node worth more than a constant: an extent derived from a species attribute gives every instance the box it actually occupies rather than one box the whole cloud shares. Must evaluate to THREE numbers per point — a scalar is REFUSED rather than broadcast, because broadcasting would quietly hand every point a cube when a box was asked for. Both corners are resolved against the INPUT geometry before either is written, so a field here reading `boundsMax` — or any box name, box("hi") or box("size") — sees the box this cook was HANDED, never one this node produced: `vec(box("x0"), box("y0") + 1, box("z0"))` raises the floor of the incoming box by 1. Box names are in the same frame, so that rewrite keeps the box where it was. A corner built from position() counts P twice: the corners are already relative to P. |
| `boundsMax` | vec3 | `[1,1,1]` |  |  | yes | Maximum corner written to every point's boundsMax, in the point's own frame, as boundsMin. As a FIELD it is PER POINT, on the same terms as boundsMin, and refuses a scalar for the same reason. Nothing here checks that max exceeds min: the two are written independently, and a point whose corners cross is a point with an inside-out box, which is what the author asked for and what a downstream reader will see. Independently RESOLVED, too: a field here reading `boundsMin` sees the input's corner rather than the one this cook just wrote, so the two params cannot observe each other in either order. Both corners are standard point attributes, so a field naming one always finds it; a geometry with the column deliberately removed refuses here rather than resolving to a silent zero. |
| `anchor` | enum | `"corners"` |  | `corners`, `center`, `baseCenter`, `min` |  | How the box is said. "corners" (the default): `boundsMin` and `boundsMax` are the box, as given; `size` is not read. The other three size a `size` box ABOUT the point, in its own frame (P, rot and scale are not read; the point's transform places the box): "center" centres it on P (min = -size / 2, max = size / 2); "baseCenter" centres it in x and z and puts its min y AT P, so the box stands on its point (a building on its lot, a block on a scattered point); "min" puts its min corner at P (min = [0, 0, 0], max = size). Under those three the corners are not read and must stay at their defaults ([0, 0, 0] and [1, 1, 1]); a corner set there is refused rather than ignored. Decided once per cook. |
| `size` | vec3 | `[1,1,1]` | >= 0 |  | yes | The box's extent per box axis [x, y, z], in the point's own units (a point's scale multiplies it in the world), read only when `anchor` is "center", "baseCenter" or "min" — under "corners" it must stay at its default [1, 1, 1], and a size set there is refused rather than ignored. As a FIELD it is resolved PER POINT, three components or one broadcast to all three: vec(4, 3 + randomField("h") * 9, 4) gives every point its own height. Resolved against the INPUT, so a box name here reads the box the point was handed. A plain value is three lengths or ONE, a cube, as a scalar field is. Each component is a length >= 0: 0 gives a box of no volume on that axis, which is kept; a negative one is refused naming the point, and a non-finite one is refused. |

## shellSplit

BREAKS every cell's box into its SHELL — floor, the four walls south / north / west / east, and ceiling — plus, if asked, the INTERIOR they enclose, and emits one point per piece, each piece a box with its OWN FRAME and a label: the component split of a split grammar, which turns a mass into the faces later rules decorate. A CELL IS A POINT WITH A BOX, as in splitBox: its standard `boundsMin`/`boundsMax`, an extent in the point's OWN frame (world = P + rot * (scale * x)), split along the box's own axes; P, rotation and scale are not read and nothing is moved: they ride onto every piece unchanged, so a ROTATED cell's shell turns with it. THE FACES are named by the box's own sides: "floor" is the min-y side and "ceiling" the max-y side; "south" is min z, "north" max z, "west" min x, "east" max x. `faces` lists the ones to cut, in the order they are emitted, `labels` gives each its label (several may share one — the default labels all four walls "wall", so one applyRules rule or one attributeIs("piece", "wall") serves every wall, and `faceAttr` still says which), and `thickness` gives each its depth into the box. A FACE NOT LISTED TAKES NO THICKNESS, so the faces beside it reach the box's side (list no ceiling and the walls run to the top); a face listed with the label "" is a GAP: it takes its thickness and emits nothing. EVERY PIECE IS INSET, carved out of the box; nothing grows past it. CORNERS: the floor and ceiling span the FULL footprint; the walls stand between them; the south and north walls run the full x extent and OWN the vertical corners; the west and east walls stand between south and north. So with the interior the pieces TILE the box exactly, no gap and no overlap, every shared plane one stored number. A piece of no volume is dropped — a face of thickness 0, a west wall when south and north meet, any piece of a flat box. THE FRAME is written as attributes, never as a transform, and it is RIGHT-HANDED on every face (along x up = outward): `alongAxisAttr`, `upAxisAttr` and `outAxisAttr` receive the piece's axes as codes (0 = x, 1 = y, 2 = z), `alongSignAttr` and `upSignAttr` the direction along and up run (+1 or -1), and `outwardAttr` the OUTWARD unit normal. On a wall up is +y and along runs LEFT TO RIGHT AS SEEN FROM OUTSIDE it: -x on the south wall, +x north, +z west, -z east. Floor and ceiling run along +x, up +z under the floor (seen from below) and -z on the ceiling (seen from above); the outward normal is [0, -1, 0] under the floor, [0, 1, 0] on the ceiling, [0, 0, -1] south, [0, 0, 1] north, [-1, 0, 0] west, [1, 0, 0] east, zero for the interior (whose frame is +x, +y, z). That is what lets a rule be written ONCE for every wall, the same text on all four. BAYS FROM THE LEFT: splitBox with axis "perCell", axisIndex attribute("alongAxis") and direction attribute("alongSign") — slot 0 is the leftmost bay seen from outside, so "the door in bay 0" is on the left of every wall. STOREYS: the same on attribute("upAxis") and attribute("upSign"). LENGTH along: choose(attribute("alongAxis"), box("sx"), box("sy"), box("sz")). THE OUTER FACE is box("center") + attribute("outward", 3) * box("size") * 0.5 (its centre), a probe d outside it box("center") + attribute("outward", 3) * (box("size") * 0.5 + d). MOVING A PIECE OUT by d adds attribute("outward", 3) * d to BOTH corners (box("lo") and box("hi")); moving one corner alone grows the box on south and west and shrinks it on north and east. LEAVES from the outside in: splitBox perCell on attribute("outAxis") with direction dot(attribute("outward", 3), vec(-1, -1, -1)) — slot 0 is the outer leaf on every wall. BOX NAMES KEEP THE BOX'S OWN AXES — box("sx") is the x extent on every face, not "along" — because every piece stays in its cell's frame, the one every box node reads (splitBox, placeBox, packBricks); a face-local box with a per-face transform would make box("sx") mean along and be misread by all of them. `thickness` is a LENGTH in the box's units, one per face or one for all, plain or a field resolved on the PARENT cell (box("sy") * 0.1, a per-cell attribute); a negative one counts as 0. `fit` says what happens when a pair of opposite faces is thicker than the box between them (floor + ceiling past its height, south + north past its depth, west + east past its width): "error" refuses, naming the cell, the faces and the numbers; "clip" lets the min-side face keep its thickness and gives the max-side face what is left; "scale" shrinks both in proportion so they meet. A pair that exactly fills its span fits, and leaves no interior. `where` passes chosen cells through UNSPLIT, as in splitBox. Every POINT ATTRIBUTE IS CARRIED onto every piece, strings included, and the DETAIL attributes come through unchanged; TOPOLOGY IS DROPPED. OUTPUT ORDER is cell-major, each cell's pieces in `faces` order with the interior last. SEEDS: the piece of face code k — 0 floor, 1 south, 2 north, 3 west, 4 east, 5 ceiling, 6 interior, the code `faceAttr` writes — of a cell with seed s gets hashCombine(s, k), repeatPoints' copy-k seed, so a piece's seed depends on its FACE alone: it moves neither when `faces` is reordered nor when a sibling is dropped, and floor and walls are seed-identical to repeatPoints(count = 5) with copy k cut into face k. No node identity enters a piece's seed; the node's own seed reaches only the fields it resolves. CPU only: which pieces exist is a comparison per cell. FIT GLOSSARY, one meaning per word across splitBox, shellSplit, placeBox and offsetBox: "error" refuses the cook, naming the cell and the numbers; "allow" writes the result as computed; "scale" rescales what does not fit, in proportion, until it fits exactly; "clamp" slides the box back inside, keeping its size, and cuts a box larger than its limit to the limit; "clip" cuts away what passes the limit and keeps the rest, nothing moved or rescaled. This node takes "error", "clip", "scale".

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [examples-brick-house.json](../graphs/examples-brick-house.json) — 1 total (`pcg graphs --node shellSplit`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `faces` | stringList | `["floor","south","north","west","east","ceiling"]` |  |  |  | The shell faces to cut, in the order each cell emits them: any of "floor" (min y), "south" (min z), "north" (max z), "west" (min x), "east" (max x), "ceiling" (max y), each at most once. A face NOT listed takes no thickness — the faces beside it run to the box's side, so ["floor", "south", "north", "west", "east"] is a storey whose walls reach the top. `labels` and `thickness` are parallel to this list. Decided once per cook. At least one face. |
| `labels` | stringList | `["floor","wall","wall","wall","wall","ceiling"]` |  |  |  | One label per entry of `faces`, written to `labelAttr` on that face's piece. Labels may repeat, and the default gives all four walls "wall" so a single rule (applyRules, attributeIs("piece", "wall")) serves every wall while `faceAttr` still tells them apart. An EMPTY label "" makes the face a GAP: it takes its thickness and emits nothing — a floor slab some other node lays, kept clear of the walls. |
| `thickness` | numberList | `[1]` |  |  | yes | How deep each face reaches INTO the box, as a length in the box's own units: ONE entry for every face, or one per entry of `faces`, in its order. AS A FIELD it is resolved on the PARENT cell and must have one component, or one per face — vec(1, 0.5, 0.5, 0.5, 0.5, 1) — and the box names read the parent's box, so a wall can be a share of the cell it bounds: box("sx") * 0.1. Every piece is INSET (carved out of the box), so a negative thickness counts as 0 — that face is then dropped, and its neighbours reach the side. A non-finite value is refused naming the cell. A pair of opposite faces thicker than the span between them is `fit`'s to settle. |
| `interiorLabel` | string | `""` |  |  |  | The label of the INTERIOR — what the shell encloses, the box less every listed face — emitted after the faces with face code 6 when this is not empty. Empty (the default) emits no interior. With it, the pieces tile the cell exactly: their volumes sum to the box's. A room's floor plan, or the void a roof rule fills, starts here. |
| `fit` | enum | `"error"` |  | `error`, `clip`, `scale` |  | What happens when two OPPOSITE faces are thicker together than the box between them — floor + ceiling past its height, south + north past its depth, west + east past its width (a face not listed counts 0). "error" refuses the cook, naming the cell, the axis, both faces and the numbers; "clip" lays the faces in order, the min-side face (floor, south, west) first, and cuts what passes the limit — the min-side face keeps its thickness, cut at the far side of the box, and the max-side face is cut where it meets it, which can leave it nothing (the cut "clip" makes on every box node; the min side keeping its thickness is the order they are laid in); "scale" shrinks both in proportion so that they meet. A pair that EXACTLY fills its span fits under every mode and leaves no interior; "exactly" is to f32 precision, as on splitBox — the two f32 steps at the box's coordinates that placeBox and offsetBox hold a face to, plus half a step of each of the two thicknesses summed, so a box at x = 1e5 (where f32 steps are 1/128) is not refused for its storage. Decided once per cook. |
| `where` | f32 | `1` |  |  | yes | Which cells are SPLIT: nonzero splits the cell, 0 PASSES IT THROUGH UNSPLIT — emitted once, exactly as it arrived, its seed and box unchanged and any value it already carried in the attributes this node writes kept (a column this node creates gives it the column's default: "" for the label, -1 for the face and the axis codes, 0 for the signs, [0, 0, 0] for the outward normal). As a field it is resolved per cell, e.g. attributeIs("piece", "storey"). A non-finite value is refused naming the cell. A field `thickness` is still resolved on EVERY cell, passed-through ones included, so it must be finite there too. |
| `labelAttr` | string | `"piece"` |  |  |  | Name of the STRING point attribute (tuple 1) receiving each piece's label — what applyRules and attributeIs dispatch on; "piece" is theirs and splitBox's too. A REPORTING SLOT: an input column of the same shape is rewritten on the pieces and kept on cells `where` passes through, one of another shape is refused, and a standard point attribute is refused by name. Empty writes no label. |
| `faceAttr` | string | `"face"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving each piece's FACE CODE: 0 floor, 1 south, 2 north, 3 west, 4 east, 5 ceiling, 6 interior — the face, not its position in `faces`, so ge(attribute("face"), 1) * le(attribute("face"), 4) is "a wall" whatever the list. The code is also what the piece's seed is hashed with. A reporting slot on the same terms as `labelAttr`. Empty writes none. |
| `alongAxisAttr` | string | `"alongAxis"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving the axis each piece RUNS along, 0 = x, 1 = y, 2 = z: x for the south and north walls, the floor, the ceiling and the interior; z for the west and east walls. It is exactly what splitBox's axisIndex reads under axis "perCell", so attribute("alongAxis") there cuts every wall along its own run; pair it with `alongSignAttr` to cut from the left. A reporting slot on the same terms as `labelAttr`. Empty writes none. |
| `alongSignAttr` | string | `"alongSign"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving the SIGN along runs, +1 or -1, so that along x up = outward on every face: on a wall, along runs LEFT TO RIGHT AS SEEN FROM OUTSIDE — -1 on the south wall (along -x) and the east wall (along -z), +1 on north (+x) and west (+z); +1 on the floor, the ceiling and the interior. It is what splitBox's `direction` reads: axisIndex attribute("alongAxis") with direction attribute("alongSign") cuts every wall from its left end, slot 0 leftmost. A reporting slot on the same terms as `labelAttr` (0 on a passed-through cell when this node creates the column). Empty writes none. |
| `upAxisAttr` | string | `"upAxis"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving each piece's second in-face axis, 0 = x, 1 = y, 2 = z: y for the walls and the interior, z for the floor and the ceiling (whose faces lie flat). With alongAxis it spans the face; a storey or course split up a wall is a splitBox perCell on attribute("upAxis"), direction attribute("upSign"). A reporting slot on the same terms as `labelAttr`. Empty writes none. |
| `upSignAttr` | string | `"upSign"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving the SIGN up runs, +1 or -1: +1 on the walls (up is +y), the floor (+z, seen from below) and the interior; -1 on the ceiling (-z, seen from above), which is what keeps along x up = outward there. Read by splitBox's `direction` with axisIndex attribute("upAxis"). A reporting slot on the same terms as `labelAttr` (0 on a passed-through cell when this node creates the column). Empty writes none. |
| `outAxisAttr` | string | `"outAxis"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving the axis each piece's THICKNESS runs along, 0 = x, 1 = y, 2 = z: z for the south and north walls, x for the west and east walls, y for the floor and the ceiling, z for the interior. A wall cut through its depth into leaves is a splitBox perCell on attribute("outAxis"); with direction dot(attribute("outward", 3), vec(-1, -1, -1)) its slot 0 is the OUTER leaf on every wall (the sign of along x up, reversed, so the cut starts at the outer face). A reporting slot on the same terms as `labelAttr`. Empty writes none. |
| `outwardAttr` | string | `"outward"` |  |  |  | Name of the f32 point attribute (tuple 3) receiving each piece's OUTWARD unit normal — the side of the box it bounds, pointing out: [0, -1, 0] for the floor, [0, 1, 0] for the ceiling, [0, 0, -1] south, [0, 0, 1] north, [-1, 0, 0] west, [1, 0, 0] east, and [0, 0, 0] for the interior, which faces nowhere. It is what moves something OUT of its face, the same text on every wall: the centre of the OUTER face is box("center") + attribute("outward", 3) * box("size") * 0.5, a probe half a unit outside it box("center") + attribute("outward", 3) * (box("size") * 0.5 + 0.5), and a piece moved out by d adds attribute("outward", 3) * d to BOTH its corners — moving box("lo") alone would grow the box on the south and west walls and shrink it on the north and east. A reporting slot on the same terms as `labelAttr`. Empty writes none. |

## smoothNormals

Rewrites the point `normal` (f32 tuple 3) of a triangle mesh so a faceted curve shades as the surface it approximates while a real edge stays sharp. Each point's normal becomes the angle-weighted average of the faces around its POSITION whose normals lie within `angle` degrees of the point's own faces: a cylinder of 16 flat walls (22.5 degrees apart) shades round, a box (90 degrees) keeps every edge, a cap meeting its wall stays a crease. This is what extrudePolygon's output needs to read as a round tank rather than a barrel of planks — extrudePolygon gives every wall band its own four points and one flat normal, on purpose, so its creases are exact, and it cannot know which of them were meant. TOPOLOGY IS UNTOUCHED: no point is merged, split, moved or reordered, and every attribute but `normal` passes through as it came, so connected components, counts, uv seams and anything keyed by point index are exactly the input's. Points are matched by POSITION, not by index — points within `weldDistance` of each other (closing transitively) are one position — which is what lets separately-pointed bands, and separate pieces that meet edge to edge (the staves of a round wall), shade as one surface. The faces around a position are read from the whole input, so two pieces that merely touch at a shared corner at a shallow angle shade together too: run the node on the rounded part alone, before it is merged with its neighbours, when that is not wanted. A point's own faces are the reference, so a point whose faces already disagree (a shared-point mesh folded across a crease) gets the one normal that reference gives rather than being split. A point whose own faces cancel or have no area (a double-sided sheet sharing its points, a sliver) keeps the normal it came with, or [0, 0, 0] when the input had none. Reads the 'poly' primitives of 3 or more vertices, fanned from their first vertex exactly as toBufferGeometry draws them, and ignores every other primitive; an input with none is refused by name. Deterministic: positions are grouped by a union-find rooted at the smallest point index, and every sum runs in point and corner order.

**Category:** surface

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-smooth-normals.json](../graphs/basics-smooth-normals.json) — 1 total (`pcg graphs --node smoothNormals`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `angle` | f32 | `35` | 0..180 |  |  | The crease angle, in DEGREES: faces whose normals differ by this much or less shade as one smooth surface, faces that differ by more keep the edge between them. 30-40 is the usual range — the default 35 smooths any circle of 11 or more segments (under 33 degrees apart) while a decagon's 36-degree edges, an octagon's 45 and every right angle stay sharp. 0 reproduces flat shading (a point takes only faces parallel to its own); 180 smooths everything that meets at a position. |
| `weldDistance` | f32 | `0.0001` | >= 0 |  |  | How close two points must be, in world units, to count as one position when faces are gathered around it. Points are NOT merged: this only decides whose faces a point may average with. Keep it well under the mesh's point spacing: the pairs inside one neighbourhood are compared each against each, so a distance that gathers thousands of points into one position is slow as well as wrong. The default (a tenth of a millimetre, in metres) absorbs the float rounding between separately computed copies of one corner while staying far below any real feature. 0 matches a point to itself alone, so only faces that already SHARE a point smooth together. |

## spawnInstances

Spawner terminal: converts the input point cloud into render-agnostic instance batches. Each point becomes one instance with world matrix T(P) * R(rot) * S(scale) (column-major 4x4, THREE.Matrix4.elements layout; missing rot/scale attributes are identity). Points are grouped into one batch per asset id, in first-occurrence order: assetAttr (when non-empty) names a string point attribute holding per-point asset ids — empty per-point values fall back to assetId. colorAttr (when non-empty) additionally carries a per-instance RGB read from that point attribute, which is how instances of ONE asset id vary in appearance — age, health, season, a hue drift — without splitting into more assets. instanceAttrs carries any other point attributes as NAMED channels on the batch, dtype and tuple size preserved, which is how graph-authored data a host must animate (a phase, an id, an RGBA) reaches it at all: the field grammar has no time input, so the graph settles the structure and the host drives it from these channels. The 'instances' pin emits one instances item (input tags carried over); 'points' passes the input geometry through unchanged for chaining or debug rendering. One cook may spawn at most 1048576 instances (one per input point); a runaway density is refused with a diagnostic rather than an allocation failure. That budget is per COOK, not per world, so a streamed world cooking one cell at a time may hold many times it across its resident cells.

**Category:** spawn

**Inputs:** `in` (geometry)

**Outputs:** `instances` (instances), `points` (geometry)

**Examples:** [basics-spawn-instances.json](../graphs/basics-spawn-instances.json), [basics-props-along-a-path.json](../graphs/basics-props-along-a-path.json), [basics-radial-on-curve.json](../graphs/basics-radial-on-curve.json) — 31 total (`pcg graphs --node spawnInstances`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `assetId` | string | `"asset"` |  |  |  | Asset id stamped on every instance not overridden per point via assetAttr. The renderer resolves it to an actual renderable (e.g. the three adapter's asset map), UNLESS the graph supplies the mesh itself: a top-level output declared role "asset" whose name equals the id is that id's mesh, in the instance's local frame, and the editor, `pcg render` and `graphAssetMap` (pcg-ts/three) draw it. For every other id ANY STRING IS ACCEPTED and none is checked, because the set of real ids belongs to the host and the library has never met it — an invented id cooks perfectly and then renders as whatever that host does with a name it does not know, which for a viewer of arbitrary graphs is usually a stand-in shape rather than an error. So confirm the spelling against the renderer you are targeting. `pcg assets <graph.json>` lists every id a graph can emit, this param and the assetAttr tables together, and marks the ids the graph supplies itself; the rest are the list to check against that host. |
| `assetAttr` | string | `""` |  |  |  | Optional name of a string point attribute holding per-point asset ids; empty string disables the override. Points whose attribute value is empty use assetId instead. Errors when the named attribute is missing or not a string attribute. Device-resident spawning supports it: the grouping is planned on the CPU (the asset column is always host-resident) and the device composes one transform buffer per asset, in the same batch order the CPU path produces. |
| `colorAttr` | string | `""` |  |  |  | Optional name of an f32 point attribute (tupleSize 3 or more) whose components 0, 1 and 2 are carried to the renderer as each instance's RGB. ALPHA IS DROPPED — both three adapters take RGB, so a fourth component (the standard `color` attribute is f32x4) has nowhere to go and is not carried. Empty (the default) carries no colour at all, and the renderer then leaves its instance-colour channel untouched. Nothing is picked up automatically and nothing scans the values: every point cloud in this library already carries `color` at [1,1,1,1], so its presence says nothing about intent, and writing an all-white instance-colour buffer would recompile the renderer's shader for zero pixels changed. Naming it is what states the intent — which also means an attribute written upstream and never named here is silently NOT drawn. Any colour-shaped attribute works: `color`, or a `tint`/`speciesColor` written with setAttribute. Errors when the named attribute is missing or is not f32 with tupleSize >= 3, listing the attributes that would fit. |
| `instanceAttrs` | stringList | `[]` |  |  |  | Point attributes to carry to the renderer as NAMED per-instance channels, in the order given: each becomes batch.attributes[<the attribute's own name>], a tightly packed column of count * tupleSize elements with instance k at k * tupleSize. This is the whole per-instance ABI between a graph and its host. The field grammar has no time input on purpose — a graph produces STRUCTURE and the host animates it — so anything the host must drive per instance at runtime (a phase offset, a stable id, a species index, an RGBA tint, a wind stiffness) has to leave the graph on this list; before it existed only transforms and RGB could cross, and a host had to re-derive the rest from a position, which stopped agreeing with the graph that authored it. DTYPE AND TUPLE SIZE ARE PRESERVED, not widened to f32: a u32 id past 2^24 does not survive f32, and THREE.InstancedBufferAttribute takes any typed array, so nothing downstream wants the widening. Item size is recovered by the consumer as column.length / count — it is not carried, so there is no second place for it to be wrong. The one exception to "in the order given" is the one JS imposes on every object: an integer-like channel name ("12") is hoisted ahead of the string ones in the record — deterministic either way, just not always the order written. Instance order is the invariant: attributes[name][k] and transforms[k] are the same instance, written in one loop from one source index. Empty (the default) carries nothing and allocates nothing. FIVE things error, each naming the way out — and all but the first the offending entry, since an empty name has none to give — in the order they are checked, per entry rather than as a ranking across the list: an EMPTY name (drop that entry, or clear instanceAttrs to carry nothing); the same name listed TWICE (a channel is named after its attribute, so a repeat would be one channel listed twice); the reserved name "color", which is checked BEFORE the lookup and so reports as reserved even when no such attribute exists (a renderer binds instance colour structurally, so colorAttr carries it instead; copy the attribute to another name upstream to carry RGBA, which colorAttr's alpha drop cannot); an attribute MISSING from the point domain (the message lists the point attributes that could become channels); and a STRING attribute (its column is indices into a string table that does not travel with it — use assetAttr for per-point asset ids). TWO MORE refusals live at the RENDERER seam rather than here, so they cook clean and throw later, in toInstancedMeshes: a channel named after something three already means (position, normal, uv, instanceMatrix and more), which would overwrite the asset's vertex data, and a channel wider than 4 components, which a vertex attribute cannot carry — split it upstream into several narrower ones. Device production is OPT-IN: the GPU evaluator's `deviceInstanceAttrs` (which requires `deviceInstances`) gathers each channel into its own device buffer beside the transforms, for a host that binds them itself from batch.attributes[name].handle.resource. Default off, and off is what it always was: a spawn naming any channel falls back to the CPU spawner for the whole terminal, with the transforms it composes there. |

## splineSample

Samples points along polyline primitives by arc length, treating all polylines of the input as one concatenated curve. mode 'count' places exactly `count` samples (endpoints included on open curves; when every polyline is closed the samples divide the total length without duplicating the start). mode 'spacing' places samples every `spacing` world units from the start. Output points carry P, the unit segment `tangent` (f32 tuple 3), and `curveU` (f32) — the normalized arc-length position in [0, 1]. Each sample ALSO carries every attribute of the polyline PRIMITIVE it landed on, even though the polylines are measured as one concatenated curve, so a per-edge value survives the sampling; a sample landing exactly on a join between two polylines takes the LATER one's values. `primtype` is the one exception, being a type tag rather than a value, and there is no opt-out: a carried name that collides with one this node writes is refused with an error naming the attribute and the fix. TWO OPT-IN REPORTS publish the ruler this node's OUTPUT is measured in, which is not the one `curveU` speaks: `curveU` is a fraction of the INPUT CURVE's arc length, while the thing handed downstream is the POLYLINE THROUGH THE SAMPLES, and a sampling CUTS CORNERS — the two agree on straights and diverge wherever the curve bends, so `curveU` times any length is two rulers in one expression and drifts exactly over the bends where a consumer reads it. `sampledLengthAttr` writes the emitted polyline's total chord length to the DETAIL domain (one number: every polyline is one curve here), including the closing chord back to the first sample when every input polyline is closed. `sampleArcAttr` writes each sample's own arc position along that same emitted polyline, in WORLD UNITS, to the POINT domain — the coordinate pathPointAt's 'distance' mode, transferAlongPath and arcTile all read. Both are empty by default and the output is byte-identical to a cook without them. Input polylines come from pointsToPath, pathResample, or createPolyline in TypeScript; the output is a plain point CLOUD with no topology, so it is no longer a path. Topology is fragile upstream too: any node that can REMOVE points drops it — filterByDensity, filterByBounds, filterByAttribute, filterByExpression, selfPrune, partitionByAttribute — and so do mergePoints and repeatPoints, so a path that passes through one stops being a path and this node will report that it found no polylines. Category is not the rule: projectToPlane is categorised `filter` but preserves topology, and filterByAttribute drops it even when its predicate keeps every point.

**Category:** sampler

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [examples-riverbank.json](../graphs/examples-riverbank.json), [pipeline-3-lots.json](../graphs/pipeline-3-lots.json), [pipeline-3-lots-edits.json](../graphs/pipeline-3-lots-edits.json) — 7 total (`pcg graphs --node splineSample`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `mode` | enum | `"count"` |  | `count`, `spacing` |  | How samples are placed: 'count' distributes exactly `count` samples over the total arc length; 'spacing' steps every `spacing` units. |
| `count` | i32 | `10` | >= 1 |  |  | Number of samples when mode is 'count'. Minimum 1. Ignored in 'spacing' mode. |
| `spacing` | f32 | `1` | >= 0 |  |  | Distance between samples in world units when mode is 'spacing'. Must be > 0 in that mode. Ignored in 'count' mode. |
| `sampledLengthAttr` | string | `""` |  |  |  | Name of an f32 DETAIL attribute (tuple 1) receiving the length of the polyline this node EMITS: the sum of the straight-line chords between consecutive samples, plus the closing chord from the last sample back to the first when every input polyline is closed (the case in which the samples divide the curve without duplicating the start, so the emitted sequence is a ring). Empty (the default) writes none. IT IS NOT THE INPUT CURVE'S LENGTH AND THAT IS THE POINT: a sampling CUTS CORNERS, so the polyline through the samples is always SHORTER than the curve it was cut from, and the shortfall is NOT UNIFORM — every unit of it accrues over the bends and none of it over the straights, so no scale factor turns one into the other. A consumer that steps the curve's length over these samples drifts, running off the end or wrapping short of its own seam. This is the number to divide `sampleArcAttr` by for a fraction, and the number to multiply a fraction by to get back to world units; `curveU` times this length is the mistake the pair exists to remove, because that expression mixes the CURVE's parameterization with the CHORD's ruler and the two only agree where the curve is straight. Measured from the f32 positions actually written, in the same order and with the same arithmetic `polylineArcTables` uses to re-measure a cloud downstream, so the number a later pathResample, pathPointAt, arcTile or transferAlongPath computes over these points IS this number rather than a near miss — the column itself is f32, so what a graph reads is that f64 sum rounded once on the way in. IT LANDS ON THE DETAIL DOMAIN, which is where this node's vocabulary differs from pathResample's: that node resamples every polyline ON ITS OWN ARC LENGTH and emits one output path per input path, so its equivalent report (`resampledLengthAttr`) is a fact about a PRIMITIVE, one per path. This node concatenates every polyline into ONE curve and emits a CLOUD with no primitives at all, so there is exactly ONE emitted length and no primitive to hang it on — the detail domain is the library's one-element domain and where attributeReduce already writes a whole-geometry number. Note that a detail attribute is NOT readable from a point-domain field (a field reads the domain it lands on); broadcast it with promoteAttribute (from 'detail', to 'point', mode 'first') when a field needs it per sample, or read it directly from a host. Same reporting-slot rule as every report in the library: the shape is this node's to pick (f32, tuple 1), so a name the output's detail domain already holds under a different shape is REFUSED rather than deleted and re-added, and a same-shape one is RESET. "primtype" is refused outright, from the param alone: it is a type tag rather than a value, and an f32 detail column under that name is one promoteAttribute detail → primitive away from replacing the tag with a float and hiding every path from the nodes that read it. The detail domain holds no `primtype` of its own for the shape check to catch, which is exactly why this name needs stating rather than leaving to the general rule. |
| `sampleArcAttr` | string | `""` |  |  |  | Name of an f32 POINT attribute (tuple 1) receiving each sample's ARC POSITION from the FIRST sample, measured along the EMITTED polyline: sample 0 is 0, and each later sample adds the straight-line chord from the sample before it. Empty (the default) writes none. ONE RUNNING COORDINATE OVER THE WHOLE OUTPUT, not one per polyline, because that is what this node's model already is — every polyline is measured as one concatenated curve, `curveU` is a fraction of that whole, and a sample crossing from one polyline to the next adds the chord that joins them exactly as any other sample adds its own. (pathResample restarts its arc at 0 on every path because it never concatenates anything; if per-path arcs are what a graph wants, that is the node that produces them.) THE UNITS ARE WORLD UNITS, NOT A 0..1 FRACTION, and that is what makes it more than `curveU` under another name: `pathPointAt`'s 'distance' mode, `pointScatterOnPath.arcAttr`, `transferAlongPath.arcAttr` and `arcTile.startAttr` are all world-unit CHORD coordinates, so this column plugs into any of them with no multiply and nothing for the graph to get wrong. The fraction is one divide away (by `sampledLengthAttr`) while going back the other way needs the length anyway, so the coordinate that composes is the one written. `curveU` is still written beside it and still measures the INPUT curve's fraction; the two disagree by exactly the corner-cutting `sampledLengthAttr` reports, which is why `curveU` times a length is not this column and drifts against it over every bend. It lands on the POINT domain because it is a fact about a SAMPLE — a different number for every point — which is what makes it unlike `sampledLengthAttr` and why it is checked against the output's point domain rather than the detail one. THE CLOSING CHORD OF A FULLY CLOSED INPUT IS NOT IN THIS COLUMN: it runs from the last sample back to the first, so no sample holds it — it is in `sampledLengthAttr`, and the last sample's value plus that chord is the emitted length. Otherwise the last sample's value IS the emitted length. The shape is this node's to pick (f32, tuple 1), so a name already on the OUTPUT's point domain under a different shape is REFUSED rather than deleted and re-added — P, scale, boundsMin, boundsMax and `tangent` (f32x3), rot and color (f32x4) and seed (u32) all reach that refusal — while `density` and `curveU` ARE f32 tuple 1, so naming either passes the shape check and RESETS it, silently overwriting a standard column with an arc length — and `curveU` is then gone rather than merely shadowed, since the two columns become one buffer and the arc is what stays in it. Give it a name of its own. TWO MORE NAMES ARE REFUSED OUTRIGHT. A name that is also a PRIMITIVE attribute of the INPUT is refused before the cook starts, whatever its shape: every primitive attribute is carried onto these samples, so it would land on this very column, and the refusal names this param rather than the carried attribute because renaming the report is the fix and moving the author's own value is not. And "primtype" is refused because it is a type tag rather than a value — this node emits no topology, so nothing here stamps it and the collision is only latent, but the name is one the library resolves as a TYPE and one promoteAttribute point → primitive away from replacing that tag with a float and hiding every path from the nodes that read it. Naming this report the same as `sampledLengthAttr` is NOT refused: the two land on different domains, so they are different columns and nothing collides. |

## splitBox

CUTS every cell's box along one axis into an ordered list of LABELLED PIECES and emits one point per piece — the split of a split grammar (a block into storeys, a wall into bays, a bay into jamb | opening | jamb). A CELL IS A POINT WITH A BOX: its standard `boundsMin`/`boundsMax`, an extent in the point's OWN frame (world = P + rot * (scale * x), as copyToPoints and spawnInstances read it), cut along the box's own axes in the coordinates they hold; P, rotation and scale are not read and nothing is moved — they ride onto every piece unchanged, so every piece shares its cell's frame and only its box differs. THE PIECES are three parallel lists, one entry per SEGMENT in order from the START of the cut — the box's MIN side, or its MAX side where `direction` is negative: `labels` (the name each piece is given), `sizes` (a number each, or a field of that many components resolved on the parent cell) and `units` — "absolute" is that length; "relative" is a weighted share of the REST, what the absolute segments leave; "repeat" cuts the rest into max(1, <repeatRound>(rest / size)) EQUAL pieces of about `size` each (`repeatRound` is floor, round or ceil; floor by default), so `labels ["bay"], sizes [4], units ["repeat"]` gives a 10-long wall two bays of 5. A LABEL OF "" IS A GAP: it takes its space and emits nothing. A PIECE OF ZERO SIZE IS DROPPED — that is how an absent sill or lintel disappears without a branch. `snap` puts every interior cut on a lattice, `fit` says what happens when absolute sizes do not fit, and `where` passes chosen cells through UNSPLIT, which is how a nested split stays one node per level: split y into under | band | over, then split x WHERE attributeIs("piece", "band"), and the under and over pieces ride through untouched. THIS NODE ONLY CUTS, ONE LEVEL: recursion is an applyRules around it (each label a rule, the stop a relabel to a label with no rule), staging is several of it chained, and any decision the children must agree on is made on the PARENT — a field in `sizes` is resolved once per cell, before the cut, so a random cut position drawn there is the same for both halves. Every POINT ATTRIBUTE IS CARRIED onto every piece, strings included, exactly as repeatPoints carries them, and the DETAIL attributes come through unchanged; TOPOLOGY IS DROPPED. OUTPUT ORDER is cell-major, each cell's pieces in slot order from the start of its cut. `direction` says where that start is: positive (the default) the MIN side, NEGATIVE the MAX side (the first label at the max end, slot 0 there), which is how one split cuts a wall from the left as seen from outside whichever way it faces — direction attribute("alongSign") on shellSplit's walls. SEEDS: the piece in slot k of a cell with seed s gets hashCombine(s, k) — repeatPoints' copy-k seed — where k counts EVERY slot of the cell's expanded list, dropped and gap slots included, so a piece's seed does not move when a sibling vanishes, and splitBox is seed-identical to repeatPoints(count = slots) followed by setBounds. No node identity enters a piece's seed; the node's own seed reaches only the fields it resolves (a randomField in `sizes`). A cell can emit NOTHING (a zero-length box, or nothing but gaps), and the output is capped at 4194304 points in all, refused past that naming the cell the total ran out on. The seed identity holds PER LEVEL: a nested split seeds its inner pieces hashCombine(hashCombine(s, j), k), so it is not seed-identical to one flat repeatPoints over all the pieces. CPU only, like repeatPoints: piece counts and drops are comparisons. FIT GLOSSARY, one meaning per word across splitBox, shellSplit, placeBox and offsetBox: "error" refuses the cook, naming the cell and the numbers; "allow" writes the result as computed; "scale" rescales what does not fit, in proportion, until it fits exactly; "clamp" slides the box back inside, keeping its size, and cuts a box larger than its limit to the limit; "clip" cuts away what passes the limit and keeps the rest, nothing moved or rescaled. This node takes "error", "clip", "scale".

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-split-box.json](../graphs/basics-split-box.json), [basics-cells-to-instances.json](../graphs/basics-cells-to-instances.json), [basics-apply-rules.json](../graphs/basics-apply-rules.json) — 6 total (`pcg graphs --node splitBox`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `axis` | enum | `"x"` |  | `x`, `y`, `z`, `perCell`, `longest` |  | The axis every cell is cut along: "x", "y" or "z" — a component of the cell's boundsMin/boundsMax: the box's OWN axis, which turns with the point's rot, not a world direction. "perCell" reads the axis PER CELL from `axisIndex` instead, for a split whose direction is the cell's own — a wall cut along its run, which is x for a south wall and z for an east one. "longest" cuts each cell along ITS LONGEST SPAN among the axes `longestOf` names (all three by default; "xz" for the longer floor axis), the cut of a recursive subdivision that halves a panel or a plan across its long side. Decided once per cook; with "perCell" or "longest" only numbers are read per cell. |
| `longestOf` | enum | `"xyz"` |  | `xyz`, `xy`, `xz`, `yz` |  | Read ONLY when `axis` is "longest" (ignored otherwise): the axes a cell's longest span is chosen from — "xyz" (the default) all three, "xz" the floor plane (a plan cut across its longer wall whatever its height), "xy" or "yz". A span is boundsMax - boundsMin along the axis, in the box's own units: a non-uniform `scale` on the point is not applied, so with one the longest is the longest in the box's units (bake the scale into the box first, e.g. transformBox scale attribute("scale", 3) then setAttribute scale [1, 1, 1], to cut the longest in the world). The measured longest wins. A TIE goes to the FIRST axis of the set in x, y, z order, and a tie is only what f32 storage cannot resolve: a stored span is off its intended length by at most half an f32 step at each of its two corners, its own error, from ITS OWN coordinates. An axis can win when it COULD be the longest — its span plus its error reaches every other axis' span minus that axis' error — and the first such axis in x, y, z order does. A square cell, or spans written as the same decimal, are therefore cut along the first axis wherever they stand, not along whichever axis the stored corners happen to round longer, while a span longer than another by more than both their storage can explain always beats it (at z = 1e5, where a step is 1/128, a z span of 1 + 2/128 beats an x span of 1 at the origin; 1 + 1/128 ties, and goes to x; at z = 2^23, where a step is 1, a z span of 2 is known only to 1 and ties both an x of 1 and a y of 1.5, but y is longer than x past both their storage, so x cannot be the longest and y is cut). The bound is half a step for a corner rounded once; a corner an earlier cut made was rounded twice, so a square made by halving can, rarely (about 1 in 18,000), go to its second axis by a difference at the seventh digit — a full step a corner would stop that, but would hand far more boxes far from the origin to a visibly shorter axis. AN AXIS THE CUT CANNOT CUT IS PASSED OVER: if the cut along the preferred axis comes back whole (fewer than 2 pieces), the other candidates are tried longest first and the first that cuts is taken, else the preferred stands — so a box 1 wide at x = 1e7, where an f32 step is 1 and a half-way cut rounds onto a corner, is cut along a tied z span of 1.9 instead. Only the preferred axis can refuse a cell: a fallback whose sizes `fit` "error" refuses (overflow, underfill) is passed over, but the point cap is still the cook's, and a fallback that runs into it refuses the cook. A zero-size box is cut along the first axis of the set. A cell whose box is not finite, or is inside out, along any axis of the set is refused naming the cell, since it has no longest span; a cell `where` passes through is not read. |
| `axisIndex` | f32 | `0` | 0..2 |  | yes | Read ONLY when `axis` is "perCell" (ignored otherwise): the axis each cell is cut along, 0 = x, 1 = y, 2 = z. As a field it is resolved on the input's point domain, ONE AXIS PER CELL, e.g. select(attribute("alongX"), 0, 2) — an axis the cell CARRIES; for "the longest span" use axis "longest" instead of spelling the comparison here. Rounded to nearest; a value that rounds to anything but 0, 1 or 2, or is not finite, is refused naming the cell. |
| `labels` | stringList | `["a","b"]` |  |  |  | One label per SEGMENT, in order from the box's MIN side; the list's length is the segment count, and `sizes` and `units` must have the same length. Each piece is written this label in `labelAttr`; a repeat segment gives all of its pieces the same one. Labels may repeat (["jamb", "opening", "jamb"]). An EMPTY label "" makes the segment a GAP: it takes its space along the axis and emits nothing — a margin, or the ceiling plate a storey split leaves to someone else. At least one segment. |
| `sizes` | numberList | `[1,1]` |  |  | yes | One size per segment, read by its unit: a LENGTH for "absolute", a WEIGHT for "relative", the MODULE (the length one piece aims for) for "repeat". Plain, a list of numbers: [1, 3, 1]. AS A FIELD it is resolved on the PARENT CELL and must have ONE COMPONENT PER SEGMENT — build it with vec(...), which concatenates any number of components: vec(sub(attribute("sill"), box("y0")), 3, 1). The BOX NAMES (box("y0"), box("sy"), box("center") and the rest) read the box of the PARENT cell here, so a size can be a share of the cell it cuts — vec(box("sy") * 0.25, 1) — and the sizes of a nested split read the piece the split before it made. A field is where a per-cell decision goes, and since it is resolved once per cell before the cut, every piece agrees on it (a randomField drawn here cuts both halves at one coordinate). A NEGATIVE size counts as 0 (nothing, and dropped), like repeatPoints' count; a non-finite one is refused naming the cell; a repeat MODULE must be > 0 and is refused otherwise, since "pieces of size 0" has no count. |
| `units` | stringList | `["relative","relative"]` |  |  |  | One unit per segment: "absolute" (the size is a length along the axis), "relative" (a weighted share of the REST — the box length less every absolute segment — so sizes [2, 1] with both relative cut the rest 2:1), or "repeat" (the rest cut into n EQUAL pieces, n = max(1, <repeatRound>(rest / size)), so "bays of about 4" on a 10-long wall is 2 bays of 5 with "floor"). At most ONE "repeat" per split, and not together with a "relative": both would claim the rest, so the pair is refused rather than given a rule. Decided once per cook. |
| `repeatRound` | enum | `"floor"` |  | `floor`, `round`, `ceil` |  | How a "repeat" segment's count rounds: n = max(1, <mode>(rest / module)). A rest within f32 precision of a whole number of modules — two f32 steps at the box's coordinates, plus half a step of every absolute size and of each module counted, never a quarter module — counts as exactly that many, so two equal walls get the same count wherever they stand (a rest of 4 that the stored box makes 3.9999998 holds two modules of 2, not one). "floor" never makes a piece shorter than the module (as many WHOLE modules as fit, the remainder shared out), "ceil" never makes one longer, "round" is nearest with a half rounding up. A rest of 0 still gives n = 1, a piece of size 0, which is dropped. |
| `snap` | vec3 | `[0,0,0]` | >= 0 |  |  | A LATTICE STEP per axis [x, y, z]; the component of the axis a cell is cut along applies to it, and 0 means no snapping. Every INTERIOR cut is moved onto a multiple of the step on a lattice anchored at 0 of the box's coordinates — the cell's P, in its own units, not its min corner — the cell's own min and max are never moved, so the pieces tile the cell exactly (except under `fit` "clip", where an underfill leaves the far end uncovered and the end of the covered run is snapped like any interior cut) — and is then clamped into the cell. Anchored at P rather than at the cell's corner, so neighbouring cells that share a frame — every piece of one root does — agree on one lattice (a packer's). A cut within f32 precision of a lattice line counts as on it, so a box edge stored as 1.2000000477 stays on a 0.4 lattice. Snapping can shrink a piece to nothing, and that piece is dropped. On an integer lattice whose cells are already integer, snap [1, 1, 1] with snapMode "floor" turns a repeat into u0 + floor(k * length / n) — whole-number bays. |
| `snapMode` | enum | `"round"` |  | `floor`, `round`, `ceil` |  | How an interior cut lands on the `snap` lattice: "round" to the nearest line (a half rounds up), "floor" to the line at or below it, "ceil" to the line at or above it. Ignored where the step is 0. |
| `fit` | enum | `"error"` |  | `error`, `clip`, `scale` |  | What happens when the absolute sizes do not fit the box. OVERFLOW (absolute sizes past the box length): "error" refuses the cook, naming the cell, the segment where the running total passed the box, and the numbers; "clip" lays the segments from the min side and cuts the one that crosses the max end there, dropping the rest; "scale" scales every absolute size down to fill the box exactly. The relative and repeat segments get nothing either way. UNDERFILL (no relative or repeat segment to take the rest, and the absolute sizes short of the box): "error" refuses, "clip" leaves the rest of the box UNCOVERED at the max end, "scale" scales the absolute sizes up to fill it. Relative segments whose weights are ALL 0 on a cell take nothing, so that cell counts as having no flexible segment. "Fit" is to f32 precision: the two f32 steps at the box's coordinates that placeBox and offsetBox hold a face to, plus half a step of each absolute size summed (a sum of sizes errs more than one coordinate), so [0.1, 0.2, 0.7] fills a box of 1 and a box at x = 1e5 (where f32 steps are 1/128) is not refused for its storage — and an absolute run that ends within it ends AT the box's far end, leaving any relative or repeat segment after it nothing. The default is strict because a cut that silently loses area is the defect worth refusing: a relative segment of weight 1 at the end is the usual way to say "and the rest". |
| `direction` | f32 | `1` |  |  | yes | Which END of the box the segment list starts from. POSITIVE (the default, and 0) lays it from the MIN side, as every other param here describes. NEGATIVE lays it from the MAX side: the first label sits at the max end and is slot 0, a repeat counts from there, `fit` "clip" cuts at the MIN end and an underfill leaves the min end uncovered, with the same seeds per slot. Without `snap` that is the forward split mirrored. WITH `snap` it is not: the lattice stays the one anchored at 0 of the box's coordinates, and "floor" and "ceil" keep their meaning (down and up the axis), so neighbouring cells cut in either direction still share one lattice — box [0, 10], absolute sizes [3, 7], snap 4: forward the first piece is [0, 4], reversed it is [8, 10] (the raw cut at 7 rounds to 8), not the mirror image [6, 10]. As a field it is resolved per cell, so one node can cut every wall of a shell from its own start: shellSplit writes `alongSign` (+1 or -1) so that, seen from outside, along runs left to right on every wall, and direction attribute("alongSign") with axisIndex attribute("alongAxis") puts slot 0 at the left of each. Read only its sign; a non-finite value is refused naming the cell. |
| `where` | f32 | `1` |  |  | yes | Which cells are SPLIT: nonzero splits the cell, 0 PASSES IT THROUGH UNSPLIT — emitted once, exactly as it arrived, its seed and box unchanged and any label, index or count it already carried in `labelAttr`, `indexAttr` and `countAttr` kept (a column this node creates gives it the column's default: "", -1, 0). As a field it is resolved per cell, e.g. attributeIs("piece", "band"): a nested split — the band of a y split cut again in x — is then one more splitBox, with no filter and no merge, and the pieces keep their order. A non-finite value is refused naming the cell. |
| `labelAttr` | string | `"piece"` |  |  |  | Name of the STRING point attribute (tuple 1) receiving each piece's label — what a downstream node dispatches on: attributeIs("piece", "window"), a byAttribute, a spawnInstances asset key. A REPORTING SLOT like repeatPoints' indexAttr: an input column of the same shape is rewritten on the split pieces (and kept on cells `where` passes through, which is how a nested split relabels only what it cut), one of another shape is refused, and a standard point attribute is refused by name. Empty writes no label. |
| `indexAttr` | string | `"pieceIndex"` |  |  |  | Name of the i32 point attribute (tuple 1) receiving each piece's SLOT index: its position in its cell's expanded segment list, a repeat counting each of its pieces, from 0 at the START of the cut — the min side, or the max side where `direction` is negative. Dropped and gap slots are COUNTED, so the numbers need not be contiguous: the opening of an under \| sill \| opening split is slot 2 whether or not the sill had any height. That is the index the seed is hashed with. A repeat-only split numbers its pieces 0 .. n - 1, exactly as repeatPoints numbers copies. A reporting slot on the same terms as `labelAttr` (default -1 on a column this node creates). Empty writes none. |
| `countAttr` | string | `""` |  |  |  | OPT-IN: name of an i32 point attribute (tuple 1) receiving, on every piece, its cell's SLOT COUNT — the length of the expanded segment list, dropped and gap slots included, so index < count always and a repeat-only split writes n, its piece count. Empty (the default) writes none. A reporting slot on the same terms as `labelAttr` (default 0 on a column this node creates). Must differ from `indexAttr`. |

## splitPolygons

Cuts every polygon on `in` along the polylines on `cutters`, removing a strip `kerf` wide around each cut, and puts out the PIECES: the glass lights between a window's mullion bars, the panels of a facade between its joints, a slab cut into bays. Reads every CLOSED polyline (last vertex back on the first point, as pointsToPath `closed: true` and voronoiCells build them) and every 'poly' face; an OPEN polyline is refused by name. Each loop is a filled region whichever way it winds — except a loop whose `holeOf` primitive attribute is 0 or more, which is a HOLE and subtracts, so this node's own output (and an extrudePolygon-ready outline with holes from anywhere else) reads back as what it is. Overlapping loops of one set simply union; a self-intersecting loop is oriented by its net signed area and read by the nonzero rule. Each input polygon (an outer loop with the `holeOf` holes that name it) is cut ON ITS OWN, so every piece carries its polygon's PRIMITIVE ATTRIBUTES — a window id, a floor level, a material — copied onto every loop it became, and two overlapping input polygons are cut independently rather than merged. Cutters are any polylines, open or closed, and 'poly' faces (their closed boundary): each segment is buffered into a rectangle `kerf` wide, extended by kerf / 2 past both ends (square caps), and the union of those rectangles is subtracted, so a polyline's cuts join squarely and a cut ending exactly on the polygon's edge cuts clean through. A `kerf` of 0 cuts along the line with no width — the pieces share the cut edge — and a zero-width cut that stops inside a polygon without separating anything leaves it whole. With `groupAttr` set, a polygon is cut only by the cutters of its own group. Output: closed polylines (one fresh run of points per loop, the last vertex back on the first point), each OUTER loop immediately followed by its HOLES, with an i32 primitive attribute `holeOf` — -1 on an outer, and on a hole the output primitive index of its outer — which is the convention extrudePolygon's hole support reads. Loops start at their lexicographically smallest vertex in the plane and outers are sorted the same way, so the output order depends on the geometry and never on input order. Robust by construction rather than by luck: shared vertices, collinear and overlapping edges, polygons touching along an edge or at a corner, and holes pinched against their outer are all ordinary input (see `snapDistance`). Pieces come out per input polygon, in input primitive order, each polygon's pieces in canonical order. Points carry P only.

**Category:** surface

**Inputs:** `in` (geometry), `cutters` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-split-a-window.json](../graphs/basics-split-a-window.json) — 1 total (`pcg graphs --node splitPolygons`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `kerf` | f32 | `0.05` |  |  | yes | Width of the strip removed along each cut, in world units — a mullion bar's width, a joint's gap. 0 cuts along the line with no width. Field-capable on the CUTTERS' PRIMITIVE domain: one width per cutter polyline, so a window's heavy transom and its light glazing bars cut different gaps in one cook (an `attribute('barWidth')` written per cutter, or a byAttribute over a bar kind). Read the domain before writing the expression: the primitive domain carries no P, so `position()` is unavailable there. Must be 0 or more; a negative width is refused naming the cutter. |
| `plane` | enum | `"xz"` |  | `xz`, `xy`, `yz` |  | The plane the polygons are read in. 'xz' (the default) is the ground plane — the plane `extrudePolygon`'s default direction '+y' builds up from; 'xy' and 'yz' are the two walls. Input points are PROJECTED onto it (the off-plane coordinate is ignored while computing), and each result loop is written back at the off-plane coordinate of the first input point that fed it — for a floor plate at y = 3, y = 3. Outer loops come out counter-clockwise seen from the plane's positive axis (+y for 'xz', +z for 'xy', +x for 'yz'), holes clockwise. |
| `groupAttr` | string | `""` |  |  |  | Name of a scalar PRIMITIVE attribute on both pins: a polygon is cut only by the cutters whose key equals its own — one window's bars cut only that window's glass. Empty (the default) lets every cutter cut every polygon (a cutter far from a polygon costs nothing: cutters are culled by bounding box first). A string key compares by its text; a numeric key must be a whole number. Both pins must carry it with the same kind. |
| `snapDistance` | f32 | `0.0001` |  |  |  | The documented epsilon, in world units: two vertices closer than this are ONE vertex, and a vertex closer than this to an edge splits that edge — so corners that should coincide but differ by f32 rounding weld, a vertex lying on another polygon's edge is treated as ON it, and collinear or shared edges merge. Features smaller than this are not preserved: a result loop whose area is at most snapDistance squared is dropped as degenerate, and a vertex within snapDistance / 1000 of the straight line through its neighbours is removed. The default 0.0001 is a tenth of a millimetre at metre scale, a few f32 steps at a kilometre from the origin. Must be greater than 0. |

## subgraph

Composite node wrapping an inner graph as a single node. Pins and params are per-instance, derived from the exposed inner pins and the exposed inner params, so this registry entry declares none — create instances with subgraphNode(innerGraph, exposedInputs, exposedOutputs, exposedParams) and read an instance's real interface with describeSubgraphPins(def) and describeSubgraphParams(def). A serialized subgraph node carries its exposed-param VALUES in "params" and its inner graph plus the exposed pin and param DECLARATIONS either inline under "subgraph" ({ graph, inputs, outputs, params }), recursively in the same versioned format, or by reference under "ref" ({ name, hash? }) to a subgraph registered with registerSubgraph. "subgraph" and "ref" are mutually exclusive; a ref's "hash" is optional, and pins the reference to that exact content (a mismatch is an error, never a warning).

**Category:** composite

**Meters the cook budget itself:** under `cook(graph, { budgetMs })` this node yields to the event loop inside its own execute, so its `NodeDoneInfo.elapsedMs` is wall time spanning those yields — not an uninterrupted block. Derive a longest-block figure from a cook with the budget unset.

**Inputs:** *(none)*

**Outputs:** *(none)*

**Examples:** [basics-subgraph-exposed-params.json](../graphs/basics-subgraph-exposed-params.json), [basics-primitive-ref.json](../graphs/basics-primitive-ref.json), [basics-gather-on-path.json](../graphs/basics-gather-on-path.json) — 38 total (`pcg graphs --node subgraph`)

**Params:** *(none)*

## surfaceSample

Scatters points on a triangle mesh: each of `count` candidates picks a triangle with probability proportional to its area, then a uniform position on it (uniform barycentric placement). densityField (0..1) is then evaluated once over the candidate cloud and each candidate is accepted when a per-candidate hashed random < density — so the output count is at most `count` and exactly `count` when density is 1. Output points carry P, a flat per-triangle `normal` (f32 tuple 3), density 1, and a hashed per-point seed. They ALSO carry every attribute of the triangle's own PRIMITIVE, gathered onto each sample — a per-face value written upstream survives the sampling instead of dying at it. `primtype` is the one exception, being a type tag rather than a value, and there is no opt-out: a carried name that collides with one this node writes is refused with an error naming the attribute and the fix.

**Category:** sampler

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-surface-sample.json](../graphs/basics-surface-sample.json), [examples-forest.json](../graphs/examples-forest.json) — 2 total (`pcg graphs --node surfaceSample`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `count` | i32 | `100` | >= 0 |  |  | Number of candidate samples to place before density acceptance. Minimum 0. |
| `seed` | u32 | `0` |  |  |  | Extra seed folded into the node seed; change it to re-roll the sampling. |
| `densityField` | f32 | `1` | 0..1 |  | yes | Acceptance probability in [0, 1] per candidate, evaluated on the candidate points after placement (so it can read P or noise). 1 keeps every candidate; 0 keeps none. |

## sweepProfile

Places a cross-section on EVERY POINT of every polyline primitive and stitches consecutive placements into 3-vertex 'poly' triangles: a curve becomes a surface. This is what `pathSegments` could only fake — a run of overlapping instanced cylinders becomes one continuous skin, at HALF the drawn triangles of the eight-sided instanced tube it replaces, because rings are shared between segments and no interior caps grow. THE PATH IS NOT RESAMPLED: one ring per input point, exactly where the point is, so a field-capable `radius` resolves at the ring rather than being averaged across a segment's endpoints the way pathSegments must. Run `pathResample` first for a finer surface. Output carries P, a `normal` (f32 tuple 3) and a `uv` (f32 tuple 2) the node writes itself — `u` is normalized arc length along the path, matching the `curveU` that pathSegments and pathPointAt write, and `v` runs around the profile — plus every INPUT POINT attribute copied (not interpolated) around each ring, and every input PRIMITIVE attribute gathered onto the triangles that came from it, so a per-path `roadWidth` or `chordPick` survives the sweep and a primitive-domain filter downstream can still see it. Input VERTEX attributes are dropped: the topology they described is gone. `normal` and `uv` are reporting slots — an input already carrying either at a different shape is REFUSED by name rather than silently deleted. Open versus closed is structural and needs no flag: a closed path shares its first and last ring so the tube closes on itself exactly (which means `u` returns to 0 across that one closing band — a texture measured along `u` repeats backwards there, the price of a genuinely closed tube), and `caps` applies only to an OPEN path with a CLOSED profile, since a closed path has no ends and a ribbon has no hole. Roll around the path is fixed by `frame` and never by chance. Junctions are NOT solved: where several polylines share an endpoint each is swept independently and the surfaces overlap, which is what every mitered-stroke renderer does by default.

**Category:** surface

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-sweep-profile.json](../graphs/basics-sweep-profile.json), [basics-clip-a-path.json](../graphs/basics-clip-a-path.json), [basics-colonnade.json](../graphs/basics-colonnade.json) — 4 total (`pcg graphs --node sweepProfile`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `profile` | enum | `"circle"` |  | `circle`, `square`, `ribbon`, `rect`, `polygon` |  | Cross-section shape. 'circle' and 'square' are CLOSED (a tube, and a square rod whose four faces stay flat because its corners carry per-face normals) and take `radius` and `caps`; 'ribbon' is OPEN — a flat two-point strip of `width`, centred on the path, facing the frame's up axis — and takes neither, because a strip has no inside. 'rect' is the square with its two extents set apart: `width` across the path (the ring's first axis) by `height` along the frame's up axis, both field-capable, placed by `anchor` (centred on the path, standing on it, or hanging from it) — a wall, a kerb, a beam, a plank — with the same flat faces, split corners, frames, miter and caps as 'square'. 'polygon' is any closed section with flat faces: the corners in `section`, in the ring's (across, up) frame relative to the path point, scaled per axis by `width` and `height` (both 1 by default, so the corners are world units). Every corner of a 'rect' or 'polygon' is split, so all its faces shade flat; run smoothNormals after the sweep to round the shallow ones. A profile from a second geometry pin (an I-beam as a mesh) is deliberately not here yet: it forces decisions no consumer has asked for, and these enum values stay valid when it arrives. |
| `sides` | i32 | `8` | 3..256 |  |  | Points around a 'circle' profile; ignored by every other profile. Default 8 matches the shipped tube asset (a three.js CylinderGeometry with 8 radial segments), so a swept tube reads like the instanced tube it replaces. Cost is linear: the ring emits `sides + 1` points (the extra one duplicates the seam so the uv does not run backwards across one column of quads) and `sides * 2` triangles per band. |
| `radius` | f32 | `0.05` | >= 0 |  | yes | Distance from the path to the surface, in world units, for the 'circle' and 'square' profiles ('square' reads it as HALF-WIDTH, so the section fits a 2 x radius box); ignored by 'ribbon', 'rect' and 'polygon', which read `width` (and `height`) instead. Same default as pathSegments' `radius`. Field-capable and resolved on the INPUT points — the path's own points, which is exactly where a ring sits — so a taper is exact rather than averaged. A per-path radius living on the primitive domain has to be promoted onto the points first (promoteAttribute, primitive to point) before a field can see it. |
| `width` | f32 | `1` | >= 0 |  | yes | Full width across the path in world units for a 'ribbon' (the strip runs from -width/2 to +width/2) and a 'rect' (its extent along the ring's first axis); for a 'polygon' it MULTIPLIES the `section` coordinates along that axis. Ignored by 'circle' and 'square'. Field-capable on the INPUT points, so a road that widens at a junction is one promoted attribute away. |
| `height` | f32 | `1` | >= 0 |  | yes | Extent of a 'rect' along the frame's up axis (the ring's second axis — the axis a 'ribbon' faces), in world units; for a 'polygon' it MULTIPLIES the `section` coordinates along that axis. Ignored by the other profiles. Field-capable on the INPUT points, resolved at the ring exactly as `width` is, so a wall that rises along its run or a kerb that dips at a crossing is one attribute away. The two are independent: a non-uniform scale is applied BEFORE `roll`, so a rolled 'rect' stays a rectangle, and each face normal is carried through the scale (inverse-transpose) so a sloped 'polygon' face keeps shading the way it faces. A zero extent makes the faces along it zero-area — drawn as nothing, skipped by area-weighted sampling — and leaves their normals unscaled rather than zero. |
| `anchor` | enum | `"center"` |  | `center`, `bottom`, `top` |  | Where a 'rect' sits across the frame's up axis: 'center' centres it on the path; 'bottom' STANDS it on the path — its bottom face runs through the path's points, so the section spans 0..height above them, which is a wall or a kerb built on a ground-hugging line; 'top' hangs it below, spanning -height..0, which is a beam under a deck line. Ignored by every other profile — a 'polygon' already says where the path is, because its corners are relative to the path point. Turned with the section by `roll`, about the path point. |
| `section` | numberList | `[]` |  |  |  | Corners of a 'polygon' profile as a flat list [x0, y0, x1, y1, ...]: x across the path along the ring's first axis, y along the frame's up axis, relative to the path point, then scaled by `width` and `height`. At least three corners; either winding (a clockwise list is reversed about its first corner, which keeps `v` = 0 there); do not restate the first corner at the end — the section closes itself. With frame 'upHint' and the default up, a horizontal path's first axis points to the LEFT of the direction of travel, so (x, y, travel) is right-handed; [0.5, 0, 0.5, 1, -0.5, 1, -0.5, 0] is a unit block standing on the path. Every corner is split (flat faces, per-face normals), `v` runs 0..1 by arc length around the corners in counter-clockwise order (starting at the first corner) measured on the section as given, before `width` and `height` scale it. Caps are exact for ANY simple section: a convex one is a fan of n - 2 triangles from its first corner, a concave one (an L, a T, an I-beam) is ear-clipped, deterministically, and neither adds a point. The section must not cross itself — a self-crossing list is not refused, and its caps describe nothing. Refused by name when it is not whole pairs, has fewer than three corners, repeats a corner, or encloses no area. Ignored by every other profile. Not field-capable: the section is one shape for the whole sweep, and `width`, `height` and `roll` are what vary per ring. |
| `frame` | enum | `"upHint"` |  | `upHint`, `curveFrame`, `rot` |  | Where the ROLL inside the ring comes from. The ring's PLANE always comes from the path, so this never changes where the surface is, only how the profile is turned within it — which is invisible for a circle and decisive for a square or a ribbon. 'upHint' uses the `up` param through the same deterministic construction (and the same [0,0,1] then [1,0,0] fallbacks) orientAlongVector and pathSegments use: purely local, correct for a tube and for a flat road ribbon, wrong for a ribbon on a curve that turns over. 'curveFrame' reads the `curveNormal` point attribute writeCurveFrame writes — a rotation-minimizing frame carried ALONG the curve, which is what a ribbon on a twisting path needs; `curveBinormal` is not read, the second axis is derived so the ring stays right-handed. 'rot' reads the standard `rot` quaternion's local +X, so anything that writes `rot` (orientAlongVector, with its field-capable direction and up) drives the roll. Both attribute modes fall back to `up` at a point whose attribute is degenerate. This node TRANSPORTS nothing along the path: the ring plane reads only the two segments meeting at its own point (a one-neighbour rule, the same reach writeTangents has) and no mode carries a value forward, so the only non-locality in a swept surface is whatever the attribute it was handed already had — 'curveFrame' inherits the non-locality writeCurveFrame documents, and nothing more. |
| `up` | vec3 | `[0,1,0]` |  |  | yes | Up hint fixing the roll in 'upHint' mode, and the fallback in the other two; need not be unit length. When parallel or antiparallel to the path direction (or zero) it deterministically falls back to [0, 0, 1], then [1, 0, 0] — the same contract orientAlongVector and pathSegments state, through the same shared code, so a vertical path's roll is arbitrary but never random. Field-capable on the input points. |
| `roll` | f32 | `0` |  |  | yes | Turns of the profile about the path direction, applied inside the ring plane on top of `frame` — 0.25 is a quarter turn, 1 is a full one. Field-capable on the input points, so a value that ramps along the path twists the section. Invisible on a 'circle' (it is rotationally symmetric) and the reason a 'square' or 'ribbon' can be aimed without changing the frame. |
| `joint` | enum | `"miter"` |  | `miter`, `perpendicular` |  | How the section meets a bend. Both modes put the ring in the plane that BISECTS the two segments meeting at the point; they differ in whether the section is corrected for the tilt. 'miter' stretches the ring by 1/cos(half the turn angle) along the bend direction, which is exactly the ellipse a cylinder cuts on that plane, so the tube keeps its radius through the corner. 'perpendicular' leaves it, so the section thins by cos(half the turn angle) — 33% at a 96-degree bend, which is visible. Miter self-intersects only when the mitered half-width exceeds half the shorter segment; `miterLimit` is what refuses that. |
| `miterLimit` | f32 | `4` | >= 1 |  | yes | Largest stretch 'miter' may apply. Past it the ring falls back to the unstretched 'perpendicular' section for that point ONLY, which pinches rather than shooting a spike out of the corner. A stretch of 4 is a 151-degree turn; the limit is never reached by a path that was resampled at anything like an even spacing, and exists for the pathological input that would otherwise self-intersect. Field-capable on the INPUT points — the limit is read at the RING, from the point the ring stands on, so one deliberate spike and a capped remainder are one cook rather than two: a corner attribute lets the one junction that should keep its radius through a hairpin do so while every other corner stays bounded. As a field a value BELOW 1 is not refused at the point the way a plain number is refused at the door; it is read for what it does, which is admit no miter at all (a stretch is always > 1 when there is a bend), so that ring takes the unstretched section — the same fallback the limit already names when it is exceeded. Non-finite is refused with the offending element named, so 'never limit' is spelled as a large finite number rather than as Infinity: a stretch of 64 already admits a 178-degree turn. Ignored by 'perpendicular', where a field is not evaluated at all — exactly as `radius` is left unresolved for a 'ribbon' — while a plain number still meets its >= 1 check wherever the graph is loaded or patched. |
| `caps` | bool | `true` |  |  |  | Close the two ends of an OPEN path with a CLOSED profile, with triangles over the end ring's own corners and NO extra centre point: a convex section ('circle', 'square', 'rect', a convex 'polygon') is a fan of n - 2 triangles from its first corner, so a box end is 2 triangles and an 8-sided tube's end is 6, and a concave 'polygon' is ear-clipped. The start cap faces back along the path, the end cap forward. Ignored for a closed path (it has no ends) and for the 'ribbon' profile (it has no hole), so all four combinations are defined rather than merely unsurprising. Cap points are separate from the wall's, so the seam between a flat cap and a round wall stays a real crease instead of being smoothed away. Cap uv is not a continuation of the wall's: for 'circle' and 'square' it is a disc mapping — the unit section, turned by `roll`, mapped into the 0..1 square — and for 'rect' and 'polygon' it maps the section's own bounding box onto 0..1, so a rectangle's corners land exactly on the uv square's. |

## transferAlongPath

Reads a path's point attributes AT ARBITRARY ARC POSITIONS and writes them onto a second, independent point cloud — N stations against an M-point path, with N and M unrelated. The `at` cloud comes back with its count, its order, its identities and its topology untouched, plus one column per sampled attribute. This is the operation the library had no node for. pathPointAt slides the path's OWN points, so its output carries the path's point count and topology and can only answer questions about the path itself; writeCurveFrame evaluates only where a path already has a point; transferAttribute is the NEAREST-POINT gather, which asks its question in space rather than along the arc, and the two answers part company exactly where a curve folds — two stations tens of units apart along a lap are centimetres apart in world space at a hairpin, and a nearest-point gather there reads the far side of the corner and reports it as a hit. This is the arc-parametric sibling of that node, and the pair covers 'what is near me' and 'what is at this distance along'. THE ARC COORDINATE IS THE CHORD ONE: the running sum of the straight-line distances between consecutive path points, including the closing segment when the polyline is closed, which is the same table pathResample steps, pathPointAt's 'distance' mode reads and arcTile tiles over. INTERPOLATION IS LINEAR between the two bracketing path points, componentwise, one tuple size in and the same tuple size out. It is not a spline and does not pretend to be: a polyline is a sequence of segments, and inventing curvature between two of its samples would put values on the cloud that the path never held anywhere. EVERY SAMPLED COLUMN ARRIVES AS f32 whatever the path stored it as, because an interpolated value is a real number — a lane index blended half way between lane 1 and lane 2 is 1.5, and an integer column would round that to a value neither neighbour holds and destroy the one fact the query was asking for. A value that must stay discrete is not an interpolation and belongs on transferAttribute's 'nearest' mapping. WHICH ATTRIBUTES: name them in `attributes`, or leave that empty to take every NUMERIC point attribute of the path except the eight standard bookkeeping columns (P, rot, scale, density, boundsMin, boundsMax, color, seed) — see that param for the argument. Naming one LIFTS the exclusion — the eight are skipped by the default rule, not forbidden — and P is the case that earns the design: sample P and every point moves to its own arc position, which is how a cloud of stations becomes a set of positions on a road. Lifting the exclusion is not a promise that the write lands: a sample arrives as f32, so the library's reporting-slot rule refuses a name the `at` cloud already carries in ANOTHER shape rather than deleting it, and `seed` therefore never lands on an ordinary cloud, whose own seed is u32 — which is the right answer, since an interpolated identity is not one. P is exempt from that rule because it is written into the cloud's own column. String attributes cannot be interpolated at all; the default rule skips them and naming one is refused. WRAPPING FOLLOWS THE PATH'S OWN CLOSED FLAG, in `pathRuns`' words and with its semantics: on a CLOSED path `wrap` (the default) takes the arc position modulo the path's length, correcting a negative, so any real number is a legal station and a lap counter that has passed the line four times still lands in the right place; with it off, and on an OPEN path where it does nothing, positions outside the path CLAMP to its ends. Either way the closing segment of a closed path is a segment like any other, so a position between the last point and the first interpolates round to the first rather than falling off the end. NORMALIZE re-lengthens a direction the blend shortened, and is opt-in for the reason the param gives. DETERMINISM IS STRUCTURAL HERE, not a promise about a seed: each point of `at` is answered from its own arc value and the path alone, there is no reduction over the cloud and no randomness of any kind, so the same station gets the same answer in a cloud of one and a cloud of a million, in any order, and shuffling the input shuffles the output and changes nothing else. ONE POLYLINE ONLY: a path input holding several is refused rather than resolved to the first, because gathering off the wrong road is a cook that looks entirely fine. The output's topology is the `at` cloud's — this node removes no point, so a path handed to `at` comes back a path.

**Category:** attribute

**Inputs:** `path` (geometry), `at` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-stations-on-a-path.json](../graphs/basics-stations-on-a-path.json) — 1 total (`pcg graphs --node transferAlongPath`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `arcAttr` | string | `"station"` |  |  |  | POINT attribute on the `at` input (tuple 1, numeric) holding each point's position along the path, as an arc length in WORLD UNITS — the same coordinate pathPointAt's 'distance' mode reads and arcTile's `startAttr` carries. Must exist; a string column and a column wider than one are both refused, the second because which component was meant is not a question this node answers for you (extract it first with setAttribute and a component() field). THE UNITS ARE THE TRAP, not the name. A track measured in half-widths, a route measured in fractions of the whole and a scan measured in samples are all called a station by somebody, and all three land somewhere wrong here without being obviously wrong anywhere: multiply by the half-width, by the path's length, or by the sample pitch with setAttribute first, and gather on the world-unit column. A NON-FINITE value is refused, naming the point — a station that could not be computed has nowhere to be, and writing the value at arc 0 onto it would hand a real position to a point whose position is unknown, which is the failure this refusal exists to prevent rather than to disguise. Drop such points upstream with filterByExpression, or give them a station with setAttribute. |
| `attributes` | stringList | `[]` |  |  |  | Path POINT attributes to interpolate onto the cloud, in any order. AN EXPLICIT LIST IS WHAT TO WRITE WHEN THE ANSWER MATTERS: every name here is sampled, and naming one of the eight standard bookkeeping columns lifts the exclusion the empty list applies — they are skipped by that rule, never forbidden by it. EMPTY (the default) means every NUMERIC point attribute of the path EXCEPT P, rot, scale, density, boundsMin, boundsMax, color and seed. Those eight are excluded because they are the point domain's own bookkeeping — written on every cloud in the library before anyone has decided anything — and each of them describes the path's POINTS rather than the curve: blending seed produces an identity that is neither of its neighbours and then drives randomness as though it meant something; P moves the whole cloud; rot and scale overwrite the transform the cloud arrived with; boundsMin/boundsMax its extent. What is left is exactly what somebody wrote onto the path deliberately — tangent, up, across, curveU, a half-width, a banking angle, a lane count — which is what a station wants. STRING ATTRIBUTES are skipped by the empty-list rule and REFUSED when named, because there is no value between two strings; move one across with transferAttribute's 'nearest' mapping instead. NAMING P IS THE PLACEMENT IDIOM and the reason the eight are excluded rather than forbidden: sample P and every point of the cloud moves onto the curve at its own arc position, which is how a scattered set of stations becomes a set of positions on the road. P is written into the cloud's OWN P column, three components, and that column is never reshaped. THE OTHER SEVEN ARE STILL SUBJECT TO THE REPORTING-SLOT RULE, because a sample lands as f32 and the column on the `at` cloud is the author's: `rot`, `scale`, `density`, `boundsMin`, `boundsMax` and `color` are f32 there too and land; `seed` is u32, so it is refused on any ordinary cloud rather than replacing an identity column with a blend of two identities. Sample it under another name if you really want the number — rename it on the PATH first with setAttribute — and read the refusal as the answer it is. A path with none of its attributes left after the exclusions is refused rather than cooking to a cloud with nothing added, which would look like success. |
| `wrap` | bool | `true` |  |  |  | Whether an arc position may run off the end of a CLOSED path and come back. True (the default) takes the position modulo the path's length and corrects a negative, so any real number is a legal station — a counter that has passed the start line four times, or a marker placed 3 units BEFORE it at -3, both land where they should. False treats the path's arc as an interval and CLAMPS to its ends. No effect on an OPEN path, which has no seam to cross and always clamps, so the default follows the path's own closed flag and nothing has to be set for the ordinary case. This is not about the closing segment, which exists on a closed path either way: a position between the last point and the first interpolates round to the first under both settings. It is only about what happens outside [0, length]. |
| `normalize` | stringList | `[]` |  |  |  | Sampled attributes to rescale to unit length after interpolation (l = the tuple's length, or 1 when that is zero, then divide). OPT-IN because it is a correction, not a default: INTERPOLATING A DIRECTION SHORTENS IT, by an amount that depends on the angle between the two path points' values, so it is worst exactly where the path turns hardest and the shortfall is invisible until something reads the length. A caller sampling `tangent`, `up` and `across` almost always wants all three back at unit length, and one that sampled a velocity or a gradient wants the length left exactly as it came out. NORMALISING THREE AXES INDEPENDENTLY DOES NOT RE-ORTHOGONALISE THEM: each comes back unit length and the angles between them are still the blended ones, which are not right angles wherever the frame twisted between the two path points. A frame that must be orthonormal has to be rebuilt from two of its axes with a cross product (setAttribute and a cross() field), and this param is not that. The same caveat covers `rot`: a componentwise blend of two quaternions normalised afterwards is a shortest-path interpolation of nearly-aligned ones and nothing useful for a pair that are far apart or opposite in sign. Every name must be one this node actually sampled — a name that is not in `attributes`, or that the empty-list rule left out, is refused rather than ignored, since a normalisation that silently did not happen is the failure this param exists to fix. A tuple size of 1 is refused (unit length on one component is the sign, which is what a sign() field is for) and so is P, whose unit length would put the whole cloud on a sphere around the origin. |

## transferAttribute

Transfers an attribute from the `source` geometry onto the main input's points, creating or overwriting it on the output's point domain. Mapping 'nearest' copies from the nearest source point in 3D (positions from P; distance ties resolve to the lowest source index; every point is assigned). Mapping 'uv' locates each destination point's UV (see uvAttr) in the source triangulation's UV space and interpolates inside the containing triangle; a UV on an edge shared by two triangles deterministically picks the lowest source primitive index. Mapping 'raycast' casts a normalized ray from each destination point along `direction` (or per-point directionAttr) against the source triangle mesh and interpolates at the nearest forward hit (smallest t >= 0, optionally capped by maxDistance; exactly-equal distances pick the lowest source primitive index). For uv/raycast the source must have 3-vertex 'poly' primitives (createTriangleMesh); zero-area (degenerate) triangles are skipped; f32 attributes interpolate barycentrically while i32/u32/bool/string take the triangle corner with the largest barycentric weight (ties to the first corner in vertex order). A PRIMITIVE source (attrDomain 'primitive') is never interpolated, whatever its type: a per-face value is constant across its triangle, so it arrives bit-exact instead of blended, and a per-triangle id, material tag or width survives the transfer intact. That reads a per-face value off a triangle MESH only — an edge or polyline network (a road from connectPoints/pointsToPath) has no 3-vertex 'poly' primitives, so neither uv nor raycast can ever reach one; to move a value off an edge network, promoteAttribute it from 'primitive' to 'point' on the source and transfer with mapping 'nearest'. Back to the shared policy: destination points with no containing triangle or no hit are misses that keep their prior value (the attribute default when the attribute did not exist) — set missCountAttr to record how many missed, and hitAttr to record WHICH ones did not (a per-point bool, 1 = found a source, 0 = missed). A miss cannot report itself through the transferred value, so hitAttr is the only per-point way to find one: filter on it to discard the misses rather than casting a second query to re-learn what this one already knew. All mappings are accelerated with deterministic uniform grids, so large inputs are fine.

**Category:** attribute

**Inputs:** `in` (geometry), `source` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-transfer-attribute.json](../graphs/basics-transfer-attribute.json), [examples-archipelago.json](../graphs/examples-archipelago.json), [examples-rig.json](../graphs/examples-rig.json) — 3 total (`pcg graphs --node transferAttribute`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"density"` |  |  |  | Name of the attribute to transfer. Must exist on the source domain selected by attrDomain — point, vertex or primitive for mappings 'uv' and 'raycast', always the point domain for mapping 'nearest'. |
| `mapping` | enum | `"nearest"` |  | `nearest`, `uv`, `raycast` |  | How destination points find their source value: 'nearest' (closest source point in 3D), 'uv' (barycentric lookup of the destination UV in the source triangulation's UV space), or 'raycast' (nearest triangle hit along a ray from each destination point). |
| `attrDomain` | enum | `"point"` |  | `point`, `vertex`, `primitive` |  | Source domain the transferred attribute is read from (uv/raycast only): 'point' reads triangle corners through the topology, 'vertex' reads per-corner values (seam-accurate), 'primitive' reads one value for the whole triangle. Mapping 'nearest' supports only 'point'. The result always lands on the destination's point domain. What 'primitive' reaches, and what it does not: it reads a per-face value off a TRIANGLE MESH — the source still needs 3-vertex 'poly' primitives, so an edge or polyline network (a road built with connectPoints or pointsToPath, carrying a width promoted onto its edges) has no triangles for either mapping to find and is refused, naming the fix. To move a value off an edge network, promoteAttribute it from 'primitive' to 'point' on the source and transfer with mapping 'nearest'. |
| `uvAttr` | string | `"uv"` |  |  |  | UV attribute name for mapping 'uv' (ignored otherwise). On the destination it must live on the point domain (f32, tupleSize >= 2; extra components ignored). On the source it is read from the vertex domain when present (per-corner UVs, supports seams), else from the point domain. Destination UVs with non-finite components miss. |
| `direction` | vec3 | `[0,-1,0]` |  |  | yes | Ray direction for mapping 'raycast'. As a plain vector it is ONE direction shared by every destination point, normalized internally so maxDistance is world-space, and required to be non-zero and finite — a whole cloud casting nowhere is a mistake, not a result. As a FIELD it is a PER-POINT ray direction, evaluated on the destination points, so each point casts the ray it asks for: normalize(sub(attribute("target"), position())) aims every point at a moving target, and a noise-driven direction scatters the rays without a setAttribute node upstream to hold them. Each direction is normalized per point, so only its DIRECTION is read and its length never changes a hit distance. The non-zero refusal becomes a per-element policy: a point whose direction resolves to exactly zero MISSES — it keeps its prior value and is counted by missCountAttr and flagged 0 by hitAttr, exactly like a point whose ray hits nothing — rather than failing the cook for the whole cloud. Non-finite is still refused, naming this param: a NaN direction is a broken expression (a normalize of a zero-length vector, a division by zero upstream), not data. Ignored, and not even evaluated, when mapping is not 'raycast' or when directionAttr is set — directionAttr still wins, so a field here and an attribute there is the attribute, silently, as it already was for a plain vector. |
| `directionAttr` | string | `""` |  |  |  | Optional per-point ray direction attribute on the destination point domain (f32, tupleSize >= 3) for mapping 'raycast'; overrides `direction` when non-empty. Each direction is normalized per point; points with a zero or non-finite direction miss. Empty = use `direction`. |
| `maxDistance` | f32 | `0` | >= 0 |  | yes | Maximum world-space hit distance for mapping 'raycast' (ignored otherwise). 0 (the default) means unlimited; a positive value ignores hits farther along the ray. Rays are forward-only regardless (hits need t >= 0). As a FIELD it is a PER-POINT cap, evaluated on the destination points, so each point gives up at its own reach — a small prop accepting only a nearby surface while a large one still finds a distant floor, in one cook. The unlimited sentinel is per point too, and it is 0 OR LESS: a field returning 0 — or a negative, which a subtraction easily produces — makes THOSE rays unlimited rather than making them miss. So 'accept nothing' is a small POSITIVE distance, never 0 and never a negative one, which would do the opposite of what it looks like. A point capped short of every hit is an ordinary MISS — it keeps its prior value and is counted by missCountAttr and flagged 0 by hitAttr — not a failed cook. Non-finite is refused, naming this param, because a NaN cap is a broken expression rather than data. Ignored, and not evaluated, when mapping is not 'raycast'. |
| `missCountAttr` | string | `""` |  |  |  | When non-empty, writes the number of missed destination points into a u32 detail attribute of this name on the output (mapping 'nearest' always writes 0 — every point is assigned). Empty = don't record. For which points those were, see hitAttr. This is a reporting slot whose shape this node picks (u32, tuple 1), so a name the input's DETAIL domain already holds under a different shape is REFUSED rather than deleted and re-added — give it a name of its own (a "__" prefix marks it internal, e.g. "__missed") or removeAttribute the clash first. A same-shape column is reused and reset. |
| `hitAttr` | string | `""` |  |  |  | When non-empty, writes a per-point flag of this name onto the OUTPUT'S POINT DOMAIN (bool, tuple 1). The polarity is the HIT, not the miss — the inverse of missCountAttr, which counts the zeros: 1 means this point found a source and received a transferred value, 0 means it missed and kept its prior value (the attribute default when it had none). Every point is written, so the column never carries a stale value: mapping 'nearest' leaves it all 1 (every point is assigned), and a source with nothing to search — every triangle degenerate — leaves it all 0, since nothing was found. Feed it to filterByAttribute (comparison 'eq', value 1) to keep only the points that landed, then removeAttribute to clean it up. Two names are refused rather than written: `name`, which the flag would otherwise overwrite, and any point attribute the input ALREADY holds under a different shape — the flag's shape is this node's to pick, so writing it there would delete that column and everything in it while the cook still looked fine (hitAttr "P" would leave a point cloud with no positions). An existing bool tuple-1 column of the same name IS reused and reset, which is what keeps the flag describing THIS transfer only. On a clash, give the flag a name of its own (a "__" prefix marks it internal, e.g. "__hit") or removeAttribute the existing column first. Empty = don't record. |

## transferByIndex

Reads the `source` geometry's point attributes AT A PER-POINT COMPUTED INDEX and writes them onto the main input's points, creating or overwriting them on the output's point domain. For each destination point the `index` param resolves to a number, that number is truncated to an integer, and the source point with that ORDINAL — its position in the source's point storage, counting from 0 — is copied verbatim. This is the transfer that asks its question in the SOURCE'S ORDER rather than in space: transferAttribute's three mappings are all searches (nearest point, containing triangle, ray hit) whose answer the caller does not know, and transferAlongPath's is an arc coordinate; this one is handed the answer. It is a separate node rather than a fourth mapping because an index is not a spatial query — the params a search needs mean nothing to it, the param it needs means nothing to them, and a node whose param list decided which of two incompatible questions was being asked would be one node in name only. THE INDEX IS AN ORDINAL, NOT AN IDENTITY, and that is the trap: a filter, a sort, a resample or a partition upstream of `source` renumbers every point, and index 7 is then whatever is seventh afterwards. Nothing here can detect that. A gather that must survive a reorder has to gather on a VALUE (transferAttribute mapping 'nearest') rather than on a position in an array. WHAT IT IS FOR: a settled list whose ORDER is the answer — a lap's worth of placements, a table of archetypes, a palette, an asset roster. Picking from one uniformly is floor(mul(randomField(k), n)), picking in sequence is a counter, picking what a neighbour already chose is an attribute; every one of those produces a number, and this is the node that spends it. THE VALUES ARE COPIED, NEVER BLENDED: each column arrives with the source's own type and tuple size, so an i32 lane index stays an i32 lane index and a STRING asset id transfers intact — which is the case transferAlongPath cannot serve at all, since there is no value between two strings. WHICH ATTRIBUTES: name them in `attributes`, or leave it empty to take every point attribute of the source except the eight standard bookkeeping columns (P, rot, scale, density, boundsMin, boundsMax, color, seed) — see that param. Naming one LIFTS the exclusion, and naming P is the placement idiom: gather P and every destination point moves onto its chosen source point's position. WHERE THEY LAND: under their own names, or under `outNames`, a list parallel to `attributes` — which is what turns a NEIGHBOUR READ into one node: wire one geometry to both `in` and `source`, compute the neighbour's ordinal in `index` (on a lattice numbered s*K + k, 'the station above me' is index + K), and gather P into 'aboveP'. A self-gather reads the values the input was handed, never ones this node has already written. AN INDEX OUTSIDE THE SOURCE is read by `outOfRange` — clamp to the ends, wrap round by Euclidean modulo, or MISS. A miss leaves the destination point's prior value (the source attribute's default where the column had to be created) and is counted by missCountAttr and flagged 0 by hitAttr, exactly as a miss on transferAttribute is. AN EMPTY SOURCE MISSES EVERY POINT under all three settings, including clamp and wrap: there is no index to clamp into and no length to wrap by, and inventing one would hand every destination point a value no source point holds. A NON-FINITE index is REFUSED, naming this node and the param, because an index that could not be computed is a broken expression rather than data — see `index` for the argument and the fix. DETERMINISM IS STRUCTURAL: this node draws no randomness at all, and each destination point is answered from its own index and the source alone, so the result does not depend on cook order, on partitioning, or on how many points are in hand. Shuffling the destination shuffles the output and changes nothing else. The output keeps the destination's count, order, identities and topology — this node removes no point and adds none.

**Category:** attribute

**Inputs:** `in` (geometry), `source` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-gather-by-index.json](../graphs/basics-gather-by-index.json), [examples-brick-house.json](../graphs/examples-brick-house.json) — 2 total (`pcg graphs --node transferByIndex`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `index` | f32 | `0` |  |  | yes | Which SOURCE POINT each destination point reads, as an ordinal counting from 0. Resolved on the DESTINATION'S point domain, so a field here sees the `in` cloud's attributes and never the source's — the source is what is being read, not what the expression runs over. As a plain number it is one index shared by every destination point, which is the broadcast case (every point takes source entry 3) and is mostly useful for a table of one. AS A FIELD IT IS THE POINT OF THE NODE: floor(mul(randomField(k), n)) is the uniform pick over an n-entry source, attribute("slot") spends an index some earlier node settled, and an expression over position() gathers by where the destination point is without ever asking a spatial query to find it. TRUNCATED TOWARD ZERO (Math.trunc), not floored: 3.9 and 3.0 both name source point 3, and so do -0.5 and 0.5, because truncation collapses the whole open interval (-1, 1) onto 0. That matters only for a negative fraction, and it is why the uniform idiom is spelled with floor() — a random in [0, 1) scaled by n and floored covers every entry exactly once, while a value that can go negative needs to decide what it means before it arrives here. PRECISION: a field resolves to an f32 column, and f32 represents every integer only up to 16,777,216. An index computed beyond that lands on a neighbouring integer — the arithmetic that produced it is where the precision went, not this node, and a source that large wants an i32 attribute read straight through attribute() rather than a computed expression. NON-FINITE IS REFUSED, naming this param: NaN and ±Infinity are what a division by zero, an overflow or a floor() of a broken sub-expression produce, and they are not indices under any reading. This param does NOT take the finiteness opt-out that filterByExpression's predicate and pointNeighborhood's radius take, and the reason is the bar those meet: a stated meaning for NaN that a throw would delete. There is no such meaning here. NaN has none under 'clamp' (which end?) and none under 'wrap' (NaN modulo anything is NaN); +Infinity clamps sensibly but wraps to NaN, so even the three non-finite values disagree with each other within one setting; and any reading of NaN as a miss would have to be conditioned on `outOfRange`, making finiteness a property of a SIBLING PARAM'S VALUE rather than of this param, which is exactly the ambiguity the guard exists to prevent. If a broken index should miss rather than fail the cook, say so explicitly: map it to a sentinel outside the source — e.g. -1 — with a select() in the expression, and set outOfRange to 'miss'. That is a decision the graph states rather than one this node guesses. |
| `attributes` | stringList | `[]` |  |  |  | Source POINT attributes to gather, in any order. AN EXPLICIT LIST IS WHAT TO WRITE WHEN THE ANSWER MATTERS: every name here is gathered, and naming one of the eight standard bookkeeping columns lifts the exclusion the empty list applies — they are skipped by that rule, never forbidden by it. EMPTY (the default) means every point attribute of the source EXCEPT P, rot, scale, density, boundsMin, boundsMax, color and seed. Those eight are excluded because they are the point domain's own bookkeeping — written on every cloud in the library before anyone has decided anything — and each describes the SOURCE'S POINTS rather than whatever the source is a table of: gathering seed hands two destination points the same identity and then drives randomness with it, P moves the destination cloud, rot and scale overwrite the transform it arrived with, boundsMin/boundsMax its extent. What is left is exactly what somebody wrote onto the source deliberately — an asset id, a lane, a width, a hue, a weight — which is what an index is asking for. STRING ATTRIBUTES ARE INCLUDED by the empty rule, unlike transferAlongPath's otherwise identical rule, and the difference is the operation: that node INTERPOLATES, and there is no value between two strings, while this one COPIES, and a copied string is just a string. Gathering an asset id out of a roster is the case this node was built for, so leaving it out of 'everything' would make the default useless exactly where the node is most used. NAMING P IS THE PLACEMENT IDIOM: gather P and every destination point moves to its chosen source point's position, which is how a scattered cloud becomes a set of picks from a settled list. The one reshape this node refuses is P's own: a source whose P is not the destination's shape is refused rather than replacing the position column with something every downstream node would misread. EVERY OTHER COLUMN IS A COPY TARGET and takes the source's shape outright — an existing destination column of another type or tuple size is REPLACED, not refused, because overwriting is what a copy is (this is transferAttribute's rule, not the reporting-slot rule that governs hitAttr and missCountAttr below). A same-shape column is written IN PLACE, which is what lets a miss keep its prior value. A source with no point attributes left after the exclusions is refused rather than cooking to a cloud with nothing added, which would look like success. |
| `outNames` | stringList | `[]` |  |  |  | Where each gathered column is written, PARALLEL to `attributes`: outNames[i] receives the source's attributes[i]. EMPTY (the default) writes every column under its own name, which is the plain gather. SET, it must be exactly as long as `attributes`, and `attributes` must then be an explicit list — the empty default picks its columns by a rule, so there is nothing for a parallel list to line up with — and each is refused naming both lengths, because a short list is either a forgotten name or a name in the wrong slot. Explicit names rather than a generated prefix, pathShift's `outNames` design and for its reason: a column no node in the graph mentions is a name nobody can grep for. THIS IS WHAT MAKES A NEIGHBOUR READ ONE NODE: wire the SAME geometry to `in` and to `source`, compute the neighbour's index in `index`, and gather into a name of its own — on a lattice numbered s*K + k, index add(attribute("i"), K) with attributes ["P"] and outNames ["aboveP"] gives every station the position of the station above it, while its own P stays where it is. Without this param that read takes a setAttribute copy of P onto the source first and then a transfer of the copy. A SELF-GATHER HAS ONE MEANING: every destination point sees the values the input was handed, never ones this node has already written, because the source columns are read from the input and the destination columns are the output's own copies — so a name here MAY also appear in `attributes` (swapping two columns, or reading `v` from another point into `v`, is well defined) where pathShift has to refuse it. EACH DESTINATION IS A COPY TARGET with the source column's shape, under the same rules as without renaming: an existing column of that shape is written in place, so a MISS keeps its prior value; one of another shape is replaced; a name the `in` input does not have is created with the source attribute's default. Writing into 'P' is the placement idiom under a new spelling and is held to the same rule: the source column must be P's own shape, or the gather is refused rather than reshaping the destination's positions. hitAttr may not name any entry here. |
| `outOfRange` | enum | `"clamp"` |  | `clamp`, `wrap`, `miss` |  | How an index outside [0, sourceCount-1] is read, applied AFTER the truncation. 'clamp' (the default) pins it to the ends, so every negative index reads source point 0 and everything past the end reads the last point; nothing misses, and a source of one point answers every query with it. 'wrap' takes a EUCLIDEAN modulo — the remainder is made non-negative before it is used, so -1 reads the LAST source point and -n-1 reads the last again, not the truncated remainder JavaScript's own % operator returns (-1 % 5 is -1, which is not a point). This is the setting for a repeating table: a counter that has run off the end of a 5-entry palette comes back to entry 0, and one that ran off the start comes back to entry 4. 'miss' leaves the destination point's PRIOR VALUE untouched and flags it — the same miss transferAttribute's uv and raycast mappings produce, counted by missCountAttr and marked 0 by hitAttr. Use it when an out-of-range index means 'no answer' rather than 'the nearest answer': clamp and wrap both invent one, and a clamped index looks exactly like a real hit downstream. AN EMPTY SOURCE MISSES UNDER ALL THREE, this setting included: clamping needs an end to clamp to and wrapping needs a length to wrap by, and a source with no points has neither. Every destination point then keeps its prior value, missCountAttr counts them all and hitAttr is all zeros — the columns are still created, so the shape of the output does not depend on whether the source happened to be empty this cook. |
| `hitAttr` | string | `""` |  |  |  | When non-empty, writes a per-point flag of this name onto the OUTPUT'S POINT DOMAIN (bool, tuple 1). The polarity is the HIT, not the miss — the inverse of missCountAttr, which counts the zeros: 1 means this point read a source point and received its values, 0 means it missed and kept its prior value (the source attribute's default where the column had to be created). Every point is written, so the column never carries a stale value: with outOfRange 'clamp' or 'wrap' and a non-empty source it is all 1 by construction, since neither setting can fail to land, and an EMPTY source leaves it all 0 whatever outOfRange says. Feed it to filterByAttribute (comparison 'eq', value 1) to keep only the points that landed, then removeAttribute to clean it up. A miss cannot report itself through the gathered value — the prior value is a real value and looks like one — so this is the only per-point way to find one. Two kinds of name are refused rather than written: any column this node is WRITING a gathered value into (named in `outNames`, or — with `outNames` empty — named in `attributes` or selected by its empty default), which the flag would otherwise overwrite with a bool, and any point attribute the input ALREADY holds under a different shape — the flag's shape is this node's to pick, so writing it there would delete that column and everything in it while the cook still looked fine (hitAttr "P" would leave a point cloud with no positions). An existing bool tuple-1 column of the same name IS reused and reset, which is what keeps the flag describing THIS gather only. On a clash, give the flag a name of its own (a "__" prefix marks it internal, e.g. "__hit") or removeAttribute the existing column first. Empty = don't record. |
| `missCountAttr` | string | `""` |  |  |  | When non-empty, writes the number of missed destination points into a u32 detail attribute of this name on the output. With outOfRange 'clamp' or 'wrap' and a non-empty source this is always 0 — every point lands — so a non-zero count there means the source was empty. Empty = don't record. For WHICH points those were, see hitAttr; a count is a cook statistic and cannot be filtered on. This is a reporting slot whose shape this node picks (u32, tuple 1), so a name the input's DETAIL domain already holds under a different shape is REFUSED rather than deleted and re-added — give it a name of its own (a "__" prefix marks it internal, e.g. "__missed") or removeAttribute the clash first. A same-shape column is reused and reset. |

## transformBox

SCALES every cell's box ABOUT A PIVOT and then MOVES it — the transform of a modelling package applied to geometry that is a box, and the way a set of boxes goes from one coordinate system to another: a lattice of whole studs and plates to units, an assembly centred on its lot, a piece shrunk about its own centre. A CELL IS A POINT WITH A BOX, as in splitBox: its standard `boundsMin`/`boundsMax`, an extent in the point's OWN frame (world = P + rot * (scale * x)), read and written in the coordinates they hold. THE MAP, per box axis: x' = (x - pivot) * scale + pivot + translate, applied to BOTH faces, so a box from 2 to 6 scaled by 0.5 about 0 runs from 1 to 3, about its centre (4) from 3 to 5, and with translate -4 after either. A NEGATIVE scale MIRRORS the box about the pivot, its faces swapped so boundsMin stays the min corner; a scale of 0 leaves a box of no volume on the pivot, KEPT, never dropped. `pivotIn` says what `pivot` is, decided once per cook: "origin" (the default) a point in the boxes' own coordinates, [0, 0, 0] their origin — the cell's P (it was called "world"; that word is refused with the rename stated); "cell" a 0..1 FRACTION of the cell's OWN box per axis, placeBox's anchor reading — 0 the min face, 0.5 the centre, 1 the max face, any value between in proportion, and outside 0..1 past the face — so [0.5, 0.5, 0.5] scales every box about its own centre and [0.5, 0, 0.5] about the middle of its floor; "union" the same fraction of the BOUNDING BOX OF EVERY CELL this cook transforms (the cells `where` selects), so one pivot serves a whole assembly and boxes that touched still touch: [0.5, 0, 0.5] scales a house about the middle of its footprint — and since corners in different frames have no common box, "union" refuses chosen cells that do not share one P, rot and scale bit for bit (every piece of one grammar root does), naming two that differ. A scale about one shared pivot ("origin" or "union") keeps a tiling a tiling; a scale about each cell's own pivot opens or closes the gaps between them. `scale`, `pivot` and `translate` are vec3, plain or FIELDS resolved per cell on the INPUT (box names read the box as it arrived; a scalar broadcasts to all three), all along the box's own axes. NO ROTATION: a box stays a box only under a map that keeps its axes; to turn a cell, turn its point with transformPoints, which moves P and composes rot and scale, and the box turns with it. Every param, plain or field, is held as f32 (as every field constant is), so scale 0.4 is f32(0.4) and a plain value past f32's range is refused by name; the boxes are computed in f64 from those f32 numbers and the stored f32 corners and written as f32, a -0 face written +0 (an input face of -0 too). An input box that is inside out or not finite, and a result past what f32 bounds hold, are refused naming the cell — leave such a cell out with `where`, which passes chosen cells through EXACTLY as they arrived (0 = untouched, and under "union" not counted in the pivot box). Same points, same order, same SEEDS, every attribute (strings included), the topology and the detail attributes carried; P, rot and scale are neither read nor written (beyond "union"'s shared-frame check), so the transformed box keeps its cell's frame. CPU only, as every box node. Use it where a setBounds rebuilt both corners from box("lo") and box("hi") by one scale and one shift: the map is then stated once instead of per corner.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-apply-rules.json](../graphs/basics-apply-rules.json), [examples-facade.json](../graphs/examples-facade.json), [examples-floorplan.json](../graphs/examples-floorplan.json) — 4 total (`pcg graphs --node transformBox`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `scale` | vec3 | `[1,1,1]` |  |  | yes | The scale per box axis [x, y, z], about the pivot: 1 keeps the axis, 0.5 halves it, 2 doubles it, a negative value mirrors the box about the pivot (its faces swapped, so boundsMin stays the min), and 0 leaves a box of no volume on the pivot. [1, 0.4, 1] takes a lattice counted in studs across and plates up to units where a plate is 0.4 of a stud. As a FIELD it is resolved per cell on the INPUT (box names read the box as it arrived) and a scalar broadcasts to all three. Must be finite. |
| `pivot` | vec3 | `[0,0,0]` |  |  | yes | The point the scale is about, per box axis, read as `pivotIn` says: under "origin" a point in the boxes' own coordinates (the default [0, 0, 0] is their origin, the cell's P); under "cell" a fraction of the cell's own box (0 the min face, 0.5 the centre, 1 the max face — placeBox's anchor reading); under "union" the same fraction of the bounding box of every cell transformed. The pivot does not move: a box face on it stays where it is, whatever the scale. As a FIELD it is resolved per cell on the input; a scalar broadcasts. Must be finite. |
| `pivotIn` | enum | `"origin"` |  | `origin`, `cell`, `union` |  | What `pivot` is measured in. "origin" (the default): a point in the boxes' own coordinates, [0, 0, 0] the cell's P (it was called "world"; that word is refused with the rename stated). "cell": a 0..1 fraction of each cell's OWN box per axis, so [0.5, 0.5, 0.5] scales every box about its own centre — which opens (or closes) the gaps between neighbours. "union": the same fraction of the bounding box of EVERY cell this cook transforms (those `where` selects), one pivot for the whole assembly, so boxes that touched still touch — [0.5, 0, 0.5] scales a building about the middle of its footprint, at ground level. The chosen cells must share one P, rot and scale bit for bit (corners in different frames have no common box); cells that do not are refused, naming two. Decided once per cook. |
| `translate` | vec3 | `[0,0,0]` |  |  | yes | How far every box moves AFTER the scale, per box axis, in the output's units: [0, 0, 0] (the default) leaves it on the pivot's frame. A field reading a per-cell attribute moves each cell by its own amount — mul(attribute("lot", 3), [-0.5, 0, -0.5]) centres a lot whose box starts at [0, 0, 0] in its own coordinates (on its cell's P, not at the world's origin) on x and z. As a FIELD it is resolved per cell on the input; a scalar broadcasts. Must be finite. |
| `where` | f32 | `1` |  |  | yes | Which cells are transformed: nonzero transforms the cell, 0 leaves it EXACTLY as it arrived — no scale, no move, no check of its box (a FIELD param is still resolved, and refused if not finite, on every cell), and under pivotIn "union" not counted in the box the pivot is a fraction of. As a field it is resolved per cell, e.g. attributeIs("kind", "roof"). Must be finite. |

## transformPoints

Transforms every point: P' = R * (scale * P) + translate, with R from rotateEuler (degrees, extrinsic XYZ order — world X applied first, then world Y, then world Z; equivalent to intrinsic ZYX, three.js Euler order 'ZYX'). Composes with existing point transform attributes when present: rot becomes R * rot (quaternion product) and scale multiplies componentwise. All three params are field-capable and resolve per point on the input positions.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-transform-points.json](../graphs/basics-transform-points.json), [basics-inline-field-params.json](../graphs/basics-inline-field-params.json), [basics-reseed-a-noise.json](../graphs/basics-reseed-a-noise.json) — 34 total (`pcg graphs --node transformPoints`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `translate` | vec3 | `[0,0,0]` |  |  | yes | Translation added after rotation and scale, in world units. Field-capable (tuple 1 broadcasts). |
| `rotateEuler` | vec3 | `[0,0,0]` |  |  | yes | Rotation about the world origin in degrees per axis, applied extrinsically in XYZ order: world X first, then world Y, then world Z (equivalent to intrinsic ZYX; three.js Euler order 'ZYX'). Field-capable (tuple 1 broadcasts). |
| `scale` | vec3 | `[1,1,1]` |  |  | yes | Componentwise scale about the world origin, applied before rotation. Field-capable (tuple 1 broadcasts). |

## valueConstant

Emits a single constant number as a value item, for feeding value pins or tagging pipelines with plain data.

**Category:** value

**Inputs:** *(none)*

**Outputs:** `out` (value)

**Examples:** [basics-report-to-the-host.json](../graphs/basics-report-to-the-host.json) — 1 total (`pcg graphs --node valueConstant`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `value` | f32 | `0` |  |  |  | The number to emit. |

## volumeSample

Fills an axis-aligned box with a regular grid of points: each axis is divided into floor(extent / cellSize) cells (at least 1) and a point is placed at each cell center, then jittered inside its cell. jitter in [0, 1] scales a deterministic per-cell random offset (0 = exact centers, 1 = anywhere in the cell) and may be a field evaluated on the un-jittered centers. Bounds come from the optional input geometry's P extents when connected, else from boundsMin/boundsMax. Emits a standard point cloud.

**Category:** sampler

**Inputs:** `in` (geometry, optional)

**Outputs:** `out` (geometry)

**Examples:** [basics-volume-scatter.json](../graphs/basics-volume-scatter.json) — 1 total (`pcg graphs --node volumeSample`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `boundsMin` | vec3 | `[0,0,0]` |  |  |  | Minimum corner of the box, in world units. Ignored when a geometry is connected. |
| `boundsMax` | vec3 | `[1,1,1]` |  |  |  | Maximum corner of the box, in world units. Ignored when a geometry is connected. |
| `cellSize` | f32 | `1` |  |  |  | Requested grid cell edge length in world units — a REQUEST, not the cell you get. Each axis is divided into max(1, floor(extent / cellSize)) whole cells, so the actual cell is extent / that count. When the extent is not a multiple you get a LARGER cell (extent 20, cellSize 12 -> one 20-wide cell); when the extent is smaller than cellSize you get a SMALLER one (extent 20, cellSize 25 -> one 20-wide cell, since an axis always has at least one cell). It equals cellSize exactly when the extent divides evenly by it. Must be > 0. |
| `jitter` | f32 | `0` | 0..1 |  | yes | Per-cell jitter amount in [0, 1]: fraction of the cell size each point may move from its cell center, per axis. Field-capable (evaluated on the grid centers). |
| `seed` | u32 | `0` |  |  |  | Extra seed folded into the node seed; change it to re-roll the jitter. |

## voronoiCells

Turns a point cloud into its VORONOI DIAGRAM: one closed `polyline` primitive per site, bounding the ground that site is nearer to than any other. That is the plot, the plate, the territory and the leaf cell, and it is the node extrudePolygon has been waiting for — `caps: 'bottom'` with `sides: false` fills each cell as a slab, `caps: 'both'` raises it into massing, and a per-site height reaches it because EVERY RING VERTEX CARRIES ITS SITE'S POINT ATTRIBUTES, P excepted, which is the corner. Cells come out in a canonical order fixed by the POINTS (identity, then position bits, then seed), so reordering the input permutes nothing. THE DIAGRAM IS A PLAN: cells are computed in the XZ plane and each ring lies flat at its own site's Y, because every subject that wants this node is planar and a 3D cell is a polyhedron; the neighbourhood is measured in XZ too, since a 3D gather would collect a SUBSET of the sites the plan depends on. THE RADIUS IS A GATHER, NOT A SIZE, AND EVERY CELL IS CERTIFIED. A site's cell is built by intersecting the half-planes of the sites within `radius` of it, and that answer is the GLOBAL cell — the one the whole cloud would have given — exactly when every corner lands within `radius / 2` of the site, because a site further than `radius` away cannot be nearer than the site to anything that close to it. Read the premise as well as the conclusion: the check audits the RADIUS, against the cloud it was handed. It cannot audit the CLOUD, so a cook that withheld a site inside `radius` — a halo set too narrow is the way that happens — gets a certified cell that is wrong. This node checks that for every cell and never emits one that fails, which matters because a truncated cell is a perfectly plausible convex polygon that nothing downstream could tell from a real one. A site on the OUTSIDE of the cloud has an unbounded true cell and no radius certifies it, so the boundary of a scatter loses a ring of cells and that is the honest answer rather than a bug; `onUncertified` picks whether that is a quiet drop or a refusal. PARTITIONING is the reason the certificate exists. A cell reads stored positions and never another cell's answer, but its footprint is data-dependent and no param bounds it, so a cell of a partitioned world is exact when it holds every point within `radius` of its own rectangle, and the certificate then confirms per site that the halo was wide enough. THE HALO IS 1.5 TIMES THE RADIUS AND THAT FACTOR IS NOT SLACK. Widen the rectangle by 1.5 * `radius` — or 1.5 times the GLOBAL MAXIMUM the field can return, when `radius` is a field — clip the cloud with filterByBounds ('halfOpen'), run this node, then run filterPrimitivesByBounds on the UNWIDENED rectangle with vertex 'first' and the same 'halfOpen' boundary. The extra half is there because a cell's points are CORNERS: filterPrimitivesByBounds tests a vertex, so the rule it can express is which window holds the ring's first corner, not which holds the site — and the certificate is exactly what bounds how far apart those two can be, at `radius / 2`. So a window can be handed a cell whose site sits that far outside it, and must have gathered around that site too. One named corner decides, so a tiling can neither double-count nor gap. If the OWNER can be chosen by the site instead — which host code can do and a graph cannot, because no shipped filter tests a point attribute's position — then `radius` alone is the exact halo, and that is the width the certificate is stated in. Input TOPOLOGY IS DROPPED — the output is a new geometry whose points are cell corners, not the sites — and so are the input's primitive and vertex attributes; point and detail attributes survive. Two sites at the same position have no bisector between them, so each gets the cell it would have had alone, which is the degenerate answer stated rather than a crash.

**Category:** point op

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-voronoi-plots.json](../graphs/basics-voronoi-plots.json) — 1 total (`pcg graphs --node voronoiCells`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `radius` | f32 | `1` | >= 0 |  | yes | How far to look for the sites that bound a cell, in world units, tested STRICTLY: a site at exactly `radius` is not gathered. IT IS NOT A CELL SIZE. It is the reach of the search, and the cell it produces is either the true global cell or nothing at all. Raising it makes more cells CERTIFIABLE, at a cost that grows with its square; it never changes a cell that was already certified, which is what makes this param safe to tune. About three times the mean spacing of the cloud is a useful starting value. 0 builds nothing. As a FIELD it is a PER-SITE reach, and unlike connectPoints' radius it needs no pair rule, because a cell is decided by ONE site rather than by two: site i gathers within its own reach and certifies against half of it. A per-site reach of 0, negative or NaN builds no cell for that site. Under a partitioned cook the halo is 1.5 times this radius — or 1.5 times the GLOBAL MAXIMUM the field can return anywhere in the world, a bound to be derived rather than measured. The half is the gap between the ownership rule a graph can express (which window holds the ring's FIRST CORNER) and the one the certificate is stated in (which holds the SITE); see the node description. THAT IS A FLOOR AND NOT A HINT. Underestimating does not merely cost the seam some cells: the certificate asks whether the cell fits inside `radius / 2` and ASSUMES it was handed every site within `radius`, so a halo that withheld one breaks the premise somewhere the node cannot look, and the cell it then certifies is WRONG rather than absent. The error is bounded by how much was withheld, which makes it small, plausible and silent — the worst of the three. |
| `onUncertified` | enum | `"drop"` |  | `drop`, `refuse` |  | What to do with a site whose cell cannot be proved global. 'drop' emits no cell for it and carries on, which is the default because a site on the OUTER BOUNDARY of any finite cloud has an unbounded true cell that no radius certifies — refusing there would make the node unusable on a plain scatter. 'refuse' stops the cook naming the site's position, the reach its cell actually needed and the radius that would cover it; reach for it when the cook must produce a cell for every site, such as a partitioned world whose seam cells matter or a plot layout that downstream code will index, so that a missing cell is an error rather than a hole discovered later. Neither setting changes a cell that IS certified: the two differ only in what becomes of the ones that are not. |
| `areaAttr` | string | `""` |  |  |  | Name of an f32 PRIMITIVE attribute receiving each cell's area in square world units, measured in the XZ plane on the exact corners the certificate accepted. Empty (the default) writes none. It is the natural key for a plot layout — filterPrimitivesByAttribute drops the slivers, and a promoted area drives a per-lot height — and it is the cheapest way to see a diagram going wrong, since a cell far larger than its neighbours is a site whose competitors were out of reach. The shape is this node's to pick (f32, tuple 1), so the only name it can collide with is `primtype`, which is refused by name. |
| `uncertifiedAttr` | string | `""` |  |  |  | Name of a u32 DETAIL attribute receiving how many sites got no cell — because they failed the certificate, because their reach was not positive, or because the polygon collapsed below three distinct corners. `radius: 0` reports every site rather than none, which is the reading that tells you nothing was built. Empty (the default) writes none. Meaningful under `onUncertified: 'drop'`, where it is the difference between a diagram that lost its outer ring — expected, and roughly the hull of the cloud — and one that lost most of its cells because the radius is too small. Read it against the input's point count rather than alone. |

## writeCurveFrame

Writes a full orthonormal frame — `tangent`, `curveNormal` and `curveBinormal` (f32 tuple 3) — at the points of every polyline primitive, keeping the points, their attributes and the topology exactly as they arrived. The tangent is the same central difference writeTangents writes, from the same shared code, so the three columns are guaranteed mutually perpendicular rather than nearly so. WHY IT EXISTS: orientAlongVector fixes the roll around a direction with an `up` hint, and a CONSTANT up cannot follow a curve that turns over — as the tangent passes through the up vector the roll flips a half turn, and everything placed along the curve (a radial spike, a chain link, a bracket) snaps round with it. The normal here is carried ALONG the curve instead of recomputed from a world axis: it starts perpendicular to the first tangent and is transported point to point by double reflection, which is the rotation that moves it as little as each step allows. Feed it back in as orientAlongVector's `up` — field-capable for exactly this — and the roll varies smoothly however the curve turns; combine `curveNormal` and `curveBinormal` with cos and sin of an angle to aim anything radially around the path. THE FRAME IS NOT LOCAL: a point's normal depends on every point before it along its path, so this must run BEFORE anything that splits a path across cook cells or partitions it — the same curve arriving as two pieces gets two unrelated frames. A CLOSED path does not come back seamless: transport around a loop returns rotated by a residual angle (the holonomy of that curve), so the frame either side of the seam differs, and no local rule can fix it. That is a property of closed curves rather than a defect, and it is left visible instead of smeared out. Degenerate points follow writeTangents: a point whose neighbours all coincide gets a zero tangent and is skipped by the transport, a point in several polylines takes the last one in primitive order, and unreferenced points get [0, 0, 0] on all three. AN OPT-IN FOURTH COLUMN, `curvatureName`, reports the CURVATURE VECTOR dT/ds beside the frame — how hard the curve turns, which the frame's three axes describe the orientation of but never the amount of. It is here rather than in a node of its own because it is the same central difference of the same tangents over the same arc tables, and computing it twice is how two nodes drift apart; it is opt-in because it is a different quantity from a frame, and a graph that wants only the roll should not pay for it. Local corner radius is `1 / length(attribute("curvature"))`, and a signed turn is that vector dotted with whichever axis you mean by 'right'.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-stations-on-a-path.json](../graphs/basics-stations-on-a-path.json), [examples-rig.json](../graphs/examples-rig.json) — 2 total (`pcg graphs --node writeCurveFrame`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `tangentName` | string | `"tangent"` |  |  |  | Attribute for the unit tangent (created, or reset when it already exists as f32 tuple 3). The default matches what pathResample and splineSample emit, so a path that already carries tangents has them rewritten to identical values. |
| `normalName` | string | `"curveNormal"` |  |  |  | Attribute for the transported normal. NOT called 'normal' deliberately: surfaceSample writes a surface `normal` of the same shape (f32 tuple 3), and an identical shape is exactly the case a reporting slot ACCEPTS — so that name would be quietly reset in place, and a graph that samples a surface and frames a curve would have one silently overwrite the other. |
| `binormalName` | string | `"curveBinormal"` |  |  |  | Attribute for the binormal, tangent cross normal — the third axis of the frame. Written here rather than left to the consumer because recomputing it downstream from two f32 columns is where a frame stops being exactly orthonormal. |
| `curvatureName` | string | `""` |  |  |  | OPT-IN REPORT: name of an f32 tuple-3 point attribute receiving the CURVATURE VECTOR dT/ds — the rate the unit tangent turns per unit of arc length, pointing toward the centre of curvature. Empty (the default) writes none and the output is byte-identical to a cook without it. A VECTOR rather than a scalar because in 3D the scalar is the incomplete answer: the magnitude is \|dT/ds\| = 1/R (`length(attribute("curvature"))`, and the local radius is its reciprocal), while the SIGN of a turn only exists relative to some reference axis, which no curve carries on its own — take it against whichever axis you actually mean with `dot`, most often a level right vector built from the tangent and world up. Computed from the SAME neighbours the tangent's own central difference used, so the two columns describe one discrete curve rather than two slightly different ones, and a closed path wraps exactly as the tangent does. The divisor is the arc length between the two tangents being differenced — the two segments meeting at the point, and at an open path's END a HALF segment, because the tangent there is that segment's chord direction and so belongs to its midpoint rather than to its far end. Zero where it cannot be measured: at a point whose own tangent or either neighbour's is zero (a degenerate point), at an unreferenced point, and at every point of a closed loop of two distinct points, whose two neighbours are the same point. Zero on a straight too — but that is the measurement rather than the absence of one. SAMPLE THE PATH FOR THE CURVATURE YOU WANT TO READ, because more samples is not better here: this is a SECOND difference of f32 positions, so halving the step halves the signal while leaving the position quantization where it was, and past a point the noise wins. Measured against an analytic parabola, the error falls to about half a percent and then climbs back — 1.4% at 100 samples, 0.5% at 200-500, 2.9% at 1000, 12% at 2000. The useful rule is to keep the sample step somewhere near a hundredth of the smallest radius you care about and no finer; resampling a curve to a step far below that makes its curvature worse, not sharper. NOTE THAT normalize(curvature) IS THE FRENET NORMAL, which is NOT what `normalName` writes — the Frenet normal is undefined on a straight and flips a half turn through an inflection, which is exactly why the frame here is transported instead. Same reporting-slot rule as the three axis names: a column of a different shape under this name is refused rather than deleted and re-added, and it may not repeat one of the axis names. |

## writeTangents

Writes a unit `tangent` (f32 tuple 3) onto the points of every polyline primitive, keeping the points, their attributes and the topology exactly as they arrived — the output is still a path. This is the tangent source for paths that were never spline-sampled: splineSample emits `tangent` only for the new points it creates, so a path built with pointsToPath has none, and orientAlongVector (which reads a direction field, typically the tangent attribute) has nothing to consume. The tangent at a point is the normalized central difference between its neighbours along the path, which stays smooth through corners; at the ends of an open path it is the adjacent segment direction, and a closed path wraps around. When the two neighbours coincide — a hairpin, where the path doubles back on itself — the forward segment direction stands in, pointing the way the path LEAVES the point. A point whose neighbours all sit on top of it, and any point not referenced by any polyline, gets [0, 0, 0] — orientAlongVector deliberately leaves a zero direction's rot untouched. A point visited by more than one polyline takes the tangent of the last one in primitive order. Any node that can REMOVE points drops topology — filterByDensity, filterByBounds, filterByAttribute, filterByExpression, selfPrune, partitionByAttribute — and so do mergePoints and repeatPoints, so run this before them, not after. Category is not the rule: projectToPlane is categorised `filter` but preserves topology, and filterByAttribute drops it even when its predicate keeps every point.

**Category:** attribute

**Inputs:** `in` (geometry)

**Outputs:** `out` (geometry)

**Examples:** [basics-orient-along-path.json](../graphs/basics-orient-along-path.json), [basics-bridge-two-paths.json](../graphs/basics-bridge-two-paths.json), [pipeline-1-boundary.json](../graphs/pipeline-1-boundary.json) — 10 total (`pcg graphs --node writeTangents`)

**Params:**

| Param | Type | Default | Range | Enum | Field | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `name` | string | `"tangent"` |  |  |  | Attribute to write (created, or reset when it already exists as f32 tuple 3). The default 'tangent' is the name splineSample emits and the one an orientAlongVector direction field usually reads. The shape is this node's to pick, so a name the input's point domain already holds under a DIFFERENT shape is REFUSED rather than deleted and re-added — writing it would destroy that column and everything in it while the cook still looked fine. Give the tangents a name of their own, or removeAttribute the clash first. 'P' is refused outright, same shape or not: it is what the tangents are computed from. |
