Materials contract

Status: decision for Metal and browser WebGPU, not an implemented buffer/bindless renderer; the device layer has 2D-array and cube-array texture support. Colour owns colour domains; baked lighting owns light-source separation. Index.

Rules

M1. One semantic representation; retain a bounded evaluator

Lower source graphs once into a versioned material record: program offset/count, parameter-block offset, texture-reference table, coordinate/animation dependencies, output-role mapping and ordered pass descriptors. Programs and parameter blocks live in read-only GPU buffers on both tiers; per-draw data selects a material/instance, not a new shader source. Static instruction structure is shared; time, tint, matrices, alpha reference, selected frame and exposure-domain metadata are parameters. Sequence topology/pass-state changes select/rebuild a program record, never reinterpret old parameters under a new layout.

Keep the current eight-stage semantic instruction subset as the generic long-tail evaluator initially, including its clamp points, TEMP, bump-next-sample behavior and packed-terrain exception. Eight is the supported imported-program bound, not a fixed hardware pipeline or a rule to discard stage nine silently. Texture roles and ordered pass descriptors remain explicit around that evaluator; do not force an entire multipass Shader into eight diffuse instructions. Reject an unrepresentable lowering with material identity and reason; do not activate an authored fallback merely because a new backend is incomplete. Preserve legal source-selected/default/empty cases and report undefined samples explicitly.

Specialize hot structures from this same program, under the shader-permutation contract (pending on this branch), never a second set of material equations. Fold only proven constants and remove unused samples without crossing clamp, role, projection, alpha or binding-side-effect boundaries. No PBR conversion, generated flattened material art or one shader per texture/export. The eventual deletion target is the duplicated handwritten mesh/generic execution machinery, not the material semantics or its CPU oracle.

Binding-time animation/procedural updates remain CPU/asset-system work until separately ported; GPU evaluation cannot advance generators once per fragment. Resolve typed export identity (same path can name a texture and a final blend), selected resource revision and binding order before submission. Earlier draws retain the revision they saw, including resources reused by subdivision stages. Unread/missing bindings must have defined validity, not accidentally sample a stale descriptor.

Validation: material_graph_test, material_compile_test, material_binding_test, material_sequence_binding_test, material_fallback_binding_test and the 601-signature coverage tool constrain lowering. Port material_graph_gpu_test, material_stage_gpu_test, material_parity_gpu_test, material_inputs_gpu_test, material_particle_gpu_test and material_terrain_gpu_test to shared Slang fixtures on Metal/Chrome. Add generic-versus-specialized comparisons before enabling each specialization; compilation success alone is insufficient.

M2. Texture references are (set, layer), not API handles

Every material sample references a logical (set, layer) pair plus a sampler/coordinate descriptor. Both components are 32-bit shader integers; no host pointer, native descriptor or WGSL 64-bit identity enters the record. Set metadata carries texture dimension, format/colour interpretation, extent and mip layout. The asset/residency table resolves logical references; records cannot outlive or alias a recycled resident resource without invalidation.

  • Metal: resolve through native bindless argument-buffer/descriptor tables. A logical set is an addressing namespace, not a requirement to pack native textures into arrays. Keep each texture's native size/format/mip chain.
  • WebGPU: resolve sets to explicitly declared texture-array bindings in the draw bucket's bind group, grouped by compatible format, dimension, size and mip layout. Layers within an array share these properties. Do not resize content into an atlas, conflate sampler states, or normalize terrain weights to make packing easier. Cube inputs retain cube sampling and face order; cube-array buckets must budget six physical array layers per cube against the adapter's array-layer limit.
  • A bucket describes the complete binding set needed by its draws, not merely one base-colour array. Core floor: four bind groups, at most sixteen sampled textures and sixteen samplers per stage, eight storage buffers per stage, and 256 physical layers per array. Reserve bindings for lighting, shadows and view resources; today's eight 2D plus eight cube declarations cannot be copied blindly alongside those resources. Pack program/parameter tables into bounded buffers (128 MiB storage bindings, 256 MiB buffers), paging/chunking rather than exceeding the floor. Validate against actual requested limits, never optional binding arrays or multi-draw support.
  • WGSL uses fixed declarations and a bounded selection/switch, not dynamically indexed resource binding arrays. Select a layer within its array as data. Different buckets may need different bind groups; a transparent draw's bucket switch does not move it in order. An over-limit program needs a validated ordered split or an explicit unsupported result, not dropped samples. Exact binding-slot allocation belongs to texture addressing (pending on this branch).

Initially draw only when the whole material dependency set and selected mip chains are resident, as specified by the plan's streaming policy. Progressive mips are not implicit: before enabling them, track per-reference resident LOD bounds and authored-to-GPU mip rebasing. Arrays expose one mip range, not one range per layer; sampling must clamp to initialized per-layer levels, including with explicit gradients, on both tiers. Never sample uninitialized finer mips or replace a pending texture with invented pixels.

