ByteTerrace/Puck / .claude/skills/rendering
rendering
VerifiedMaps 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.
references/sync-pairs.md
View on GitHub# C# ↔ HLSL sync pairs
The field catalogues define the enum rosters, reader actions and shader operand reads.
Arithmetic helpers and several packed records still have C# and HLSL implementations. Back to
[../SKILL.md](../SKILL.md).
**A parity law states what is exact and what is a tolerance.** Discrete results
(which instance, triangle or probe answered, a miss, every flag a later stage
branches on) match exactly; floats (distances, positions, weights) match within a
bound derived from scene scale and float precision, with a near-tie rule where two
candidates lie inside that bound. The GPU's evaluation order and fused multiply-add
make bit-identical floats unattainable, so a brief that says "the same values"
without that split stops its lane on rounding (a GPU probe-trace law failed on a
2e-5 difference in a hit distance). The gather law's weights within 0.002 are the
model.
**Generate the field dispatch and operand reads from the model.**
`src/Puck.SdfVm/Assets/Shaders/Sdf/isa/sdf-isa.hlsli` is generated by
`SdfIsaHlsl` (in `Puck.SdfVm.Model`, which compiles no shader) from the live C# model: every member of `SdfOp`, `SdfShapeType`, `SdfBlendOp`, `SdfLift`,
`SdfNoiseFlavor`, `SdfCellMode`, `SdfAxis`, `SdfPlane` and `SdfWallpaperGroup` (every enum an instruction lane
carries, the axis and plane selectors included), the header lanes as accessors (`SDF_INSTRUCTION_SHAPE(header)`,
`SDF_PROGRAM_MATERIAL_COUNT(header)`, `SDF_SEGMENT_COUNT(header)`, …) with the vector counts that place the headers
(`SDF_PROGRAM_HEADER_VECTORS`, `SDF_INSTRUCTION_DATA_VECTORS`, `SDF_BOUND_RECORD_VECTORS`,
`SDF_DIRECTORY_HEADER_VECTORS`), all from `SdfProgram`'s lane constants, which the packer writes through, and the
packed-layout constants marked *generated* below. A kernel reads a header lane only through its accessor and a
header's place only through the vector counts; `SdfKernelHeaderReadLawTests` refuses a swizzle or a literal
offset. An enum member's
HLSL name is its C# name in upper snake case after the enum's prefix
(`ResetPoint` is `SDF_OP_RESET_POINT`); a constant's HLSL name is listed
in `SdfIsaHlsl.Generate`. Never edit the file: change the C# and build. Every
generated declaration is in `ShaderDeclarations`' one list, which the kernel
projects' build-only reference `Puck.Shaders.Generator` writes before their
kernels compile and `puck shaders generate` writes by hand; a change that adds a
declaration and a kernel reading it builds in one pass. `puck shaders generate
--check` fails CI naming the file when it disagrees with the model. A new
ISA-owned constant or enum the kernels read joins `SdfIsaHlsl.Generate` rather
than a hand `#define`. Every numeric constant a kernel shares with C# is generated this way, the hash, mesh-record,
probe, transport, atmosphere, history, sky-environment and debug-mode constants included; a constant with no C# reader
stays a kernel `static const`. The generated vocabulary is two files: `sdf-isa.hlsli`, what the field interpreter
and the mesh bake read (the enums, lanes, layouts, the shapes' and hash's constants, the sampler filters, the
transform-slot sentinel), and `sdf-render.hlsli` (`SdfRenderHlsl`, from `SdfIsaHlsl.DeclareRender`), which includes
it and adds what the renderer alone reads (lights, exposure, the visibility record, mesh records, the irradiance
probe, temporal, glass, sky, atmosphere and debug-view constants). A renderer constant goes in the second, so it
moves no stored mesh's key; a field module includes only the first.
The generated field switches use the operand readers in `sdf-field-operands.hlsli`.
The hand-packed record lanes and masks with no C# constant still have two definitions. Pass interfaces and native record
buffers generate their declarations through `ShaderInterfaceHlsl`; their host
writers must follow those same layouts. A kernel set
agrees with the instruction set it was built with because the build refuses
bytecode stale against its sources and every include (the generated
`sdf-isa.hlsli` among them), and `puck shaders generate --check` refuses a
stale generated file. The instruction set's fingerprint
(`SdfIsaHlsl.DescribeFingerprint`) hashes the includes' layout (their stamped
`#define` lines: every integer declaration and every real the host also shares,
but not a `Tuning` real, a value no host packing or decoding reads, so retuning
one keeps the stamp and a reload accepts the kernels;
[classification](../../../../docs/reference/shaders.md#pass-interfaces)). The
glass sum scale is stamped too: the composition-owned raster pipeline encodes it and the
reloadable compute kernel decodes it, so a compute-only reload cannot change that encoding.
The
irradiance tuning reals (`BehindShare`, `NormalBias`, the depth coverage pair) are
also read by `SdfMeshIrradiance`'s CPU gather, which feeds the bounce trace as
well as `world.probe`: a shader-only retune of one lights pixels and bounces by
different values until the host is rebuilt, a lighting mismatch, never a layout
fault)
and the model's described encoding (`SdfEncodingProbe.Describe`: one builder call per
operation, shape, blend, lift and lane-enum member, and calls packing every
side table and flag, described by each packed program's integer words and,
for each input raised alone, the bits of every integer word that moves and
every float word that moves; then, for each float word that moves, the input
that moves it most, or a tie when no input beats the next by half again), so
it moves when a field,
a bitfield, a header lane, a table entry or an enum value moves;
`SdfEncodingProbeLawTests` holds the probe to every member. `puck shaders
generate` records it in `SdfIsaFingerprint.cs`, which the host reads
(`SdfIsaFingerprint.Value`) rather than describing the encoding at boot. It is
the stamp the kernels' interfaces carry (`SdfWorldInterfaces.Stamp`, the `passGroup`
variable's name in `sdf-world.interface.hlsli`);
the bake's interface (`sdf-mesh-bake.interface.hlsli`) carries the field's
fingerprint instead (`SdfIsaFingerprint.Field`, `SdfIsaHlsl.DescribeFieldFingerprint`:
`sdf-isa.hlsli`, the field dispatch includes and the packed encoding), so a renderer constant moves no bake key,
and every kernel's bytecode reflects the instruction set it was compiled against,
and a reload holds each changed kernel to the host's interface, stamp and
bindings (`SdfKernelSet.InterfaceMismatch`). `SdfFieldDeviceLawTests`
(`tests/Puck.World.Tests`, probe kernel `Assets/Shaders/sdf-field.comp.hlsl`)
runs the interpreter on Vulkan and Direct3D 12 hardware against
`SdfFieldEvaluator`, directly where it accepts a program and through an
equivalent at each point for the refused warps and displacements its oracles
describe; a new op the evaluator refuses gets an oracle there when one point
has an equivalent. Host-side law tests
(`PackLightsAndSkyLawTests`,
`WorldRenderEnvelopeLawTests`) pin only their C# half; `SdfFrameBlockLawTests`
holds the frame block's writer to the generated offsets, and
`SdfLightAndSkyLayoutLawTests` holds the lights and sky records, decoded through
their generated structures, to every value the kernels read.
C# symbols live in `src/Puck.SignedDistance` (the program model and its packed
records), `src/Puck.SdfVm.Model` (`SdfIsaHlsl`, `SdfKernelInterfaces`,
`SdfVisibility`, `ShaderDeclarations`), `src/Puck.SdfVm` (the residency, tables,
recorders, passes, meshes and kernel set) or `src/Puck.Shaders.Model/Graph`
(`SdfWorldPackage`); `puck declarations` names any one's file.
HLSL paths are under `src/Puck.SdfVm/Assets/Shaders/Sdf`. "Word" means a 32-bit
uint; "uint4" and "float4" name 16-byte vectors.
## Identity and vocabulary
| C# | HLSL | Contract |
|---|---|---|
| `SdfOp`, `SdfShapeType`, `SdfBlendOp`, `SdfLift`, `SdfNoiseFlavor`, `SdfCellMode` | *Generated:* `SDF_OP_*`, `SDF_SHAPE_*`, `SDF_BLEND_*`, `SDF_LIFT_*`, `SDF_NOISE_*`, `SDF_CELL_MODE_*` | Members are numbered densely in declaration order and no id is reserved: removing a member renumbers the ones after it, and regenerating carries the new numbers to the kernels. A new instruction takes a call in `SdfEncodingProbe`. A renamed member renames its HLSL spelling, so its kernel uses move with it. |
| `SdfAxis`, `SdfPlane` | *Generated:* `SDF_AXIS_*`, `SDF_PLANE_*` | An axis's value is the component index a kernel reads a point at. `SdfAxis` rides RepeatPolar, AxialProfile and Shear's Shape lane and RotatePlane and Shear's Blend lane; `SdfPlane` rides WallpaperFold's Blend lane and RotatePlane's Shape lane. |
| `SdfWallpaperGroup` | *Generated:* `SDF_WPG_*`; the `sdfWallpaperFoldCell` axis decode | Groups 0..16 (all 17 IUC groups). A program builds only the continuous ones (`SdfWallpaperFold.IsContinuous`). |
| `SdfBoundAlgebra` (`Compose`, `Unbounded`), `SdfDomainOps.IsUnboundedRepeat` | none: CPU-only cull analysis | The compose of operand bounds through intersection, subtraction and union that `SdfProgram.HasUnmaskableInfluence` and `CreationStampEmitter.RenderReach` both read, and the one test for a repeat with no edge. Nothing on the GPU reads a bound's algebra, only the packed radius it yields. |
| `SdfWallpaperFold` (`Fold`, `InverseCell`, `IsContinuous`, `IsUnbounded`, `LimitRefusal`, `CellRefusal`, `MaximumHexCoordinate`) | `sdfWallpaperFoldCell` and `sdfWallpaperFoldHexCell` in `field/sdf-point.hlsli` | The CPU statement of the kernels' fold, branch for branch: the lattice round (nearest even), the clamp to ±limit on a square lattice (a whole number of cells; the hex reduction is never clamped), the parity-keyed in-cell isometries and the hex axial reduction. Data0 = (cell.xy, `InverseCell`, exactly one over the cell), Data1 = (limit.xy, 0, 0); `LimitRefusal` and `CellRefusal` state what the lanes may hold. The hex reduction clamps its point to ±`MaximumHexCoordinate` first, `SDF_WALLPAPER_HEX_COORDINATE_MAX` in `field/sdf-point.hlsli`, the one hand-written constant the two share (its doc derives it from the reciprocal cap); an edit to either moves the other. Continuity is measured from `Fold` at type initialization, so a kernel change that moves a branch changes `Fold` with it. No device law compares the two directly; `SdfFieldDeviceLawTests` evaluates the fold through the interpreter for the programs it packs. |
## Program layout
| C# | HLSL | Contract |
|---|---|---|
| `SdfProgram` packed `Words`; its lane constants (`ProgramInstructionCountLane`, `InstructionShapeLane`, `SegmentStepScaleLane`, `InstancePartProgramsLane`, …) and vector counts | *Generated:* the header lane accessors and vector counts; by hand: `sdfLoadProgramLayout` in `field/sdf-layout.hlsli` and the decoders in `field/sdf-map.hlsli` | The first uint4 is the program header (instruction count, material count, data offset, material offset). Each instruction is a uint4 header (op, shape, blend, material) plus two float4 data vectors. Then the bounds table (after the instruction data), segment directory, instance directory, world segments, rigid-leaf plan, side tables and part programs, every one the field interpreter reads (`SdfProgram.FieldWords`); then, at the material offset, the appearance section: the materials, then the paints (`SdfAppearance.Pack`). The segment header's `.w`, the instance header's `.z` and `.w` and the world-segment header's `.y` are zero. Every table after the world segments is located by an absolute offset a header or an instruction carries. The layout comment at the top of `SdfProgram.cs` states each table. |
| `SdfProgram.InspectInstance` | The packed directories above | Inspection attributes instruction headers/data/bounds, instance and segment rows, rigid leaves, shape side tables and instance part bindings to their actual owner. Palettes and shared part assets remain explicit shared overhead; placement costs must reconcile to the live packed total without re-emission. |
| `SdfProgram.BoundModeNone` / `BoundModeStatic` / `BoundModeDynamic`; `SegmentRigidPlanFlag`; parked bound | *Generated:* `SDF_BOUND_*`, `SDF_SEGMENT_RIGID_PLAN`, `SDF_SEGMENT_BOUND_MASK` (`SegmentBoundModeMask`) | A parked instance packs radius −1. An instance record's `.w` is its segment range's end alone. |
| `SdfProgram.RigidLeafIdentityRotationFlag`, `RigidLeafFoldedFlag`, `RigidLeafMaxFoldRun`; folded rigid leaves | *Generated:* `SDF_RIGID_LEAF_IDENTITY_ROTATION`, `SDF_RIGID_LEAF_FOLDED`, `SDF_RIGID_LEAF_MAX_FOLD_RUN`, `SDF_RIGID_LEAF_SHAPE_MASK` (`RigidLeafShapeMask`); by hand: `sdfRigidFoldPoint` in the rigid walk | A fold run packs an extension slot (pre-run pose, quaternion, run length) and a negative bound. |
| `SdfProgram.PartPrograms.cs` (`IndependentPartTracingFlag`, entry/leaf/binding runs) | `sdf-parts.hlsli`, `sdfCanTracePartsIndependently` | The instance-directory header `.y` holds the part-table offset (zero when absent). The part-table header `.x` bits 0..30 = compiled-instance count, bit 31 = the root-union certificate (`sdfCanTracePartsIndependently`), under which the walk bounds a compiled part whole. One uint4 per instance names leaf run, binding run, `.z` = leaf count (bits 0..15), distance gain (bits 16..29, `SdfProgram.EncodePartDistanceGain`: `k` times `PartDistanceGainUnit`, the full field exactly 1, zero uncertified), bit 30 zero, and dynamic (bit 31), and `.w` the compiled scope multiplier (zero for an uncompiled entry, which has a zero count and its gain alone). Generated `SDF_PART_LEAF_COUNT_MASK`, `SDF_PART_DISTANCE_GAIN_SHIFT`, `SDF_PART_DISTANCE_GAIN_MASK` and `SDF_PART_DISTANCE_GAIN_UNIT` decode the entry; `sdfPartDistanceGain` and `SdfProgram.DecodePartDistanceGain` are the two decoders. Whole-instance and group-word rejection both retain zero-gain instances the walk does not bound; a root-union certificate proves composition only. Shared geometry reads canonical payloads. Its geometry key must include every parameter that changes the field. |
| `SdfAppearance.MaterialVectorsPerEntry`, `SdfMaterial.DefaultRoughness`, `SdfMaterial.EmissiveLane` (material row 20.z), `SdfMaterial.Glass` (`SdfGlass`, material rows 21 and 31, row 20.w) | *Generated:* `SDF_MATERIAL_VECTORS_PER_ENTRY`; by hand: `sdfMaterialLoad`, `SdfRoughnessFloorSquared`, `sdfApplyEmissiveLane`, `sdfMaterialIsGlass`, `sdfGlassContact` and the medium in `passes/sdf-glass.comp.hlsl` | Row 20.z holds the emissive lane plus one as uint bits, zero for a static emissive; `sdfApplyEmissiveLane` scales `emissive` by the saturated lane (`sdfLane`: the hit's frame slot's or the world's) in the light stage. `SdfMeshIrradiance` reads a lane-driven emissive as zero, as a static draw shades it. Row 21 holds a glass material's absorption per world unit (`SdfGlass.Absorption` of the albedo, its tint) and its index of refraction, zero for an opaque material, so a positive index says glass (`sdfMaterialIsGlass`); the glass pass applies `exp(-absorption * distance)`. Row 31 holds the medium, `SdfGlass.Scatter` and `Scattering` (the glass shows the scatter colour under the light arriving at it over `1 - exp(-scattering * thickness)` of itself), and row 20.w the contact as two half floats, its reach low and its coverage high, zero for none (`SdfGlass.MaxContactReach` keeps the reach within a half). |
| `SdfWorldPackage.GlassSumWords`, `GlassSumScale`, `GlassDepthDistanceScale`, `GlassAbsorptionScale`; `SdfWorldPackage.Parts.GlassSums` | *Generated:* `SDF_GLASS_SUM_WORDS`, `SDF_GLASS_SUM_SCALE`, `SDF_GLASS_DEPTH_DISTANCE_SCALE`, `SDF_GLASS_ABSORPTION_SCALE`; by hand: `frame/sdf-glass.hlsli` (`sdfGlassAccumulate`, `sdfGlassThicknessAt`, `sdfGlassOpticalDepthAt`, the second record's `SdfGlassFrontCountWord` to `SdfGlassNearestBackWord` and their readers), called by `sdf-mesh-glass.frag` through the mesh interface's `sdfGlassSumsRW` and by `sdf-glass.comp` through `sdfGlassSums` | Sixteen words a render-grid pixel, laid out as the visibility records are: the signed sum of each glass face's ray distance before the pixel's opaque hit in `GlassSumScale` steps a world unit, a front face subtracting and a back face adding, and the count of front faces less back faces, both two's complement accumulated with `InterlockedAdd`; then three 64-bit sums, low word first, of each face's quantized absorption times its quantized distance to the opaque hit, a front face adding, a back face subtracting, the carry added to the high word. The thickness is the matched sum plus the opaque distance per unmatched front face, clamped to the distance from the nearest front face to the opaque hit; the optical depth is each 64-bit sum over the product of the two scales. The last eight words are the second glass record, kernel-only constants: the count of front faces before the opaque hit, three entries (draw plus one, triangle) the first three claim through that count's `InterlockedAdd`, and the nearest back face as an `InterlockedMax` of its distance's complemented bits, zero for none; the clear's zero is every word's empty state. `SdfGlassSumsDeviceLawTests` mirrors the word offsets. The clear (`Parts.GlassClear`, a transfer write) and the raster record on one geometry signature, and the raster's version forwards the cleared one as preserving, so a standing raster never accumulates onto a clear it did not see. |
| `SdfMaterial.Flow` (`SdfFlow`, material rows 27–30), `SdfAppearance.FlowLaneMask`, `FlowWorldFrame`, `FlowCoverageLaneShift`, `SdfFlow.ClockPeriodSeconds`; the pass block's `SdfWorldPackage.FlowClock` (written by `SdfFrameBlock`) | *Generated:* `SDF_FLOW_LANE_MASK`, `SDF_FLOW_WORLD_FRAME`, `SDF_FLOW_COVERAGE_LANE_SHIFT`, `SDF_FLOW_CLOCK_PERIOD`, `passGroup.flowClock`; by hand: `sdfMaterialLoad` (`flowVelocity`, `flowShape`, `flowColor`, `flowResponse`, `flowSeed`, `flowControl`) and `sdfApplyFlow` in `shade/shade-flow.hlsli`, called through `sdfShadeFlow` from the light stage and the glass pass | Row 27 holds the velocity and the pattern's frequency (zero for no flow), 28 the stretch, `SdfFlow.CyclesPerClock` (a whole number, so the layer joins where the clock wraps), the tilt and the coverage, 29 the revealed colour and softness, 30 the revealed roughness and metal, the seed bits and the control word (`SdfAppearance.FlowControl`: the velocity lane plus one in the low byte, the world-frame bit, the coverage lane plus one in the byte at `FlowCoverageLaneShift`). The clock is `PresentedTick.Integrate(1, ClockPeriodSeconds) / ClockPeriodSeconds`, zero for a program without flow (`SdfAppearance.ResolveShadeReads`), and a lighting member of the cadence signature. Discrete fields (the cycle count, seed, control word) pack exactly; floats as written. |
| `SdfLanes` (`FirstWorld`, `Count`); the pass block's `SdfWorldPackage.WorldLanes`, written by `SdfFrameBlock.WorldLanesOf` from `SdfFrame.WorldLanes` | *Generated:* `SDF_FIRST_WORLD_LANE`, `SDF_LANE_COUNT`, `passGroup.worldLanes`; by hand: `sdfLane` in `frame/sdf-lanes.hlsli`, the one reader of `worldLanes`, called by `sdfApplyEmissiveLane`, `applyWeathering`, `sdfApplyFlow` and `sdfVolumeIntensityScale` | A shading-time lane index below `FirstWorld` reads the frame slot's lanes (the dynamic transform's third row), the rest `worldLanes`, which the host resolves from `render.lanes` at the presented tick (`WorldEnvironmentResolve`). `WorldLanesOf` writes zero for a frame whose materials (`SdfAppearance.ResolveShadeReads`) and volumes read none, and the value is a lighting member of the cadence signature. Bake-time lanes (`LaneErode`, `Morph`) read the slot's lanes in `mapCore` alone (`SdfLanes.IsSlotLane`). |
| `SdfAppearance.PaintVectorsPerEntry`, `MaxPaintsPerMaterial`, `PaintWinningFrame`; `SdfAppearance.PackPaint` and material row 20 | *Generated:* `SDF_PAINT_VECTORS_PER_ENTRY`, `SDF_MAX_PAINTS_PER_MATERIAL`, `SDF_PAINT_WINNING_FRAME`; by hand: `sdfMaterialLoad` (`paintFirst`, `paintCount`) and `sdfApplyPaints` in `shade/shade-layers.hlsli` | The paint table follows the materials in the appearance section, after every table the field reads. Rows: frame origin and shape type, rotation, residual scale and its smallest component, the two data vectors as the builder packs them, colour and stroke, slot and bound center, bound half-extents. All paint entries precede all paint side tables; a convex polygon or sweep names its table by an absolute vector offset. Shade programs follow the side tables. |
| `SdfProgramBuilder.MaxFieldScopeDepth`, `FlareMinScale`, `LaneErodeRaggedAmount`, `ScreenMaterialId` | *Generated:* `SDF_MAX_FIELD_SCOPE_DEPTH`, `SDF_FLARE_MIN_SCALE`, `SDF_LANE_ERODE_RAGGED_AMOUNT`, `SDF_SCREEN_MATERIAL` | `mapCore` saves each parent in a named slot and returns the ISA error hit on overflow or underflow. Its preprocessor check requires the number of slots to match `SDF_MAX_FIELD_SCOPE_DEPTH`. |
| `SdfPathProfile` / `SdfPathCompiler` / `SdfProgram.Path` | `SDF_SHAPE_PATH`, `sdfPathSolid` | Data0 = (table offset as float bits, edge count, enclosing 2D radius, half-depth); Data1 = (smooth, stroke mode, 0, 0). At most 128 edges, two uint4 each: (A.xy, B.xy), (radiusA, radiusB, 0, 0). Full kernel only; the fixed-point evaluator refuses it. |
| `SdfSampledField`, `SdfSampledSet`, `SdfProgramBuilder.SampledValues`, `SdfProgram.SampledFields`; `SdfMeshBakeBatch.WriteSampledDirectory` | `sdfSampledRegion`, `sdfSampledVoxel` over `sdfSampledValues` (`SdfWorldPackage.SampledValues`) | Data1.z holds the field's handle as uint bits, its place in `SdfProgram.SampledFields`; no voxel is a program word. The bake job's table holds a word per handle (the word its snapshot starts at, `0xFFFFFFFF` for none), then each snapshot's voxels as float bits, x fastest; only the bake kernel (`SDF_SAMPLED_REGIONS`) reads it, and the tables bind a filler. Program construction binds and validates each field's dimensions; excerpt and retained emission relocate the binding. Mesh identity hashes the frame's snapshot (`SdfFrame.Sampled`, read through its `Baked` identity, the instruction-sampled handles) in place of the handle, and a batch writes the snapshots its groups hashed, one a handle. |
| `SdfHeightField` (`ReferenceCells`, `ReferenceRows`), `SdfProgramBuilder.HeightField`, `SdfProgram.HeightFields`; `SdfFrameSampled` (`None`, `HeaderWords`), `SdfWorldTables.PackFrameSampled`; `SdfMeshDisplacement`, `SdfMeshRecord.DisplacementWord` | *Generated:* `SDF_FRAME_SAMPLED_NONE`, `SDF_FRAME_SAMPLED_HEADER_WORDS`, `SDF_HEIGHT_FIELD_REFERENCE_CELLS`, `SDF_MESH_DISPLACEMENT_WORD`; by hand: `sdfMeshDisplacementEntry`, `sdfMeshHeightAt`, `sdfMeshDisplaced` in `frame/sdf-mesh.hlsli` over `sdfFrameSampled` (`SdfWorldPackage.FrameSampled`, a World table after the field's tables and a member of the `sdf-mesh` interface) | A height field's reference is baked with every raised column's top `ReferenceCells` cells above the origin, which `sdfMeshDisplaced` assumes; its heights' handle sits in `SdfProgram.SampledFields` after every instruction's and no bake reads it. The frame's sampled table is a word per handle (the word its entry starts at, `None` for none), then each height field's entry: width and depth, the origin's three coordinates and the cell as float bits (`HeaderWords`), then the frame's heights and the previous frame's, x fastest. The draw record's `DisplacementWord` holds the handle or `None`. `sdfMeshWorldPosition`, `sdfMeshWorldNormal` and `sdfMeshPreviousPosition` (the previous heights) all displace through it. |
| ConvexPolygon and Sweep side tables | `field/sdf-shapes.hlsli` polygon and sweep decoders | Polygon packs `(offset << ConvexCountBits) | (count - 1)`, with five count bits. Sweep packs three uint4 per record (`SweepCurveVectorsPerEntry`). |
## Instruction semantics shared by both interpreters
The [op catalogue](../../../../src/Puck.SignedDistance/SdfFieldOps.cs) and
[blend catalogue](../../../../src/Puck.SignedDistance/SdfFieldBlends.cs) name the generated cases.
Every blend, and every shape both readers evaluate except the target escapes, is one formula in
[`SdfFieldFormulas`](../../../../src/Puck.SignedDistance/Formulas/SdfFieldFormulas.cs), written in the closed
expression language of `SdfFormula`. The Roslyn generator in `Puck.Analyzers` compiles that source into
itself and lowers each formula to a fixed-point method of `SdfFieldEvaluator` (`SdfX`, with the generated
`EvaluateShape` and `BlendShape` dispatch); `puck shaders generate` lowers the same objects to precise HLSL
(`sdfX`, `isa/sdf-field-shape-formulas.hlsli` and `isa/sdf-field-blend-formulas.hlsli`), folded into
`SdfIsaFingerprint.Field` and the shade fingerprint. An operand is named once per formula with its C# lane and
its HLSL swizzle, so renaming or dropping it changes both readers. A shape whose `Formula` is null is a target
escape: its `Shader` and `ShapePoint` facets name hand-written readers, and PUCKFIELD003 refuses an entry whose
`ShapePoint` says `Formula` without one, or names an escape beside one. The escapes are the side-table and
texture shapes (`ConvexPolygon`, `Path`, `Sweep`, `Glyph`, `SampledRegion`), the GPU-only star polygon
(`RegularPolygon`, `Star`), and one per-target primitive inside a formula: the ellipse's bisected projection root
(`SdfEllipse2D`, `sdfEllipse2D` in `field/sdf-ellipse.hlsli`), which needs a loop. Interval enclosures stay
hand-written facets. What generation cannot show is whether float and Q48.16 agree near a rounding tie, or
whether a formula's Lipschitz claim or enclosure is sound; `SdfFieldDeviceLawTests`' shape-formula leg reads
every formula on both backends.
| C# | HLSL | Contract |
|---|---|---|
| `GrooveUnion`, `PipeUnion`, `GrooveSubtraction`, `PipeSubtraction`; `SdfProgram.ComposeLipschitz`; `SdfFieldEvaluator.Compose` | *Generated:* the blend formulas, called by `blendShape` in `field/sdf-blend.hlsli` | Radius r = Data1.x. With h = sqrt(a² + b²): groove = max(min(a,b), r − h), pipe = min(min(a,b), h − r); the subtraction forms use max(a, −b). Compose bound hypot(La, Lb), never a program-wide √2. |
| `Morph`, `StairsUnion`, `StairsSubtraction`; `PushFieldMorph` / `PushFieldStairs` | the PopField compose tail in `mapCore` | PopField only; a ShapeBlend carrying one is refused. Morph lerps saved→candidate by a lane ramp, winner at t ≥ 0.5. Stairs: r = Data1.x > 0 (builder and `SdfProgram` refuse r ≤ 0, since a zero radius is a plain Union/Subtraction pop), n = Data1.z ≥ 1; its material winner follows the union or subtraction rule. Both bound as max(La, Lb). The fixed-point evaluator reads every lane as zero. |
| `RotatePlane` | `SDF_OP_ROTATE_PLANE` in `mapCore` | Shape selects the plane (XY/YZ/XZ), Blend the driver axis, Data0 = (rate, origin). `BendX/Y/Z` and `TwistY` are builder methods over it. |
| `LogSphere` | `SDF_OP_LOG_SPHERE` in `mapCore` | Data0 = (w = ln ratio, twist, 1/w, 0), from the builder; Data1 is zero. |
| `LaneErode` | `SDF_OP_LANE_ERODE` in `mapCore` | Data0 = (lane 0..3, from, to, noiseScale), Data1.x = target reach. t ≥ 1 skips the next shape; the ragged term scales by 4t(1 − t). Render-only. |
| `ReliefRow` and a relief's Material lane (`SdfReliefMask`, `SdfReliefBand`, `SdfReliefRegion`, `SdfProgramBuilder.NoiseDisplace`'s masks, `SdfProgram.DecodeReliefRuns`); `SdfFieldEvaluator.MaskProduct`, `BandWeight`, `WeightedRelief`, `MaskProductBounds` | `SDF_OP_RELIEF_ROW` (no-op) and `sdfMaskProduct`, `sdfReliefBandWeight`, `sdfReliefRegionDistance` in `field/sdf-map.hlsli`, read by `SDF_OP_NOISE_DISPLACE` | A relief's Material lane counts the rows directly before it: a band (Blend 0; Data0 = start, width, inside, outside, on the grids `SdfReliefBand` names, so `start + width` is exact in both carriers), then per region a pose (Blend 1; Data0.xyz = origin, Data1 = unit quaternion) and a primitive (Blend 2; Shape = Box, Superellipsoid, Capsule or Plane; Data0 and Data1 as a shape packs them, Data1.x zero). A mask's distance is the least of its regions' at `turn_back(q − origin)`; its weight is `outside` at or beyond the end, `inside` at or below the start, else `inside + (outside − inside)·t²(3 − 2t)`; the relief multiplies its displacement by the product and adds nothing, evaluating no noise, where the product is exactly zero; a mask whose distance reaches its start skips its remaining regions. The door (`SdfProgram.DecodeReliefRuns`, header of `SdfProgram.ReliefRows.cs`) keeps a run contiguous, counted, in its relief's owner and within the caps (8 masks, 32 regions, `SDF_MAX_RELIEF_ROWS`); the kernel refuses a count past the cap or the segment's start. The step bound adds `|a|·SdfReliefMask.SlopeOf` through the relief's point factor (`SdfNoiseDisplacement.MaskedSlope`). Every other walker steps over a row. |
| `SdfProgram.Lipschitz.cs` per-op factors | `sdfStepScale()` in `field/sdf-program.hlsli` and `mapCore`'s final multiply in `field/sdf-map.hlsli` | `Displace` and `DomainWarp` use 1 + amp · max\|freqᵢ\| (infinity norm); flare uses `FlareOperatorNorm`. The program `stepScale` is the reciprocal of the worst unscoped factor. |
| `SdfFieldEvaluator` supported sets | the full GPU vocabulary | Contact and render readings share fixed-point twist/bend (`RotatePlane`): `WarpPoint` mirrors `mapCore`; `WarpBounds` uses `FixedInterval.Sin` and `Cos` so its enclosure contracts with the query. Contact admits creation noise relief and Path; render also admits non-uniform `Scale` and `RenderWarpOps`, including `AxialProfile` (whose arithmetic is `sdfAxialProfile` in `field/sdf-point.hlsli`). Dynamic transforms stay excluded. Read the current sets from `IsSupported*` rather than from a copied list. `Overlap` resolves a failed world-origin rebase toward occupied. |
| `Superellipsoid` | *Generated:* `sdfSuperellipsoid` and its e == 2 branch | Every ellipsoid is a superellipsoid at exponent 2. The fixed carrier divides by each radius (`SuperellipsoidScaledRatio`); the shader multiplies by the packed reciprocal (Data1.yzw), the one operand only the shader reads. |
| `Pcg3dLatticeNoise.Pcg3d` in `Puck.Maths` | `sdfPcg3d` in `field/sdf-hash.hlsli` | One hash, a C# and an HLSL implementation. Its constants are *generated* from `Pcg3dLatticeNoise` (`SDF_PCG_MULTIPLIER`, `SDF_PCG_INCREMENT`, `SDF_HASH_STREAM_A`/`_B`, `SDF_HASH_TUMBLE`, `SDF_NOISE_SEED_STREAM_Y`/`_Z`). The R2 lattice's increments and its dither (`puckR2Dither`) are `Shared/low-discrepancy.hlsli`'s alone, generated from `LowDiscrepancy.R2AlphaXQ32`/`YQ32`; the volumes and the display encode include that file, and the SDF tree no longer spells them. |
| `SdfProgram.SqrtHalf`, `SmoothRadiusMin`; `SdfFieldEvaluator.SweepSamples`, `SweepRounds` | *Generated:* `SDF_SQRT_HALF`, `SDF_SMOOTH_RADIUS_MIN`, `SDF_SWEEP_SAMPLES`, `SDF_SWEEP_ROUNDS` | The chamfer bevel's scale, the smooth blends' radius floor and the sweep search. The fixed-point evaluator converts the two floats once (`FromDouble`). `SdfProgramBuilder.Scale`'s floor is `SdfSolidGeometry.MinimumScale`, host-baked; the kernel applies none. |
| `SdfOctahedral` (`Encode`, `Decode`, `BorderSource`) | `sdfOctEncode`, `sdfOctDecode`, `sdfOctBorderSource` in `field/sdf-octahedral.hlsli` | One map in the kernel's convention: +z pole, [-1, 1] squared. The C# is the double-precision authority; a caller with another pole swizzles at its call as its kernel does (the sky environment: x, z, y, then to [0, 1]; the stars: unswizzled). `SdfWorldPickReadback.DecodeNormal` is the visibility record's SNORM16 unpack (`SdfVisibility.NormalBits`, through `UnpackSigned`). `PackSigned`/`UnpackSigned` carry a signed-normalized pair of any width (the store codec's 16 bits, the probe surface map's 8, the visibility record's 16), and `SignedScale` is the one scale the generated `SDF_VISIBILITY_NORMAL_SCALE` and `SDF_MESH_IRRADIANCE_DEPTH_NORMAL_SCALE` take from the widths. |
## Engine buffers, groups, and bindings
Native record buffers use `ShaderInterfaceStructure.From<T>()` to derive the
public unmanaged C# fields' offsets and stride. `ShaderInterfaceHlsl` emits the
struct and explicit padding; its reflected resource name carries the layout
identity so a same-stride field reorder rejects stale bytecode. The shared
interface echo reads two consecutive records prepared by
`ShaderInterfaceEcho.WriteRecordSentinels`, checking every field and the stride.
Keep record changes, generated includes, host region writes, and echo evidence
together.
| C# (`SdfWorldTables` unless noted) | HLSL | Contract |
|---|---|---|
| `SdfWorldInterfaces.World`, `WorldParameters`, `SdfWorldPackage.Members` and `Values`; the pass block `SdfFrameBlock.Write` writes | *Generated:* `sdf-world.interface.hlsli` (`puck shaders generate`) | The frame group (set 0) is the standard frame block, which the view's node writes once a frame. The World group (set 1) is `SdfWorldPackage.Tables`, the field's tables first (`FieldTables`): every table's buffer, the sampled-values filler, the glyph atlas and the samplers, one set per upload ring slot the tables own (`SdfWorldTables.WorldSet`). The pass group (set 3) is one set per frame slot for each pass of a view's instance: its block holds the view's render extent and then, in ordinal name order, every value `SdfWorldPackage.Values` declares: the world values (imageExtent, the view's extent and the visibility record stride; meshDraws; screenCount; viewBase, zero, since each instance renders one view; viewportCount, one), the view's camera, quality (`SdfViewSnapshot.Quality`) and editor grid (`SdfViewSnapshot.Grid`, whose flags `SdfIsaHlsl` generates as `SDF_GRID_*`), far distance and debug mode, the frame's bench levers, the light count (`lightCount`), stable light indices (`shadowSlots`, int4 with −1 for a vacant slot), configured stable count (`shadowSlotCount`) and active incoming count (`shadowFadeCount`), and the curvature shading (`curvatureCavity`, `curvatureRim`, `curvatureInk`, `curvatureInkLow`, `curvatureInkHigh`, `curvatureInkColor`). The instance's `jitter` is a float2 ray offset in render pixels (+Y down); `historyFrames` is its uint accumulated-sample count; `temporal` is one when the instance runs `SdfWorldPackage.TemporalFragment`, which tells the views pass to write `reactivityRW` and the resolve to reconstruct over time. `SdfFrameBlock.WriteTemporal` writes all three after the frame values, so cadence signatures remain independent of the sample. Its bindings are the view's own: its scratch buffers, output, screen sources and mesh target, the buffers typed by element. Nothing is pushed. No offset is written by hand on either side. |
| `SdfWorldInterfaces.MeshBakeParameters`, `SdfWorldPackage.BakeMembers` and `BakeValues`; the pass block `SdfMeshBakeBlock.Write` writes | *Generated:* `sdf-mesh-bake.interface.hlsli` | The bake's mask and sampler: the frame group, the world interface's World group (so they bind the residency's World set), and a pass group of their own, one set per frame slot from the bake pipeline's group layout (`SdfWorldPassRecorder`), whose block holds the extent, `instanceMaskWordCount`, `meshBakeCount`, the 64 `meshBakeLattices` rows and the work-counter rows, and whose resources are the instance masks, the samples and the work counters. It carries the field's stamp (`SdfWorldInterfaces.FieldStamp`). Its bytecode keys the stored meshes, so nothing joins it that the bake does not read. |
| `SdfWorldInterfaces.ResolveParameters`, `SdfWorldPackage.ResolveMembers`, `SdfResolveRecorder` | *Generated:* `sdf-resolve.interface.hlsli`; `passes/sdf-resolve.comp.hlsl` | The pass extent is output-sized; `imageExtent` is the active render grid, written from the recording's `RenderWidth`/`RenderHeight`. Common values are copied by generated member offsets from the one frame writer, while resolve-only sharpness leaves native ABI unchanged. The pass samples `currentColor` and writes `output`; color keeps coverage in alpha. Its pass group also carries the temporal members in port order after them, the visibility records, `reactivity`, `historyColor` and `historySurface` read and `historyColorRW` and `historySurfaceRW` written (`SdfResolveRecorder.TemporalInputs` and `TemporalOutputs`), which a spatial resolve binds to the tables' fillers, and it binds the residency's World set, whose tables `sdfReprojection` reads. A device law that dispatches the kernel alone binds a filler of its kind at every binding it does not name (`SdfResolveDeviceLawTests`). |
| `SdfWorldInterfaces.Mesh` | `worldView` in `frame/sdf-viewport.hlsli`, read by the world kernels and both mesh stages; `worldViewDims`, `worldFarDistance` | The mesh interface's pass block is the world interface's, member for member (`SdfFrameBlockLawTests`), so the mesh pass binds the block its node writes for it. `worldView` gathers the view's block values into `ViewportData`'s rows; `worldViewDims` is the active render extent and visibility stride, so the surface, views and sky passes agree. Resolve alone reconstructs the render grid into the output; `place` places that full-output image. The interface also declares `sdfVisibilityRecords` (read) and `sdfGlassSumsRW` (written), which only the glass raster pass binds to the view's storages; the mesh and shadow passes bind the tables' dummy at both. |
| `SdfWorldInterfaces.GlassParameters`, `SdfWorldPackage.GlassMembers`, `SdfGlassRecorder` | *Generated:* `sdf-glass.interface.hlsli`; `passes/sdf-glass.comp.hlsl` | The glass shading pass's own pass group: the common values copied by name from the world layout, `lit` and `glassVisibility` sampled, `sdfVisibilityRecords` and `sdfGlassSums` read, `reactivityRW` written (the dummy outside a temporal view) and `output` the `glassLit` image; its World group is the world interface's, so it reads the material table, the lights and the sky's environment map. `SdfPassBindingLawTests` holds which light and sky tables it binds. |
| `SdfProgram.InstanceMaskWordCount`; the bake block's instanceMaskWordCount | `sdfInstanceMaskWordCount`, `worldInstanceMaskBase` | Width W = max(1, ceil(n/32)). Each bake lattice stores W words plus ceil(W/32) summary words written by `sdf-mesh-bake-mask.comp.hlsl`. Indexing is host-written, never shader-derived. |
| `SdfProgramBuilder.MaxInstances` | *Generated:* `SDF_MAX_INSTANCES` | At most 2048 mask words per lattice. |
| `SdfFrameBlock.WritePreviousView`; `SdfTemporalHistory.PreviousView` | `frame/sdf-reprojection.hlsli`, `passGroup.previousView` | Six float4 rows: position.xyz + validity, right.xyz + tan(fov/2), up.xyz + aspect, forward.xyz, render extent.xy + jitter.zw in render pixels, near + unjittered frustum offset.yz. `sdfProjectView` reads these rows (and the resolve's own current rows in the same layout) into unjittered render pixels; `sdfReprojection` subtracts the jitter, returning the previous render's jittered sample coordinates. The camera belongs to this instance's last completed render, independently of whether temporal sampling is enabled. |
| `SdfWorldPackage.HistorySurfaceWords`; `SdfWorldPackage.TemporalPeriod` and `FeaturePeriods`; `SdfWorldPackage.TemporalFragment`'s reactivity count | *Generated:* `SDF_HISTORY_SURFACE_WORDS`, `SDF_TEMPORAL_PERIOD`, `SDF_HISTORY_WEIGHT_CAP` (the period), `SDF_HISTORY_FEATURE_WEIGHT_CAP` (the period times `FeaturePeriods`), read by `passes/sdf-resolve.comp.hlsl`; by hand: `frame/sdf-viewport.hlsli` (`sdfReactivityIndex`) | The history surface holds six words per output pixel, row-major at the output extent: the receiver's visibility identity; its ray distance and the gathered sample weight as two half floats, the distance low, the weight capped at `SDF_HISTORY_WEIGHT_CAP`, or at `SDF_HISTORY_FEATURE_WEIGHT_CAP` while the pixel carries a feature; the accumulated surface transport's two words as `sdfPackTransport` packs them; then the remembered sub-pixel feature's YCoCg as three half floats, Y low and Co high in the fifth word, Cg low in the sixth with the frames the memory has left (at most `SDF_TEMPORAL_PERIOD`, zero for none) above it. The reactivity buffer holds one float per render-extent pixel, laid out as the visibility records are. The history color's alpha is the coverage. |
| `SdfSurfaceTransport.InverseDistanceScale`, `PackWord`, `SdfTransportWord`; `SdfWorldPackage.Parts.Transport` (stride 8) | *Generated:* `SDF_TRANSPORT_INVERSE_DISTANCE_SCALE`, `SDF_TRANSPORT_SAMPLE_BIT`; by hand: `sdfPackTransport` in `shade/sdf-transport.hlsli` | The surface transport is two words an output pixel. First word's top bit clear: four half floats, the fog's in-scatter weight low and the coverage over the ray distance times 1024 high (its sign masked) in the first word, the haze's weight low and the medium's high in the second. Top bit set (`SdfSurfaceTransport.SampleBit`): one render sample copied whole, its ray distance's float bits below the bit and a zero second word, which the composite turns into transport at the one site a native pixel reaches. |
| `SdfAir` (`SeriesLimit`, `ExponentLimit`, `SteepLimit`, `MaxLights`, `FogColorAuthored`, `Depth`, `Along`, `Phase`); `SdfSky.PackAtmosphere`; `SdfVolume.ScatterAnisotropy` | *Generated:* `SDF_AIR_SERIES_LIMIT`, `SDF_AIR_EXPONENT_LIMIT`, `SDF_AIR_STEEP_LIMIT`, `SDF_AIR_MAX_LIGHTS`, `SDF_AIR_FOG_COLOR_AUTHORED`, `SDF_VOLUME_SCATTER_ANISOTROPY`; by hand: `sdfAirDepth`, `sdfAirAlong`, `sdfAirPhase` in `shade/sdf-atmosphere.hlsli`; `passes/sdf-composite.comp.hlsl` (`SDF_SKY_DETAIL_ATMOSPHERE`, generated from `SdfSkyDetails.AtmosphereRow`) | The atmosphere's closed forms in one order with one set of guards on both sides: a height kind's depth, its series below `SeriesLimit` for a ray parallel to its base, its exponent bounded at `ExponentLimit`, a ray steeper than `SteepLimit` folding its exponentials; the medium's surface crossed in order; the fog and the haze sharing the air's in-scatter by depth. The air lights are the first `MaxLights` lit directionals, baked as unit direction and colour times weight. `SdfAtmosphereLawTests` hold the series on both sides. |
| `SdfWorldTables.Motion.cs` | `sdfPreviousDynamicTransforms` and `sdfPreviousMeshTransforms` | GPU-only histories: three float4 per rigid slot and `SdfMeshRecord.MatrixWords` per mesh draw. `sdfMeshPreviousRow` converts the current draw-record address to the compact matrix stride. The shared region-copy kernel gathers changed mesh rows in one dispatch; separate per-slot requests hold the pre-upload advance and post-upload seeds. Copy the preceding consumed frame's changed rows before the current upload; after it, seed every row on the first upload, a program upload or a frame owing every row, a reseated range, and a mesh draw whose identity changed at its index; settle once after motion stops. Only copy requests cross the host bus for mesh history. Mesh history is a table apart from the host-written mesh region. |
| `DynamicTransformByteLength` = 48 | `sdfDynamicTransforms` | Three float4: position + shadow participation, quaternion, four render lanes. |
| `SdfProgramBuilder.MaxScreenSurfaces` = 32; `ScreenMaterialId`; `ScreenSurfaceByteLength` = 48 | *Generated:* `SDF_MAX_SCREEN_SURFACES`, `SDF_SCREEN_MATERIAL`, and the `screenSources` array's length in the world interface; by hand: `SdfDecalDescriptorCount` (from `SDF_MAX_SCREEN_SURFACES`); `screenSurfaces`, three float4 rows per screen read through `worldScreenSurface` | The screen count is stated once; every per-screen table and the source array take their length from it, and no mask caps it. Each screen samples `screenSources[i]` through `samplers[f]`, `f` its row's `GpuSamplerFilter` (generated `SDF_FILTER_*`), in `sampleScreenSource`'s wave-uniform loop: a descriptor array is indexed only by a dynamically uniform value, which Vulkan's `shaderSampledImageArrayDynamicIndexing` permits (`VulkanLogicalDeviceFactory.FeatureIndicesOf` requires it and refuses a device without it by name). The material sentinel band `ScreenMaterialId + 1 + i` is closed on both sides; `sampleScreenSurface` bounds the index. Right/Up are unit and orthogonal and half-extents positive, because the shader divides by them. |
| `ScreenMappingByteLength` = 144; `SetScreenMapping` over `SourceMapping.Draw` (`src/Puck.Commands/Sources`) and `SdfScreenTreatment`, `SetScreenBound` | `ScreenMappingData`, nine float4 rows per screen read through `worldScreenMapping` from `screenMappings` (`frame/sdf-screen-mapping.hlsli`); the screen shading in `shade/sdf-environment.hlsli` | Rows: the warp's u and v rows (coefficients of u, v and 1, then the face distance one warped unit spans), the image map's u and v rows (coefficients of the warped u, v and 1, then mapped and letterboxing flags), the crop, the crop inset by half a source pixel, and the state row (bound this frame, the sampler's `GpuSamplerFilter` value, the luminance, and the `SdfScreenFace`: 0 an opening, 1 a display), then the two treatment rows (`SdfScreenTreatment`: scanlines, subpixel stripes, vignette, glint; glint power, corner radius, edge softness, and whether the face draws a treatment). An unmapped screen's first six rows are zero, and `sdfScreenSurfaceShades` shades it as unbound glass; an unbound one's bound flag is zero, and the world block's `screenCount`, one past the highest bound screen, bounds the screen-light loop. A screen's mapping carries no warp: its glass is exactly its picture, and an authored screen material changes only the treatment rows. A new warp arm is drawable only through an affine inverse. |
| `SdfScreenEmission` (`Edge`, `Bytes`, `DefaultLuminance`, `MaxLuminance`); `SdfWorldTables.ScreenEmission.cs`; `SdfWorldPackage.ScreenLights` | `passes/sdf-screen-emission.comp.hlsl` writes `sdfScreenLights`, which `shade/sdf-light.hlsli` reads | One float4 per screen, reduced on the GPU from the acquired screen image: its pixel-weighted linear RGB mean times the screen mapping's peak luminance (`mapping.state.z`, in nits), with W = 1 for a populated result and 0 for an empty one. No CPU colour feeds it. |
| `SdfLight`, `SdfSkyBlock` (256 bytes), `SdfSkyLayer` and the kind records (`Puck.SignedDistance`); `SdfKernelInterfaces.LightAndSkyTables`; `SdfLights.Pack`, `SdfSky.Pack`; `SdfWorldTables.LightsAndSky.cs` | Generated light/sky/layer structs, `SDF_LIGHT_*`, and World-group buffers; `shade/sdf-light.hlsli` for each direct light kind | The host packs lights, one sky block (atmosphere, ambient/reflection gains, frame axes, tier and run structure), and up to eight layer records. Views reads the layer table for analytic panels and the shared coefficients for ambient; sky/composite reads layers for camera composition. The environment kernels read the upload slot's block and layers. `SdfPassBindingLawTests` pins deployed bindings. |
| `SdfSkyEnvironment` (`Size` = 64, `TexelBytes` = 8, `MapBytes` = 65,536, nine coefficients / 144 bytes); `SdfSkyEnvironmentRefresh`; `SdfWorldTables.SkyEnvironment.cs` | *Generated:* `SDF_SKY_ENVIRONMENT_SIZE`, `SDF_SKY_ENVIRONMENT_COEFFICIENTS`, `SDF_SKY_ENVIRONMENT_MAX_RADIANCE`; `shade/sdf-sky-environment.hlsli`, `shade/sdf-lighting.hlsli`, the environment and reduction kernels; generated `sdfSkyEnvironment` and `sdfSkyCoefficients` buffers | Two half-float planes share one lighting-stack walk: full radiance for SH/fog, panel-free radiance beneath analytic reflection panels. Solid-angle projection integrates the first texel's constant term analytically. Views applies cosine factors π, 2π/3, π/4. Changed candidates project on the CPU and refresh the GPU only at an all-direction maximum irradiance difference of at least 1/255 from the last rendered coefficients. Camera-only edits and still skies do no projection; zero fog and gains disable it. Candidate projections, texels and skipped renders have submission counters. The submitted environment revision joins the lighting cadence signature after upload; fog density, gains and lighting-visible panel records (including their frame axes) join directly, so analytic panel edits below the SH threshold still rerun views/resolve. Device laws hold the CPU/GPU maps and coefficients; `SdfSkyLightingLawTests` holds convolution and refresh. |
| `SdfVolume.VectorsPerEntry` = 12; `SdfProgramBuilder.MaxVolumes` = 64; `SdfWorldTables.PackVolumes` | *Generated:* `SDF_VOLUME_VECTORS_PER_ENTRY`, `SDF_MAX_VOLUMES`; by hand: `shade/shade-volumes.hlsli` (`sdfVolumes`) | `PackVolumes` writes each row the shader decodes, including the motion `SdfVolumeMotion` bakes from the frame's presented tick; read the row assignment from those two, which state it beside each other. The shader stops at the zeroed trailing entry and composites intersecting volumes far to near. |
| `SdfWorldPackage.VisibilityRecordByteLength` = 32 | `frame/sdf-visibility.hlsli`, through `sdfVisibilityRecordBuffer`: `sdfVisibilityRecordsRW` in the surface pass; `sdfVisibilityRecords` in views, the resolve and the composite; `SdfWorldPickReadback`'s word offsets | One buffer, two members of the world interface's pass group. Eight words per pixel: the ray parameter, identity, material, triangle, the draw's frame slot (`SDF_TRANSFORM_SLOT_NONE`, `SdfProgram.NoDynamicTransformSlot`, for a static draw), a 16-bit octahedral normal, curvature and AO as halves, and K, read and written only through that module's typed functions. K packs four stable shadow visibilities as four 8-bit lanes through `sdf-shadow-visibility.hlsli` alone (no CPU code reads K; `SdfVisibility.ShadowBits` and `ShadowMask` generate its lane constants; a lane's top code, `SDF_SHADOW_UNQUERIED`, marks a slot the surface pass did not query and queried visibilities take the codes below it; `SdfShadowVisibilityDeviceLawTests` runs the codec on both backends), and `SdfIsaHlsl` generates the lane constants and the normal word's `SDF_VISIBILITY_NORMAL_SCALE` and `SDF_VISIBILITY_ZERO_NORMAL` (`SdfVisibility.NormalBits`, `ZeroNormal`). The identity carries the kind (`SdfVisibilityKind`) above `SdfVisibility.KindShift` and the source in `SdfVisibility.SourceMask`, *generated* as `SDF_VISIBILITY_KIND_*`, `SDF_VISIBILITY_KIND_SHIFT` and `SDF_VISIBILITY_SOURCE_MASK`; a mesh source is its draw ordinal. Anonymous lanes load from the draw's frame slot's transform row at `3 * frameSlot + 2`, or zero for a static draw. `SdfWorldPicker` ordinarily copies words 0 to 3 (16 bytes) and captures the frame's immutable `ISdfPickMap`; an inspector request copies through word 5, decoding the octahedral normal (`SdfWorldPickReadback.DecodeNormal`) and capturing the exact camera/jitter/cut epoch for world-point reconstruction. Graph-owned barriers order this optional readback, and no demand records no copy. |
| `GpuRegion`'s `Copy*` constants (`CopyHeaderWords`, `MaxCopyRuns`, `CopyWorkgroupSize`, `CopyMaxGroupsPerDimension`, `CopyRowThreads`, `CopyMaxRows`), `CopyGroups`, `CopyThreads` and `CopyPipeline`; `RecordCopy`, `StageOwed`, `GpuBufferStridedCopy.Record` | `src/Puck.Shaders/Assets/Shaders/Residency/region-copy.comp.hlsl`: `copyRequest` binding 0 (t0), `copyDestination` binding 1 (u1), `copySource` binding 2 (t2), `RegionCopyHeaderWords`, `RegionCopyGroupsPerRow`, `RegionCopyRowThreads`, `RegionCopyMaxRows`, `[numthreads(64, 1, 1)]` | Registers equal bindings; no push constants. Requests lead with `(count, runCount, sourceBase, destinationBase, rowWords, sourceStride, destinationStride)`, then `(logical word, first thread)` pairs. `MaxCopyRuns` bounds host debt before page clipping; clipping can expand the encoded run table, whose data base follows its actual length and whose runs never cross an unmapped page. A packed region sets the three row fields to zero and binds the staging buffer as both request and data: its data at `sourceBase` holds the runs' words packed one after another. Thread `t` is its dispatch row times `CopyRowThreads` (65,535 groups of 64) plus its column; a copy past one row dispatches more rows, at most `CopyMaxRows` (64, within Direct3D 12's 4,194,303 groups), and the kernel computes the dispatch's threads as `CopyThreads` does. Each thread handles ordinal `i` from `t` in steps of those threads, finding `word` as the run's logical word plus `i` minus its first thread. Packed mode reads `sourceBase+i` and writes `destinationBase+word`. Strided mode uses `row=word/rowWords`, `column=word%rowWords`, and addresses each buffer at its base plus row times its stride plus column. Both modes share one search and uint assignment. The reusable strided recorder owns separate requests/sets per fenced slot and recording; its copied words and address extents stay within `GpuRegion.MaxByteCount/4`. `UploadModelGpu` models both modes. |
| `SdfMeshRecord` (`DrawWords` = 64, every word offset, `VertexWords` = 6, `MemberWords` = 8, `SkinVertexWords`, `NormalsFlag`, `MaterialsFlag`, `SkinFlag`, `WorldMaterialFlag`); `SdfMeshRegion` (`MaxDraws`, the writer), `SdfMesh.LevelOf`, `SdfMesh.MaxTriangles`, `SdfMeshRegionLayout` | *Generated:* `SDF_MESH_DRAW_WORDS`, the `SDF_MESH_*_WORD` offsets, `SDF_MESH_VERTEX_WORDS`, `SDF_MESH_MEMBER_WORDS`, `SDF_MESH_SKIN_VERTEX_WORDS`, the four `SDF_MESH_*_FLAG`s; by hand: `frame/sdf-mesh.hlsli` (`sdfMeshWorldPosition`, `sdfMeshWorldNormal`, `sdfMeshSurfaceNormal`, `sdfMeshMaterial`, `sdfMeshLevelIndex`, `sdfMeshInfluenceWord`) and `frame/sdf-mesh-skin.hlsli` (`sdfMeshSkinSlotsOf`, `sdfMeshSkinPose`) over `sdfMeshRegion`, a `StructuredBuffer<uint>` in both the `sdf-mesh` and `sdf-world` interfaces, read only through `frame/sdf-mesh-words.hlsli` (`sdfMeshRecordWord` for a record, `sdfMeshWord` for a mesh's own words) | Every offset is `SdfMeshRecord`'s, which the region's writer writes through and the kernels read generated; its doc comment states the layout. Per draw, 64 words: the row-vector matrix (0–15), material, index word, index count, vertex word, flags, triangle-material word (16–21), the normal matrix (22–30), the frame slot or -1 (31), the skin word (32), where a mesh with members keeps its member count, `MemberWords` a member and `SkinVertexWords` a vertex (its first member, its second member byte and unorm16 share, two binary16 gradient components, and the third with padding: `SdfMeshInfluence`, written by `SdfMesh`'s skin writer), the carry (33–40), the clip plane (41–44) and the shared level-table pointer/count (45–46), then four GPU selection rows (47–62): center/flags, half X/stretch, half Y/staged instance generation and half Z/level count, then the displacement handle (63). Each mesh stores one three-word row per level (including zero) after its levelled indices: first triangle, vertex count and error. `sdf-mesh-selection.hlsli` reads these rows; no pass stages a second candidate list. Then every distinct mesh's vertices (six floats), triangle materials and indices, each mesh's levels after its own triangles. The mesh target stores a pixel's draw plus one and its levelled triangle as floats, so both stay below 2^24 (`MaxDraws`, `MaxTriangles` over every level). |
| `SdfMeshOcclusion.Stage`, `SdfMeshCull.WriteGpu`, `SdfMeshDetail.WriteGpu` | `passes/sdf-mesh-occlusion.comp.hlsl`, `frame/sdf-mesh-selection.hlsli` | 224 bytes, 14 uint4 rows: row 0 holds candidate count, pyramid levels, flags (bit 0 depth occlusion, bit 1 exit partitioning) and glass; rows 1–3 detail; rows 4–13 cull. `ArgumentPhases` and `SdfOcclusionPhases` are both 3: entry/early, late/solid exit, thin exit. Selection flags bit 2 carries `EnclosesSolid`; cascade statistics count entry and exactly one exit command per kept draw. |
| `SdfKernelInterfaces.MeshLevelShift` = 24; `MeshPushedIndex` | *Generated:* `SDF_MESH_LEVEL_SHIFT`, read by `sdf-mesh.hlsli`, `sdf-mesh-raster.hlsli`, the shadow vertex stage and the occlusion kernel | The index a mesh draw call pushes, and a counted indirect draw's identity: the level of detail from bit 24 up, the draw below it. The occlusion kernel writes the level its candidate carries into the identity. The fragment stage writes the draw plus one into the target's second channel, which `sdfMeshSampleAt` reads back. |
| `SdfWorldPackage` (`MeshTargetFormat`, `MeshDepthAttachment`, `MeshClearDepth` = 0) | `sdf-mesh.frag.hlsl`'s target (ray parameter, draw plus one, triangle); `meshVisibility` in the world interface | The target and its depth are retained resources of `SdfWorldPackage.Fragment`, which the planner moves between the mesh pass and its readers; the depth resource declares `MeshClearDepth`, the clear `MeshDepthAttachment` states and `SdfMeshRasterPass.RenderPass` also clears by. |
| `SdfSkyDetails` (`Runs`, `AtmosphereRow`, `Fixed`); `SdfSkyKindsHlsl` | *Generated* `SDF_SKY_DETAIL_ATMOSPHERE` | Views, sky, composite and environment share stable detail identities: field runs, atmosphere, then layer labels. Fixed labels cannot be authored as layer names. |
| `GpuKernelCounters` (`RowWords`, `CountWords`, `GpuWork.KernelKinds` order); `ShaderWorkCounters` (`Row`, `DetailRow`, `Buffer`); `SdfFrameBlock.WriteWorkCounterRow`, `WriteWorkCounterDetailRow` | *Generated* into each counting interface: `workCounters`, `passGroup.workCounterRow`, `passGroup.workCounterRowDetail`, `PuckWork*` constants and counting functions (`puckCountWork`, `puckCountDetail`, `puckCountShapes`, `puckCountFragmentWork`); other interfaces declare them empty | Pass rows precede named detail rows. A row holds the kinds in `GpuWork.KernelKinds` order: march steps, texels written, sky evaluations, hashes and texture loads, then primitive evaluations and gradients. The 7 kinds occupy 14 words (56 bytes); primitive counts use words 10 and 12. The three environment projection kinds are host counts only: the submission has 26 columns, with environment counts at 21–23 and primitives at 24–25. Each kernel kind is a 64-bit count, low word then high word, with atomic carry. A named row adds only its own work; the ledger reconciles its sum with the plain remainder after readback. |
| `SdfWorldPassRecorder`'s port binding; `SdfSkyRecorder`'s and `SdfResolveRecorder`'s, by member name | `output`: the lit image views writes, the resolved lit image the resolve writes, the `color` the composite writes; the sky interface's `lit`, `skyBase*`, `skyUpper0*` to `skyUpper2*`, `transport` and `screenSources` (a panorama's or textured disc's screen, bound like views' screens) | Each pass of a view's instance has its own set per frame slot, allocated from the instance node's pool (`RenderGraphPackageSets`). |
| Glyph atlas; decal cells | `sdfGlyphAtlas` through `samplers[SDF_FILTER_NEAREST]`; `sdfDecalCells` | |
| The instance-mask buffer | `sdfInstanceMasksRW` in the bake mask; `sdfInstanceMasks` in the bake | `SdfWorldPackage.MeshBakeBatch` lattices of `instanceMaskWordCount` words each. |
| `SdfMeshIrradianceProbe` (`ProbeWords` = 235, `DepthSize` = 12, `DepthWords` = 216, `DepthWord` = 19, `OffsetWord` = 17, signed normal scale, surface fade, the solid and sheet coverage ramps, flags and 0.05 m bias); `SdfMeshProbeCoverage`; `SdfMeshProbeDepth` (`Trace`, `Surfaces` and its sheet bit, `Visibility`); `SdfOctahedral`; `SdfMeshIrradiance` (`Place`, `Compose`, `Gather`/`TryGather`, `Incoming`, `LightVisibility`); `SdfWorldTables.MeshIrradiance.cs` | *Generated:* `SDF_MESH_IRRADIANCE_*` record/read constants; by hand: `sdfMeshProbeCoverageVisibility`, `sdfMeshProbeDepthVisibility` (the sheet bit masked off the curvature half), `sdfMeshProbesAt`, `sdfMeshIrradianceReachShare`, `sdfMeshIrradianceAt`, `sdfMeshLightVisibility` (traced lights, and the sun in a view with no cascade), octahedral helpers | A 940-byte record holds one bounded first-hit surface per texel: FP16 ray distance and two signed octahedral normal bytes; negative distance marks a miss to that reach. Four reflected angular taps reconstruct compatible compatible local quadratic coefficients with cached normal gradients, testing the entering root, with 2 cm fade and blocked-coverage filtering. Opposite faces and separate walls never interpolate together. No radial/squared-distance moments remain: they rejected coplanar grazing receivers. No neighbour filter, whole-sphere planes or vetoes. Sky and bounce share the same precomputed full-reach quadrature across cells and camera traces; per-cell random rotations are removed. Gather uses trilinear × a half-spacing smooth distance fade in front of the receiver × visibility at the actual biased receiver. Empty gathers return zero indirect/static light on CPU and GPU. `SdfMeshIrradianceGatherDeviceLawTests` runs `sdfMeshProbesAt` and `TryGather` on one published volume and requires the same slots, weights, share and sun visibility on both backends; the surface reach (`SurfaceReach`, `SurfaceReachFadeStart`) and the coverage ramps are generated. The published table fits the published tier and is copied on the device from the probe service's feedback table, changed slot runs only; the binding revision follows buffer replacement. See [mesh GI](mesh-gi.md). |
| `SdfMeshProbeTrace`, `SdfMeshProbeRelight` (packet words, `PreviousWord`, `RecordInputWord`, group sizes); `SdfMeshIrradianceProbe` (`InsideShare`, `OpenGroundShare`, `CameraSampleCoincident`, `LightBias`, `BoxMargin`, `BoxMarginShare`); `SdfPhotometry.LuminanceRed`/`Green`/`Blue` | *Generated:* `SDF_PROBE_*`, those `SDF_MESH_IRRADIANCE_*` reals; by hand: `passes/sdf-probe-*.comp.hlsl` against `TrySampleCamera`, `Relight`/`Shade` and `Affected` | The probe kernels read every value the CPU reference shares through these generated names; a literal in a probe kernel that copies a C# constant is a defect. Every kernel's luminance (the SDF lighting and composite, bloom, overlay focus) reads `PuckRec709Luminance` from the generated `Shared/luma.hlsli` (`ShaderLumaHlsl`), derived from `ImageSourceConversion.Bt709Kr`/`Bt709Kb`; `SdfPhotometry.LuminanceRed`/`Green`/`Blue` are the CPU side of the same weights. |
| `DebugViewModes.Names` (`Puck.SdfVm.Model`) | *Generated:* `SDF_DEBUG_VIEW_COUNT` and `SDF_DEBUG_VIEW_<MODE>` (the name in upper snake case), read by `frame/sdf-levers.hlsli`, `debug/sdf-debug-views.hlsli` and the passes | The list's order is the wire value, so a new mode appends; the kernels' switches read each mode by its generated name. |
| `SdfProgram.DynamicTransformSlotBits` = 24, `MaxDynamicTransformSlot` = 2²⁴ − 1 | the `TransformDynamic` slot decode (`(uint)data0.x`) and the transform rows at `3 * slot` through `3 * slot + 2` | A slot rides the instruction's float data lane, exact below 2²⁴, and its row index stays inside 32 bits. `SdfVisibilityLawTests` holds the lane to the bits and refuses a wider slot by name. |
## Shadow handoff storage
Shadow handoff records are `SdfShadowHandoff` in `Puck.SignedDistance`:
`Outgoing`, `Incoming`, `Slot` and `Weight` at byte offsets 0, 4, 8 and 12,
three signed integers and one float, stride 16. `SdfKernelInterfaces` derives
the HLSL structure and `sdfShadowHandoffs` World-group buffer from that record;
`SdfWorldTables.LightsAndSky.cs` writes active controls through the counted region.
The pass group carries the active count (`shadowFadeCount`) separately from
configured capacity, which `SDF_SHADOW_FADE_CAPACITY` bounds in
`frame/sdf-lights.hlsli`. A handoff allocates nothing: `shade/sdf-light.hlsli`
fades the outgoing light from its stable slot's K lane and lights the incoming
one unshadowed.
## Retained pass cadence
`ShaderPipelineResource.Retained` is an owned intermediate's single
queue-ordered allocation; do not combine it with transient, external, history
or public-output storage. A package recorder's nullable `Signature` authorizes
reuse only together with the node's input-generation and output-validity checks.
Keep `SkipAccesses` as the barrier-state path for both inactive and standing
passes; content generations are not a second barrier tracker.
Before setting `PreservesPredecessor` on a forwarding version, audit its actual
shader writes: it must preserve predecessor-owned fields and replace its own
fields idempotently. An accumulated counter or an overwritten sky image
violates that contract. A same-pass predecessor buffer read is legal only with
this validated retained package contract; the planned output remains a compute
read/write access. The package reads and writes through that writable binding,
not simultaneous SRV/UAV aliases. Keep the recorder's
binding, shader load alias and fragment output together. A later destructive
forward orders readers of all still-preserved ancestor versions before it.
An ordinary destructive forward or sampled image overlap is
still refused. Force a null signature for unversioned borrowed inputs
and for demanded work whose recording must run, including readback, capture
and temporal convergence. Existing dependency preparation retains its own
counting and ordering. `GpuPassState.Standing` has no per-pass count, so timing
or counted-load consumers must not interpret it as a measured zero.
A paused buffer producer publishes without a display surface. Keep its actual
last and previous named-output snapshots across an install, detach only owned
published ring slots into the existing held-resource retirement, and count their
bytes once. Do not expose unrendered replacement allocations or take ownership
of package-borrowed buffers. Their replaced package recorders retain the actual
owner while either publication names a borrowed allocation. An installed package
retaining the same buffer object takes over that owner obligation without holding
redundant old graphs; raw handles and external bindings do not. After actual
displacement, the existing reader lag and fence retire those recorders. The graph
never disposes the borrowed buffer directly. The reader lag retires displaced owned slots;
reset and device release withdraw both snapshots.
## Image sources
| C# (`Puck.Abstractions.Sources`) | HLSL (`src/Puck.Shaders/Assets/Shaders/Sources`) | Contract |
|---|---|---|
| `ImageSourceUploadLayout`, `ImageSourceUploadHeader` | `ImageSourceHeader`, `imageSourceHeader` in `image-source.hlsli` | Eight little-endian uints: width, height, format code, color word, plane 0 offset and stride, plane 1 offset and stride. The color word packs matrix, range, transfer and primaries in bytes 0 to 3. |
| `ImagePixelFormat`, `ImageYuvMatrix`, `ImageYuvRange`, `ImageTransferFunction`, `ImageColorPrimaries` codes | `IMAGE_FORMAT_*`, `IMAGE_MATRIX_*`, `IMAGE_RANGE_*`, `IMAGE_TRANSFER_*`, `IMAGE_PRIMARIES_*` | Numeric values match one to one; format code 0 is never a format. |
| `ImageSourceConversion.YuvToRgb`, `Coefficients`, `YuvToRgbCoefficients`, `PqToNits`, `ToLinear`, `LinearToWorking`, `ToWorking`, and `SrgbTransfer` (`Puck.Maths`, the extended sRGB curve both directions, which `HexColor`'s `DisplayColor.ToScene` decodes with) (its BT.2020 to BT.709 matrix), `DisplayOutput.SdrWhiteNits` | `imageSourceYuvToRgb`, `puckPqToNits`, `puckSrgbToLinear`, `imageSourceToLinear`, `puckLinearToSrgbExtended`, `imageSourceToWorking`, `IMAGE_SDR_WHITE_NITS`; the `puck*` transfer curves live in `src/Puck.Shaders/Assets/Shaders/Shared/transfer.hlsli`; *generated:* each matrix's Kr and Kb (`PuckBt601Kr` and the rest) in `Shared/luma.hlsli` from `ImageSourceConversion.Bt601Kr` and the rest (`ShaderLumaHlsl`) | The CPU reference is double precision; a kernel agrees within one 8-bit code. |
| `ImageSourceConversion.YuvToRgbCoefficients(matrix)` | The camera converter's derived `Conversion.Matrix` constants (`Win32D3D11CameraFrameConverter`, `src/Puck.Platform.Windows/Assets/Shaders/camera-conversion.hlsl`) | The converter derives its four Y'CbCr coefficients from the one Kr/Kb statement rather than writing them by hand. |
| `ImageSourceConversion.PassOf` and its pass names | `source-palette`, `source-nv12`, `source-rgba`, `source-transfer` `.comp.hlsl` | Set 3, as a document pass's interface places its ports: region at binding 1 (`ByteAddressBuffer region`, t1), image at binding 2 (`image`, u2), the pass block at binding 0 holding the extent, `paperWhiteNits` (`RenderGraphPackageCatalog.SourcePaperWhite`, which `SourceConversionPackage` writes each frame) and the work counter row, 8×8 threads a group, one thread a pixel. |
| `ImageSourceConversion.ImagePassOf` and `ScRgbImagePass` | `source-scrgb.comp.hlsl` | Set 3: the imported image at binding 1 (`Texture2D source`, t1, `RenderGraphPackageCatalog.SourceInput`), image at binding 2 (`image`, u2), the same pass block, 8×8 threads a group; its arithmetic is `source-transfer`'s for scRGB (`imageSourceToWorking` with the linear transfer and BT.709 primaries), held by `ImportedImageConversionDeviceLawTests`. |
## The display encode
| C# (`Puck.Abstractions.Gpu`) | HLSL (`src/Puck.Shaders/Assets/Shaders/Runtime/display-encode.frag.hlsl`) | Contract |
|---|---|---|
| `DisplayEncodeLayout` (`Group`, `SourceImageBinding`, `SamplerBinding`, `BlockBinding`) | `sourceTexture` (t0), `sourceSampler` (s1), `encode` (b2), all in space 3 | The pass group, each register equal to its binding. |
| `DisplayEncodeLayout.WriteBlock`, `BlockBytes` = 16 | `struct DisplayEncode` | Four little-endian words: the `DisplayColorSpace` value; the white scale (`DisplayOutput.WhiteScale`), a float; the dither step, a float, one code of the target's format (`GpuPixelFormats.ColorCodeMaximum`) or zero on a float target; and one when the target encodes sRGB on write (`GpuPixelFormats.EncodesSrgb`). |
| `DisplayColorSpace` values | `DisplayHdr10` = 1, `DisplayScRgb` = 2 | sRGB is 0, the fall-through. |
| `SdfWorldPackage.OpticsMembers` (`DisplaySharpness`, `DisplayFidelity`, `DisplayEncode`, `ToneShape`, `ToneToe`), `SdfToneCurve`, written by `SdfOpticsRecorder` | *Generated:* `isa/sdf-optics.interface.hlsli`; by hand: `puckToneCurve` and `puckSharpen` in `Shared/display-transform.hlsli`, read by `passes/sdf-display.comp.hlsl` | `ToneShape` is peak, contrast, linear start and linear length; a zero peak is no curve. The display pass encodes with `puckLinearToSrgbExtended`, so the display encode's decode is its exact inverse; `DisplayEncode` is zero only for a debug view that is not scene light (`DebugViewModes.ComposesFinal`, `sdfDebugComposesFinal`). |
| `LowDiscrepancy.R2AlphaXQ32`, `R2AlphaYQ32` (`Puck.Maths`) | *Generated:* `PuckR2AlphaX`, `PuckR2AlphaY` and the `puckR2Dither` they make in `src/Puck.Shaders/Assets/Shaders/Shared/low-discrepancy.hlsli`, read by the display encode and the SDF volumes | No hand pair: `puck shaders generate` writes the include from the C# constants. |
The buffer-copy range uses both source and destination byte offsets through `IGpuRecorder.CopyBuffer`, its counting wrapper, both native backends and the upload-memory model. Storage destinations transition through `GpuAccess.CopyWrite` (Vulkan transfer write; DirectX COPY_DEST). Storage clears retain `TransferWrite` and DirectX UAV state. Keep the access mapping laws and the history row/untouched-row laws aligned with this distinction.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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 implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| 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 fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| 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 always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |