Skip to content

ByteTerrace/Puck / .claude/skills/rendering

rendering

Verified

Maps Puck's SDF renderer and GPU code: mapCore, mesh bake, HLSL kernels, sdf-isa.hlsli, SdfOp, C#/HLSL layouts, world.shaders.reload, field scopes, GPU cost and occupancy. Sculpting: sdf-authoring.

FileKindSize
SKILL.mdskill md139.7 KB
evals/g02-ao-edit-has-no-effect/graders/ambient-is-a-separate-dispatch.mdmarkdown140 B
evals/g02-ao-edit-has-no-effect/graders/isolate.mdmarkdown84 B
evals/g02-ao-edit-has-no-effect/graders/reload-loop.mdmarkdown79 B
evals/g02-ao-edit-has-no-effect/graders/right-file.mdmarkdown96 B
evals/g02-ao-edit-has-no-effect/graders/skill-fired.mdmarkdown36 B
evals/g02-ao-edit-has-no-effect/graders/views-only-reads.mdmarkdown287 B
evals/g02-ao-edit-has-no-effect/prompt.mdmarkdown413 B
evals/g03-framerate-after-placements/graders/budget.mdmarkdown70 B
evals/g03-framerate-after-placements/graders/capacity-growth.mdmarkdown132 B
evals/g03-framerate-after-placements/graders/counted-work-not-wall-clock.mdmarkdown215 B
evals/g03-framerate-after-placements/graders/counters-gpu.mdmarkdown72 B
evals/g03-framerate-after-placements/graders/quality-knobs.mdmarkdown119 B
evals/g03-framerate-after-placements/graders/skill-fired.mdmarkdown36 B
evals/g03-framerate-after-placements/prompt.mdmarkdown371 B
evals/g04-hand-written-isa-define/graders/encoding-probe.mdmarkdown73 B
evals/g04-hand-written-isa-define/graders/generated-from-the-csharp-model.mdmarkdown138 B
evals/g04-hand-written-isa-define/graders/name-follows-the-enum-member.mdmarkdown135 B
evals/g04-hand-written-isa-define/graders/regenerate-verb.mdmarkdown98 B
evals/g04-hand-written-isa-define/graders/skill-fired.mdmarkdown36 B
evals/g04-hand-written-isa-define/prompt.mdmarkdown201 B
evals/g06-extra-map-call-sites/graders/each-site-is-an-inlined-copy.mdmarkdown110 B
evals/g06-extra-map-call-sites/graders/register-pressure.mdmarkdown74 B
evals/g06-extra-map-call-sites/graders/reuse-through-a-loop.mdmarkdown119 B
evals/g06-extra-map-call-sites/graders/rolled-loop.mdmarkdown65 B
evals/g06-extra-map-call-sites/graders/skill-fired.mdmarkdown36 B
evals/g06-extra-map-call-sites/prompt.mdmarkdown234 B
evals/g07-abi-change-with-reload/graders/both-sides-change-together.mdmarkdown103 B
evals/g07-abi-change-with-reload/graders/needs-a-rebuild.mdmarkdown113 B
evals/g07-abi-change-with-reload/graders/reload-compiles-kernel-sources-only.mdmarkdown118 B
evals/g07-abi-change-with-reload/graders/skill-fired.mdmarkdown36 B
evals/g07-abi-change-with-reload/graders/sync-pairs.mdmarkdown252 B
evals/g07-abi-change-with-reload/prompt.mdmarkdown192 B
evals/g08-dynamic-transform-capacity/graders/capacity-does-not-grow.mdmarkdown138 B
evals/g08-dynamic-transform-capacity/graders/fix-the-emission.mdmarkdown124 B
evals/g08-dynamic-transform-capacity/graders/identity-slot-is-a-bug.mdmarkdown117 B
evals/g08-dynamic-transform-capacity/graders/skill-fired.mdmarkdown36 B
evals/g08-dynamic-transform-capacity/prompt.mdmarkdown238 B
evals/g10-hard-op-in-one-kernel-only/graders/cpu-interpreter.mdmarkdown74 B
evals/g10-hard-op-in-one-kernel-only/graders/encoding-probe.mdmarkdown73 B
evals/g10-hard-op-in-one-kernel-only/graders/not-done.mdmarkdown71 B
evals/g10-hard-op-in-one-kernel-only/graders/parts-walk.mdmarkdown66 B
evals/g10-hard-op-in-one-kernel-only/graders/skill-fired.mdmarkdown36 B
evals/g10-hard-op-in-one-kernel-only/prompt.mdmarkdown144 B
evals/g12-hard-carve-reads-phantom-surfaces/graders/extend-the-carve-or-use-union.mdmarkdown141 B
evals/g12-hard-carve-reads-phantom-surfaces/graders/skill-fired.mdmarkdown36 B
evals/g12-hard-carve-reads-phantom-surfaces/graders/subtraction-exact-only-near-its-subject.mdmarkdown115 B
evals/g12-hard-carve-reads-phantom-surfaces/prompt.mdmarkdown217 B
evals/g13-hard-wrap-each-primitive-in-a-scope/graders/clamps-are-bounds-not-cost.mdmarkdown101 B
evals/g13-hard-wrap-each-primitive-in-a-scope/graders/make-the-primitive-lipschitz.mdmarkdown138 B
evals/g13-hard-wrap-each-primitive-in-a-scope/graders/scope-is-a-per-sample-cost.mdmarkdown88 B
evals/g13-hard-wrap-each-primitive-in-a-scope/graders/skill-fired.mdmarkdown36 B
evals/g13-hard-wrap-each-primitive-in-a-scope/graders/skips-early-out-and-rigid-planning.mdmarkdown110 B
evals/g13-hard-wrap-each-primitive-in-a-scope/prompt.mdmarkdown167 B
evals/g14-hard-two-lanes-both-added-an-op/graders/ci-checks-only.mdmarkdown122 B
evals/g14-hard-two-lanes-both-added-an-op/graders/fingerprint-rewritten.mdmarkdown100 B
evals/g14-hard-two-lanes-both-added-an-op/graders/generate-verb-or-build.mdmarkdown116 B
evals/g14-hard-two-lanes-both-added-an-op/graders/skill-fired.mdmarkdown36 B
evals/g14-hard-two-lanes-both-added-an-op/prompt.mdmarkdown207 B
evals/g15-signed-modulo-on-vulkan/graders/driver-answers-wrongly.mdmarkdown172 B
evals/g15-signed-modulo-on-vulkan/graders/lift-and-wrap-as-uint.mdmarkdown121 B
evals/g15-signed-modulo-on-vulkan/graders/skill-fired.mdmarkdown36 B
evals/g15-signed-modulo-on-vulkan/prompt.mdmarkdown353 B
evals/g16-per-pixel-field-view/graders/no-field-walk-in-a-pixel-kernel.mdmarkdown203 B
evals/g16-per-pixel-field-view/graders/sample-a-lattice-through-the-bake.mdmarkdown164 B
evals/g16-per-pixel-field-view/graders/skill-fired.mdmarkdown36 B
evals/g16-per-pixel-field-view/graders/slice-verb.mdmarkdown83 B
evals/g16-per-pixel-field-view/prompt.mdmarkdown311 B
evals/g17-new-bake-source-stale-meshes/graders/identity-follows-the-calls.mdmarkdown436 B
evals/g17-new-bake-source-stale-meshes/graders/names-mesh-identity.mdmarkdown70 B
evals/g17-new-bake-source-stale-meshes/graders/skill-fired.mdmarkdown36 B
evals/g17-new-bake-source-stale-meshes/graders/store-keyed-by-bake-identity.mdmarkdown175 B
evals/g17-new-bake-source-stale-meshes/prompt.mdmarkdown293 B
evals/moving-blend-crease-copies/graders/one-tuple-and-one-skin.mdmarkdown648 B
evals/moving-blend-crease-copies/prompt.mdmarkdown597 B
evals/shade-helper-cost/graders/one-admission-contract.mdmarkdown419 B
evals/shade-helper-cost/prompt.mdmarkdown312 B
references/authored-shading.mdmarkdown31.3 KB
references/gpu-cost.mdmarkdown37.1 KB
references/kernels.mdmarkdown34.6 KB
references/mesh-bake.mdmarkdown123.2 KB
references/mesh-gi.mdmarkdown64.6 KB
references/runtime-contracts.mdmarkdown26.7 KB
references/sync-pairs.mdmarkdown69.2 KB