Validation: mixed-size/non-square/cube fixtures, nonzero firstMip and detail changes, bucket/layer boundaries, layer reuse after eviction, full-limit bind groups and dependency loss after eviction. Compare native standalone textures against WebGPU array samples with the same texels and sampler descriptor. The existing sampling spike covers mixed sizes but not array addressing, cube arrays or residency.

M3. Sampler and layout semantics are portable

Keep independent U/V wrap/clamp, authored mip chain/firstMip, mip bias, texel/mip filtering, tested anisotropy, UV-stream selection, transform order and projective divide before bump displacement. Coordinates/derivatives stay float; do not quantize tiled UVs or long-running time to half. Mask alpha and signed U/V/luminance remain data; colour defines the encoded material-local colour calculation and linear scene boundary. Lighting ×2 removal does not remove authored graph ×2.

The Slang findings are requirements, not optional optimizations:

  • Under per-pixel branches, compute the actual sample coordinate gradients in uniform control flow and use SampleGrad. Bump and generated/projected coordinates need their own transformed/displaced gradients, not reused UV0 gradients. If that cannot be expressed safely, sample unconditionally then select; do not disable WGSL derivative-uniformity diagnostics or force mip zero on a mipmapped material. Uniform-buffer-only branches passed the spike; storage-program/instance selection is not automatically uniform.
  • Shared GPU records use 16-byte float4/uint4/int4 fields and arrays of those, not bool, float3 or host size_t packing. Assert offsets/stride and compare Slang reflection for Metal/WGSL. Explicit counts bound buffer reads/dispatches; Slang Metal lacks structured-buffer GetDimensions in the tested path.
  • Globals/bindings follow declaration order, checked against reflection for every entry point. Slang can retain globals on Metal vertex functions even when sampling is fragment-only; budget layout visibility accordingly. Neither backend may reorder a host binding table by semantic name and assume the generated numbers changed with it.

Validation: retain the spike's randomized CPU/MSL/WGSL combiner checks; add bilinear/trilinear/anisotropic, address-seam, projective, signed-bump, cube and filtered-alpha probes using the existing texture/material GPU fixtures. Check reflection and byte-pattern buffer reads in native and Chrome tests. Cross-GPU rounding differences are measured tolerances, not claims of adapter precision.

M4. Blend families and ordering are content

Preserve these RGB equations with source S, destination D and source alpha a, along with each authored alpha equation, cutoff, culling, depth test/write and secondary-pass state:

Since the linear-scene migration the device renderer evaluates them in the linear scene with converted sources (colour contract); the encoded equations below remain the CPU reference (SceneRaster) and their defined semantics.

FamilyRGB equation
Opaque / maskedS (masked retains its cutoff)
Alphaa*S + (1-a)*D
Add / AlphaAddS + D / a*S + D
Screen / DarkenS + (1-S)*D / (1-S)*D
Modulate / ModulateOnce2*S*D / S*D
AlphaModulate / InvisibleS + (1-a)*D / D

Do not reinterpret alpha modulation as permission to premultiply an unweighted source. Final blend 6 (SRCALPHA/ONE) differs from shader 6 (ZERO/INVSRCCOLOR); the serialized enum number is not a shared blend ID. No independent-alpha convention may silently replace today's alpha behavior. In the target these scene equations operate in the colour contract's linear composition space; this intentionally changes gamma-space additive/transparent appearance, not blend family or ordering. Bounded screen/darken/modulation inputs stay factors in [0,1], separate from unbounded emission; do not use HDR radiance as a negative destination factor.

Maintain a stable ordered submission stream within each view/pass, with BSP anchors, equal-distance ties, actor section/secondary-pass order, terrain layers, water boundaries and deferred emitters intact. Batch only adjacent order-compatible transparent packets across texture buckets. Sorting by material/bucket globally is forbidden. Pure additive draws may reorder only when depth tests, no depth writes, clipping, stencil, read dependencies and absence of intervening noncommutative blends establish equivalence; otherwise preserve order. Refraction snapshots and child views are explicit graph boundaries. No full OIT is required, and this contract does not solve intersecting translucent geometry.

Collapsing separate reflection/self-light/detail passes requires a proof for their independent alpha/depth/blend semantics, not just matching an isolated RGB sample. Preserve GREATER alpha tests (equality fails), equal-depth receiver/secondary passes and opacity materials that write depth. Terrain's future single pass reproduces ordered alpha composition and holes, not normalized splat weights; authored stage/pass clamp locations remain part of that comparison during the backend port.

Validation: analytical blend/alpha/depth tests in scene_gpu_test and material_parity_gpu_test, foliage/equipment fixtures, material_particle_gpu_test, retained-layer terrain probes and scene_gpu's scene_recursion test. Add interleaved A/B/A texture buckets across intersecting emitters, equal-distance anchors, depth-writing alpha and refraction snapshots. Compare a deliberately unbatched order oracle on Metal and Chrome; retain animated goldens, not just stills.