references/authored-shading.md

View on GitHub
# Authored shading: admission and execution

`SdfShadeProgram` is a sealed presentation program with a private constructor.
`Compile` is its only admission door: expressions become typed SSA in dependency
order, exact binary32 arithmetic folds, commutative operands sort, common values
share a register, and only surviving outputs emit instructions. The world
vocabulary's `WorldShadeLowering` uses the ordinary parser, lexical scopes,
template/function expansion and compile-time loops; it does not run a second DSL.

The stamp and allowed phase reads are `SdfShadeOps.Inputs`; output members and
types are `SdfShadeProgram.OutputType`. A light's direction, reach, probe share
and visibility are evaluated once (`sdfLightInputs`) and read by both the default
response and the light phase's stamp: `light.visibility` is the share the default
response lets through (a cascaded directional's slot shadow; for any other
directional or point light the probes' share times the ambient occlusion; one
otherwise), `light.probeShare` the probes' share alone and `light.occlusion` the
surface's ambient occlusion
([decision](../../../../docs/decisions/rendering.md#global-illumination)). There is no author buffer address or
neighbour read. Runtime parameters occupy a separate typed block. Structural
constants enter code; runtime data does not. Canonical words, parameter layout
and the live semantics fingerprint determine identity. Author names are reporting
metadata. Canonical documents retain a flat dependency-ordered value graph, so
common expressions do not expand exponentially when serialized.

A palette row's `shade` list composes programs into one definition before
admission (`WorldShadeLowering.Program`): each element lowers into the same
outputs and parameters in order, a later output replacing an earlier one, and
while an element lowers its surface reads of `material.*` and `surface.normal`
resolve to the surface outputs the elements before it wrote
(`WorldShadeLowering.ReadComposed`). An element may be an admitted program held
as a value, such as `base.shade` in a function that wraps a row: its canonical
values expand back into expressions and its parameters take fresh slots
(`WorldShadeLowering.Import`). So a surface treatment (terrain bands) and a
light response (cel) are one program with one identity, and admission prices the
composition as one. Only the surface phase chains; the light and compose phases
read the composed surface through `surface.albedo` and its siblings.

## One program, one row

A world holds each program once, in its root `shades` table, under its identity
(`ShadeReference.KeyOf`: the definition's name, a slash and the SHA-256 of its
compact canonical JSON); a palette row, a look case and `render.shade` each
write that key ([decision](../../../../docs/decisions/rendering.md#authored-shading)).
The invariant is that every use a consumer reads holds its program, and the
program is the one its key names. The places that keep it:

- **Lowering.** `WorldShadeLowering.Lower` answers a key, and the compilation
  keeps each program once (`ProgramsOf`), with each program expression's
  identity in that compilation (`CacheKeyOf`: a template call's template and
  evaluated arguments, a value by its value, a list by its elements), so a
  palette row a template repeats lowers once and costs a key a use.
  `WorldShadeLowering.Import` reads a key as the program this compilation
  lowered under it. `WorldDocumentEmitter` writes the compilation's programs as
  the root's `shades`; `WorldDocumentMembers` hoists a program written inline
  into the table, keeps the rows a whole document's uses name and refuses a key
  no row holds.
- **Composition.** `WorldDocumentBasis` adopts `shades` rows whole: equal keys
  are equal programs, so layers and sibling imports never merge one member by
  member.
- **The model.** `ShadeReference` reads a key alone or a whole program, and
  writes its key. `WorldDefinition.ShadesRaw` writes the table derived from the
  uses (`WorldShadeTable.Of`), so a row nothing names is dropped and a use
  holding its program (a mutation's inline program) carries it.
- **Resolution, the one door.** `WorldStateDocumentValues.TryResolve` and
  `TryResolveGraph`, which every door that turns bytes into a live world runs,
  call `WorldShadeTable.TryResolve` first: every key-only use takes its program
  from the table, and a key the table does not hold, or a row whose key is not
  its program's identity, is refused by path. `ShadeReference.Definition`
  throws on a use no door resolved, so a reader that skipped the door fails
  loudly rather than shading with the default. A projection carries the table
  (`WorldProjectionDocument.Shades`) because its prototype bodies travel as
  content-addressed objects that name their programs.

The table is a document shape only. Admission, `DeclaredShadeMaterials`,
`world prepare`, the publication door and the specialized kernels see programs
by content and identity as before, and a definition object shared by a key's
uses is compiled once (`SdfShadeProgram.Compile`'s per-instance table). The
bake never reads a program, so the table leaves the bake identity alone.

`WorldShadeLowering` binds each runtime argument through an immutable typed view;
integer expectations cross `let`, `select`, conditional and function bindings.
One source argument may supply float and uint views without changing either slot.
Admission labels live parameters by their output uses, ignoring declaration order
and dead slots; symmetric uses order their data consistently. Each slot's label
recomputes only the nodes that reach it. Raw definitions cross the same null,
type, shape and checked-arithmetic guards in `Compile`.

`Compile` answers a source equal in content to one admitted under the running
code revision with that program, or the same refusal, without compiling again:
a document change rebuilds its object graph, so the validator and presentation
see fresh definitions of unchanged programs on every edit. The key is
`SdfShadeProgram`'s private `SourceKey`, which deconstructs every source record
positionally; a positional member added to a source type is written there or
the build fails. Callers hold no shade cache of their own.
`world.counters sdf.shade` counts requests, compiles and content reuses.

The canonical SSA receives deterministic register allocation into the named
set bounded by `MaxRegisters`. Evicted pure values are rematerialized from their
dependencies; admission prices that final instruction stream. Operands held by
an enclosing expression cannot be evicted, and a destination may reuse its dying
source. Output masks write phase outputs at each defining instruction, before a
temporary is reused. Excess held operands or work are refused, never spilled into
an interpreter array. The generated stamp,
registers and outputs are named fields selected by constant-index helpers; every
decoded register field is masked. CPU compilation does not prove zero driver
spill; a driver's pipeline statistics do, read per device.

`SdfShadeOps.Table` owns the op names, arities, helper-closed work and HLSL
templates. `SdfShadeHlsl` derives both the interpreter switch and straight-line
emission from the same typed functions. Results and shared float helper returns
are `precise`; no contraction or reassociation is permitted. Host folding is
limited to exact IEEE arithmetic, comparisons and literal vector construction;
transcendentals stay on the device. Integer conversion is explicit: `quantize`
floors then bitcasts, and `hash` consumes unsigned bits. The shared stage
sanitizers replace non-finite outputs with the value the stage holds for that
output, clamp domains and normalize normals. A light phase's assigned outputs
(`SdfShadeProgram.AssignedOutputs`, the light and compose phases' fourth header
word, a constant per arm in a specialized kernel: `sdfShadeAssigned`) are terms
the default response never computes (`sdfLightResponse`'s `replaced`), so a cel
band pays for no GGX lobe it discards, and a non-finite authored light term falls
back to no light. `SdfShadeHlsl.Invocation` generates the surface, light and compose doors
used by both the views and glass kernels. Glass supplies contact and thickness;
authored roughness drives both its light response and its optical frost and
environment. The standard water program keeps the underlying glass smooth while
its reveal supplies foam, selected by the `flow` template's structural glass argument.
The frame operations share the old layers' slot and transformed-static-draw
conventions. Each executed instruction increments `sdfWorkSteps`.

The standard programs live in `worlds/standard/shading.puck`, called by the
foliage, water and styles libraries and the debug world's exhibits; the terrain
program (`terrain`, laid on a row by `terrainMaterial`) lives with the terrain
library in `worlds/standard/terrain.puck`.
`world.shade programs|layers` selects programs (the default) or the old layers
for comparison. A program that omits the surface phase keeps the material's
layers as its surface (`sdfShadeHas(binding, 0u)` in the views and glass stages,
`SdfShadeProgram.Authors` on the CPU); the standard's `cel` relies on it. While
`world.toon off` suppresses every cel style, `sdfShadeBinding` marks a styled
material's binding unstyled (`sdfToonAuthored`), and `sdfShadeHas` reads its light
and compose phases as omitted. A material with no program inherits `WorldRenderDefaults.Shade`
(`render.shade`); `world.shade default <program|document>` selects an admitted
named scene program or restores that document default. `SdfFrameBlock.WriteShadeDefault`
carries its identity and parameter range; `SdfWorldTables.PackShadeDefault`
uploads its code and parameters after the scene's appearance words.

`SdfAppearance.Pack` alone places admitted programs in the appearance tail.
Its material stride is generated from `MaterialVectorsPerEntry`. Row 32 carries
program and parameter ranges; row 33 carries demand and read flags. All program
operands and shape side-table addresses are slice-relative. `sdfShadeRead` checks
the relative range and the enclosing allocation before reading; shape helpers
receive a relocated address only after their complete side table passes it.
The shade fingerprint covers templates, generator code and the embedded field
helper include closure. It joins the renderer stamp, not the field identity.

Costs are checked sums over allocated instructions. `SdfShadeCost.Shape` charges
convex vertices, ellipse bisection, and every sweep strand/sample/refinement;
the ellipse and sweep loop bounds are generated from the evaluator constants.
`PixelWork` includes the bounded light walk, default phases and fixed stage work.
`MaxOps` bounds allocated instructions separately from weighted work. Admission
checks the allocated phases' `PixelWork` at `MaxLights` for a complete 8x8 group,
including both glass interfaces, against `MaxWork`. This admission bound is provisional;
it is not a measured timeout margin. `SdfShadeDispatch.Plan` partitions the full
padded extent into whole groups under that bound and the backend group-count
limit, pricing a pixel's walk at the lights its view's mask holds
(`SdfLightSelection`, which every tile's walk narrows) and the bound screens, and
pricing the tier the residency records the frame with (`SdfWorldResidency.ShadeTier`,
an `SdfShadeTier`): no program for the plain kernels, a specialized selection's
straight-line arms (`SdfShadeStraight.Costs`: each canonical value once, without the
interpreter's `SdfShadeOps.DispatchWork`), the interpreter otherwise. A plan bounds
its own tier and every cheaper one, and `SdfShadeSlots.RecordSelection` refuses a
plan with a costlier tier's kernels; `PrepareShade` invalidates the shading passes
whenever the tier grows costlier, while a publication moves to a cheaper tier and
invalidates nothing. A binned views pass records the plan its bins pass last
committed (`SdfWorldPasses.CommitShadePlan`, `ShadePlanOf`), so it advances by the
widths its arguments hold while the bins pass stands, as after a publication.
Its `Record` door pushes each job's first group; both recorders use it.
The shared pixel entry remaps that ordinal to the original grid, preserving the
views filter's local lanes and barrier. `SdfWorldResidency.InFlightShadeIdentities`
holds each submission's identities on the residency that recorded it, until a
proof of completion removes them, and never asks a fence: a reusable slot fence
reads signaled after an abandoned submission and after a loss's teardown drain
alike. `SdfShadeSlots` is the one door: a recording captures its residency and
plan, only a pass that drew is armed (`ShaderPipelineRenderNode.SubmitPackageReadbacks`),
and the node's wait of the slot (`IRenderGraphPackageReadback.Completed`) or a
released recorder's next package frame (`SdfShadeReleases`) completes it. A device
loss before either proof marks the submission lost, and it stays reported for the
quarantine. The quarantine and the calibration of `MaxWork` belong to the remaining
[shader plan](../../../../docs/plans/author-shaders.md).

Read flags come only from live input ops. `SdfAppearance.ResolveShadeReads`
selects reads from the active programs and inherited default or legacy layers;
emissive lanes remain independent. `SdfFrameBlock` writes clock and world lanes
only when those reads require them. Default identity and data invalidate shading;
its demand separately invalidates the surface pass. Shadow demand combines base wrap with the
program's proven wrap and tilt bounds; unproved normal or light response reach
demands every side. `sdfMaterialShadowDemand` drives cascade queries, including
the exactly opposite face for every-side demand. `sdfLightVisibility` keeps an
unqueried authored slot at zero even during a shadow handoff. `world.budget` reports admitted program identities,
author names, static cost and demand. `shade-cost` displays the sum of explicit
phase work over `MaxPhaseWork`; `shade-tier` shows a pixel's tier: grey for no
program (a program whose specialization is still compiling included), cyan
interpreted, green specialized. There are no quarantined kernels yet.

## The three views and glass kernels

Every views and glass recording takes its kernel from one door,
`SdfShadeSlots.RecordPipeline`, which asks the residency's selection:

- **Plain** (`sdf-world-views-plain`, `sdf-glass-plain`, fixed kernels compiled
  with `SDF_SHADE_EMPTY`): a frame with no active program (the lever on layers,
  or no material and no default with a program), and a frame whose programs no
  specialization has been published for yet. `sdfShadeBinding` folds to none,
  so every program branch of the stages compiles out, not only the interpreter.
- **Interpreter** (`sdf-world-views`, `sdf-glass`): only under
  `world.shaders.tier interpreted`. It costs 60 to 420 ms a frame on the debug
  world, so no edit falls back to it
  ([the decision](../../../../docs/decisions/rendering.md#authored-shading)).
- **Specialized** (`sdf-world-views.shade-<set>`, `sdf-glass.shade-<set>`,
  `sdf-world-views-shade.shade-<set>`): `SdfShadeHlsl.Specialize` spliced in as
  `isa/sdf-shade.hlsli`, each program an
  arm of straight-line `precise` phases chosen once a pixel by the identity its
  header carries (`SdfShadeProgram.IdentityVector`). An arm is emitted from the
  program's straight-line form (`SdfShadeProgram.Straight`: each canonical value
  once, without the rematerialization only the interpreter's sixteen registers
  need), and its light phase's values that read no light input (parameters,
  constants, the surface and material members) are computed once before the walk
  (`sdfShadeLightPrologue`, the arm's `Carry` function) and read from an
  `SdfShadeCarry` by every light: DXC leaves loop-invariant work inside a switch arm
  in the walk, which the hoist hand-written shading has removes. There is no interpreter arm:
  one would keep the interpreter's registers allocated for the whole kernel. The
  published set keeps recording while the frame's active programs leave it: a
  binding whose identity matches no arm binds none (`sdfShadeBinding`, under
  `SDF_SHADE_ARMS`), so an edited or added program shades as a material with no
  program, as the plain kernels shade it, until the set that holds every active
  program (`SdfShadeKernels.Covers`) publishes. A parameter value is no part of
  an identity, so a parameter edit keeps its arm and shows at once.

A frame with active programs shades its views **in bins** while
`world.shaders.bins` is on (`SdfWorldPackage.WithBins`; the residency's
`ShadesInBins`, taken once a frame by `PrepareShade` with the selection):
`views-filter` writes each hit's filtered occlusion and shadows into a filter
record and each 8×8 tile's bin (no pixel with a program, or any) into the shade
bins; `views-bins` sorts the tiles and writes each job's indirect arguments; and
`views` shades bin zero with `sdf-world-views-shade-plain` and bin one with the
selection's `sdf-world-views-shade` (interpreter or specialization), each bin's
jobs through `SdfShadeDispatch.RecordBin`. The three passes share one plan a
frame (`SdfWorldPasses.ShadePlanOf`) and the views recording takes every bin's
kernel from one capture (`SdfShadeSlots.RecordSelection`). The binned kernels
join the pipeline set on demand (`SdfWorldPipelines.AcquiredOnDemand`). A frame
with no program, or the lever off, records the unsplit kernels above; a binned
graph records unsplit on such a frame until the rebuild its revision asks for
installs. A dispatch that runs no program (the plain kernels, the plain bin, the
filter) is one dispatch within the group-count limit: `MaxWork` bounds only
what a program adds. `[pipeline-statistics]` names the binned kernels apart, and
`world.counters gpu` counts the bins pass's tiles in its `no-program` and
`program` detail rows.

`SdfWorldResidency.PrepareShade` is the one publication door, once a frame
after packing, on the frame the passes record. It requests the frame's active
programs together with the documents' declared ones (`SdfFrame.ShadeDeclared`,
`WorldRenderSettings.DeclaredShades`, the same set `world prepare` compiles),
compiles them off the frame thread on `ShaderCompileTurns` through the World's
`ShaderCompiler` (counted in `shaders.compiler`, a hit runs no tool), reflects
and builds the pipelines (`SdfShadePipelines`), and publishes only an arrival
whose identity (programs, op fingerprint, `SdfShadeKernels.InterpreterOf`: the
kernels' content key and their sources' keys) is still requested and which
covers the active set. A set compiles the `SdfKernelSource` its kernel set
carries for views and glass (`SdfKernelSet.SourceOf`, read when the bytecode was
taken and replaced only with it), never the tree as it stands: an include the
source lacks refuses the plan, and bytecode installed without its source stays
interpreted. An overtaken or released build is retired to the catalog's
`RetiredBuilds`, disposed on the pool as it finishes and drained at device
loss and World root teardown, so neither waits on the frame thread.
A frame whose active set leaves the published one keeps it, shading the programs
it holds and every other as no program, so a frame never drops to the
interpreter's cost while an edit compiles; only a kernel reload that replaces
its interpreter key retires it. `world.iteration`'s `shaded` stage holds once
the frame's programs all have their arms (`SdfWorldResidency.ShadesWhole`).
A recording pins the set it records
with; the pin moves to its submission and drops only on a completion proof,
abandonment before submission or a device loss, and a retired set is freed only
at zero pins (or at device teardown and the residency's final idle drain).
Publication moves no revision; `world.shaders.tier` and `world.shaders.bins`,
and a tier that grows costlier (the interpreter after a specialization), alone
invalidate the shading passes, from the frame `PrepareShade` takes them on.
`world.shaders.status` lists each program's state.
`SdfShadeKernels.Plan` refuses a plan whose closure lacks the generated text: the
closure looks generated includes up by `Path.GetFullPath`'s spelling (derived
from the stage's path, `passes/../isa/`), and a key spelled otherwise silently
compiles the interpreter under the specialization's name.

## The GPU-lifetime invariants

Each names what enforces it and where that stops. A change to the shading
kernels' lifetime, publication or binning keeps all nine.

**Publication and specialization.**

1. *A specialized set is published only at a frame boundary, and only when it
   holds every active program; once published it shades the programs it holds
   and binds none for any other.* The one publication
   door is `SdfWorldResidency.PrepareShade`, which runs once a produced frame
   after the frame is packed and before any pass records, with the frame the
   passes record. A frame whose kernels a reload replaced retires the set there
   before any recording; an arrival
   publishes only while its identity (the sorted program identities, the op
   fingerprint and `SdfShadeKernels.InterpreterOf`: the kernel set's
   `SdfKernelSet.ContentKey` and the key of each specialized kernel's
   `SdfKernelSource`) is still the request and it covers the active set
   (`SdfShadeKernels.Covers`). Every views
   and glass recording takes its kernel from `SdfShadeSlots.RecordPipeline`
   alone, which reads that selection, so the passes of one frame record one
   selection.
2. *A kernel is freed only after the last submission that recorded it.*
   `RecordPipeline` pins the set before a native handle reaches the recorder; the
   pin moves to the slot's submission and drops only on that submission's
   completion proof (the node's wait of the slot, or a released recorder's next
   package frame), on abandonment before submission, or on a device loss. A
   retired set is disposed by `PrepareShade` only at zero pins; device teardown
   and the residency's final release (after `TryWaitIdle`) dispose every set.
3. *Nothing on the frame thread waits for a compile or a driver.* Compilation
   (on the shared `ShaderCompileTurns`), reflection and pipeline creation run in
   `SdfShadePipelines.BuildAsync` on the thread pool; `PrepareShade` only polls
   it. A build an edit overtook, and one still running at the residency's final
   release, is detached into the catalog's `RetiredBuilds`
   (`RetiredBuilds`), which disposes its result on the pool as it finishes; the
   sets a final release disposes are built, so their leases wait for nothing.
   The catalog outlives every residency, so the device's end drains it: a
   residency's device loss (`RetiredBuilds.Drain`) before recovery, and the World
   root's teardown (its last `Holdings` entry) while the device is alive. Where
   it stops: a device loss that reaches no live residency drains nothing (the
   World root holds its world residency for its whole life), and the residency's
   own pipeline set and a reload still in flight still wait on release
   (`SdfWorldPipelineSource.Release`, `CancelShaderReload`; the
   [frame-time findings](../../../../docs/plans/open-items.md#other-frame-time-findings) hold that).
4. *Publication changes no scene revision and no render history.* Only the
   comparison levers `world.shaders.tier` and `world.shaders.bins`, and a tier
   that grows costlier (`SdfShadeTier`, whose plans a standing pass's cheaper
   plan does not bound), invalidate the shading passes, from the frame
   `PrepareShade` takes them on. A publication moves to a cheaper tier, which a
   standing pass's plan bounds (`SdfShadeSlots.RecordSelection` refuses the
   reverse).
5. *A set compiles exactly the source its interpreter was compiled from.* A
   kernel set carries, beside the views and glass bytecode, the `SdfKernelSource`
   it was compiled from (`SdfKernelSet.SourceOf`): the stage and every include's
   text, read once when the bytecode was taken (the deployed tree's at load, a
   reload's compile plan) and replaced only with that bytecode
   (`SdfKernelSet.With`). `SdfShadeKernels.Plan` reads nothing else: every
   include comes from the source (`ShaderCompiler.Plan`'s `readInclude`), so one
   it does not hold refuses the plan, and a tree edited since cannot enter the
   set. Bytecode installed without its source refuses the specialization, which
   stays interpreted. Views and glass each specialize their own interpreter's
   source, so a reload that has installed one and not yet the other specializes
   the mixed state the interpreter runs. Where it stops: the deployed tree's
   sources are taken as its bytecode's because the build publishes them
   together; a process whose output directory is rebuilt between those two reads
   is outside it.

**Binning.**

6. *Every pass of a frame records one shading selection and one bins
   decision.* `SdfWorldResidency.PrepareShade` takes both once a produced frame
   (`ShadeSelection`, `ShadesInBins`), after publication and before any pass
   records; `world.shaders.tier` and `world.shaders.bins` only set the levers,
   which take effect there, and a lever change, never a publication,
   invalidates the shading passes. A views recording takes every bin's kernel
   from one capture (`SdfShadeSlots.RecordSelection`), which pins the set for
   the whole recording, so no bin can record with a set another bin did not.
7. *A tile in the plain bin holds no pixel with a program.* The filter
   classifies a pixel through the generated `sdfShadeBinding`, the function
   the shading kernels bind a pixel's program through, so the plain kernel only
   ever shades pixels whose binding is none, which it shades as the full
   kernel does. A tile whose pixels part between bins takes bin one, whose
   kernel shades every program the frame runs. The bins depend on the bindings
   and the visibility record alone, which the views signature (the lighting
   signature) and the visibility input's generation cover, so a views pass that
   re-records while its filter stands (a screen changed) reads bins that are
   still the frame's.
8. *Every job the views pass records reads arguments the bins pass wrote for
   it this frame, and covers its own tiles.* The three passes of one view share
   one plan a frame (`SdfWorldPasses.ShadePlanOf`, cached by its inputs), so the
   widths the bins pass reads from its pass block (`SdfFrameBlock.WriteShadeBins`)
   are the widths the views pass's jobs advance by; the argument record of bin
   `b`'s job `k` is `b × tiles + k` on both sides (`SdfShadeDispatch.RecordBin`,
   `sdfShadeArgumentWord`), and the buffer holds a record a tile a bin, so no
   plan can name a record past it. The graph orders the arguments' write before
   their indirect read (the views pass's `Dispatch`); the recorder orders its
   own clear before the filter's atomics and the offsets before the scatter.
9. *The binned storages and kernels live only while a binned graph does.* The
   filter record, the bins and the arguments are the binned fragment's graph
   storages, allocated with that graph and retired with it; the binned kernels
   are on-demand slots of the residency's pipeline set (`BuildOnDemandAsync`
   before a binned pass's recorder exists, `RequestOnDemand` when a view
   follows another residency), owned and released with the set.

Where these stop: the bins plan's widths are a pure function of the frame and
the passes' common extent, which every pass of one view shares; a recorder
that recorded a binned pass at another extent than its siblings would break
invariant 8, and no type prevents it beyond the one door all three passes call.

Check changes with the `shade-*` spelling pairs and `ShadeLoweringTests` in
`Puck.World.Transpiler.Tests`, plus `puck test` of those authored admission worlds.
The pairs compare canonical documents, program words, identities and costs.
`puck shaders generate --check` checks generated-table drift. CPU shader
compilation can check both backend formats. `SdfShadeDispatchTests` checks padded
group coverage and work bounds. GPU comparisons use non-lockstep settled stills
in one process, the tick paused (`world.rate pause`), the exposure pinned to an
explicit EV and the camera fixed (`view.override camera look`), on Direct3D 12
and Vulkan, with the debug sweep's still tolerance (`worlds/debug/sweep.json`:
a channel more than 16 levels apart, amber past 2 % of pixels). Fresh lockstep
processes do not repeat. The debug world's stills drift between captures even
paused (two back-to-back captures of one mode differ in 0.2 to 0.5 % of pixels
past the tolerance, and more as wall time passes), so a comparison reads each
cross-mode pair beside a same-mode pair taken over the same interval; confirm
the graph a still came from before it (`world.counters gpu pass <label>` names
a binned pass only while the binned graph is installed). Check backfaces
under wrap and animated normals, contact foam and static transformed flow, and
clock/world-lane/no-read cadence separately. `puck mesh identity --against`
checks that presentation changes leave the bake identity alone. Timing is read
by the [shader plan](../../../../docs/plans/author-shaders.md#the-decision-matrix)'s matrix.

`worlds/debug/shade-surface-checks.puck` isolates the shadow and glass cases:
its `shadeWrap` and `shadeTilt` state cells drive the panel's world lanes, a
blocker covers one panel, and shallow glass copies carry object-frame flow with
one rotated copy. Shadows are explicitly enabled; the minimal basis defaults
them off. Keep indirect lighting off for the isolated shadow witness, and check
the cel sphere with indirect lighting enabled separately.
`worlds/debug/shade-checks.puck` isolates cadence and the inherited default.
Use `world.row.set render shade` to select programs reading `clock`,
`lanes.world0`, or neither, and inspect the views pass while simulation runs.
The clock reader executes as ticks advance; the lane reader stands until
`shadeLane` changes; the neither-reader stands throughout. `SdfFrameBlockLawTests`
checks the corresponding clock/lane bytes and default identity directly.

Wait for `world.wait ready` before submitting simulation-routed setup commands
under lockstep. `WorldRenderProbe` includes `RenderGraphRuntime.Render` in readiness,
so it reports the dependency holding a tick, including probe convergence in a routed
view, instead of declaring a partially completed graph ready. A frame rendering
while simulation commands wait is not evidence of a device hang; inspect that
reason and the advancing work counters first.

Keep lockstep enabled from startup for fresh-process animation comparisons.
Pausing the boot world does not pause routed instances: inspect
`world.instance.status` and pause their schedules too when their lighting must
stand. A `world.wait captures` answer only means no request remains pending;
confirm the requested PNG and its capture completion line. A refused request
also drains that queue, including when convergence outlasts the host's capture
hold budget. After an unknown control outcome, read the current state before
moving a camera or issuing the next capture.

`latticeGradient` uses `sdfLatticeNoiseGradient3`, shared with the old flow layer.
`shape` is a coverage-distance operation: within its footprint neighbourhood it
evaluates the admitted primitive, and outside its bounding box it returns the
positive box lower bound, as the paint path skips that exterior. It is not an
exact outside-distance query. Its op records a footprint read, packs the bounds
with the descriptor, and charges the full helper even when the early-out wins.
`SdfPaintShape.Of` enforces primitive admission for both paints and shade shapes;
captured scale and primitive rotation both reach their point evaluation. Shade
definitions normalize through `SdfShadeShape.Canonicalize`, including convex
profile start and unused controls, before their canonical document is written.
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall