diff --git a/docs/cultmath-interval-ground-cut-glsl-lowering.spec.json b/docs/cultmath-interval-ground-cut-glsl-lowering.spec.json new file mode 100644 index 00000000..94f3ccca --- /dev/null +++ b/docs/cultmath-interval-ground-cut-glsl-lowering.spec.json @@ -0,0 +1,141 @@ +{ + "campaign": "cultmath-tapes", + "cut": "glsl-lowering", + "revision": 1, + "title": "GLSL lowering: shaders/CultMath.glsl is generated from CultMath.hlsl by one enumerated textual transformation, pinned by a test, compiled by glslang, with a committed golden fixture for WebGL2 parity", + "repo": "GameCult/CultLib", + "branch": "hands/cultmath-glsl-lowering", + "base": "c49c76ee", + "depends_on": [], + "first": [ + "Map: docs/cultmath-interval-ground-cut.md, sections 'Where the interval math lives' (route C) and 'The authority map'. Model: the HLSL -> C# mirror in tests/CultMath.Tests/HlslSourceCompatibilityTests.cs (wrapper at :348) and its complete transformation list in packages/cultmath/docs/design.md:92-134. The GLSL lowering follows the same discipline: a complete, enumerated list; anything outside it fails the test rather than being patched around.", + "Read how HlslSourceCompatibilityTests resolves #include \"CultMath.Phacelle.hlsl\" (CultMath.hlsl:506); the GLSL lowering inlines the included file at that line, because GLSL has no #include.", + "Target dialect: GLSL ES 3.00 (#version 300 es), WebGL2. No implicit int/uint -> float conversion; step(vec4, float) and max(vec4, float) differ (max(genType, float) exists, step(genType, float) does not); C-style casts do not exist; lerp/frac/saturate/rsqrt/asuint are mix/fract/clamp(x,0.0,1.0)/inversesqrt/floatBitsToUint; floatN/intN are vecN/ivecN; static const is const. Mixed-signedness shifts are allowed.", + "Where the lowered text does not compile, fix the HLSL into the common subset with a legal, bit-identical HLSL edit (e.g. CultMath.hlsl:114 and :200 step(h, 0.0) -> step(h, float4(0.0, 0.0, 0.0, 0.0)); :471-473 and :502 (float)((uint)hash.x >> 8) before the float multiply). The HLSL -> C# mirror test and the FXC/dxc compiles keep those edits honest. Never special-case the lowering for one function.", + "Casts need a balanced-paren scanner, not a regex: (int)((state >> 28) + 4) at CultMath.hlsl:396 is the case that breaks a regex.", + "Dropped, as the C# mirror drops them: include guards (replaced by CULTMATH_GLSL guards), and the Texture2D/SamplerState functions at CultMath.hlsl:535-573. The GLSL declares no precision; the host shader does (precision highp float; precision highp int; the pcg hashes need 32-bit int).", + "Regeneration: the pin test writes shaders/CultMath.glsl when the environment variable CULTMATH_WRITE_GLSL=1 is set, then asserts equality. No new project, no PowerShell copy of the transformation.", + "Golden fixture: tests export 256 seeded points per function family (snoise float3/float2, snoise_grad, fbm_grad 4 octaves, ridged_grad, cellular, pcg3d/pcg4d, iv_* if present on main by then) with outputs as float32 bit patterns in hex, to tests/CultMath.Tests/fixtures/glsl-parity.json. JSON is tolerated here: the consumer is a browser-pane WebGL2 readback, a xenos boundary. The site cut evaluates it.", + "glslang: tools/get-glslang.ps1 fetches a pinned glslangValidator release the way tools/get-dxc.ps1 does; tools/compile-glsl.ps1 compiles a #version 300 es fragment wrapper that includes shaders/CultMath.glsl and calls every public function once. Run on Starfire, one job, detached with a log, polled in the foreground.", + "Verification on Yggdrasil: dotnet test from packages/cultmath/tests/CultMath.Tests; Stryker --since:c49c76ee from a plain clone (not a linked worktree: Stryker resolves --since paths against the main checkout). Never run verification as a background shell task." + ], + "deletes": [], + "keeps_moves": [ + "Both tracked CultMath.hlsl copies (packages/cultmath/shaders and unity/org.gamecult.cultmath/Shaders) stay one blob; the common-subset edits land in both.", + "The C# mirror test, the FXC probe and dxc -T lib_6_3 -HV 2021 all still pass on the edited HLSL; the Unity package does not ship the GLSL file.", + "design.md's HLSL -> C# transformation list (92-134) is unchanged; the GLSL list is a new sibling section." + ], + "adds": [ + "tests/CultMath.Tests/GlslLowering.cs: the HLSL -> GLSL ES 3.00 transformation, one static function string -> string, with the list as named steps in order: inline includes; drop guards and texture functions; type names; static const; casts via the balanced scanner; intrinsic renames (lerp, frac, saturate, rsqrt, asuint/asfloat); float literal passthrough; guards CULTMATH_GLSL added; a provenance header line naming the source file and that the file is generated.", + "tests/CultMath.Tests/GlslMirrorTests.cs: CommittedGlslEqualsLowering (writes when CULTMATH_WRITE_GLSL=1, prints a unified diff on failure); NoHlslOnlyTokensSurvive (regex over the output for float[234]\\(|int[234]\\(|lerp\\(|frac\\(|saturate\\(|static const|\\((float|int|uint)\\)|Texture2D|SamplerState -> 0 matches); EveryPublicFunctionIsLowered (the set of cultmath_* function names in the HLSL minus the texture ones equals the set in the GLSL); GoldenFixtureMatchesCSharp (regenerates the fixture in memory from C# and asserts equality with the committed file).", + "shaders/CultMath.glsl: the committed generated artifact.", + "tests/CultMath.Tests/fixtures/glsl-parity.json: the golden fixture (seed, points, per-function expected bit patterns, tolerance class per function: exact for integer-hash paths, ulp-bounded for transcendental).", + "tools/get-glslang.ps1 and tools/compile-glsl.ps1, mirroring get-dxc.ps1 / compile-hlsl-spirv.ps1 in shape.", + "packages/cultmath/docs/design.md: a section 'GLSL Target: Source Transformations' after :134 with the complete list, the common-subset rule for HLSL, the regeneration command, and that the GLSL is a derived file never edited by hand.", + "packages/cultmath/README.md: one paragraph that CultMath.glsl exists, what dialect it is, and how a WebGL consumer includes it (string concatenation before its own #version-led source; declare highp)." + ], + "file_changes": [ + { + "location": { "path": "packages/cultmath/shaders/CultMath.hlsl", "line": 114 }, + "change": "step(h, 0.0) -> step(h, float4(0.0, 0.0, 0.0, 0.0)); same at :200. Bit-identical in HLSL and C#." + }, + { + "location": { "path": "packages/cultmath/shaders/CultMath.hlsl", "line": 470 }, + "change": "jitter components and the id at :502: an explicit (float) cast around the shifted uint before the float multiply, so the lowered text has no uint*float." + }, + { + "location": { "path": "packages/cultmath/shaders/CultMath.Phacelle.hlsl", "line": 1 }, + "change": "whatever common-subset edits the glslang compile demands; each one bit-identical, each one listed in the cut report." + }, + { + "location": { "path": "packages/cultmath/docs/design.md", "line": 134 }, + "change": "new section: GLSL Target: Source Transformations." + } + ], + "authority_map": { + "owner": "GlslLowering (tests/CultMath.Tests) owns the HLSL -> GLSL transformation; shaders/CultMath.glsl is its derived output, pinned by GlslMirrorTests. CultMath.hlsl stays the one hand-written shader source.", + "inputs": [ + "shaders/CultMath.hlsl and shaders/CultMath.Phacelle.hlsl text", + "C# math for the golden fixture values" + ], + "outputs": [ + "shaders/CultMath.glsl (GLSL ES 3.00 library, every public cultmath_* function except texture samplers)", + "tests/CultMath.Tests/fixtures/glsl-parity.json" + ], + "derived_state": [ + "CultMath.glsl is derived; a hand edit fails CommittedGlslEqualsLowering", + "the fixture is derived from C#; a stale fixture fails GoldenFixtureMatchesCSharp" + ], + "forbidden_writers": [ + "no per-function special case in the lowering; a dialect gap is fixed in the HLSL in the common subset", + "no second transformation implementation (no PowerShell or JS copy of the rules)", + "no GLSL in the Unity package; no precision statement in the library file" + ], + "shared_paths": [ + "both tracked CultMath.hlsl copies receive the same edits; the existing one-blob rule covers them", + "the same dotnet test run pins the C# mirror, the GLSL pin and the fixture" + ], + "deletion_line": "Nothing is deleted in CultLib. The liability bought is one generated file, one test file, one fixture and two tool scripts; what it retires is every future hand copy of CultMath noise in a GLSL consumer, starting with the site." + }, + "verification": { + "builds": [ + "Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests green; paste counts", + "Yggdrasil: dotnet stryker --since:c49c76ee from a plain clone; triage every survivor by name", + "Starfire: tools/compile-glsl.ps1 exits 0 on the wrapper over shaders/CultMath.glsl; a negative-control wrapper with one lerp( call must fail (records that the compile check sees errors)", + "Starfire: FXC cs_5_0 and dxc -T lib_6_3 -HV 2021 still compile both HLSL copies after the common-subset edits" + ], + "tests": [ + { + "name": "GlslMirrorTests.CommittedGlslEqualsLowering", + "pins": "the committed GLSL is exactly the lowering of the committed HLSL; the regeneration path is the same code." + }, + { + "name": "GlslMirrorTests.NoHlslOnlyTokensSurvive", + "pins": "the list is complete: no HLSL-only token survives in the output." + }, + { + "name": "GlslMirrorTests.EveryPublicFunctionIsLowered", + "pins": "no function is silently dropped except the texture samplers." + }, + { + "name": "GlslMirrorTests.GoldenFixtureMatchesCSharp", + "pins": "the fixture the site will read on WebGL2 is C#'s current truth." + }, + { + "name": "HlslSourceCompatibilityTests.EveryMirrorFunctionMatchesCSharpMath (existing)", + "pins": "the common-subset edits changed no bit of any HLSL function." + } + ], + "negative": [ + { + "pattern": "lerp\\(|frac\\(|saturate\\(|float[234]\\(|int[234]\\(|static const|\\((float|int|uint)\\)|Texture2D|SamplerState|#include", + "scope": "packages/cultmath/shaders/CultMath.glsl: 0 matches." + }, + { + "pattern": "precision (high|medium|low)p", + "scope": "packages/cultmath/shaders/CultMath.glsl: 0 matches (the host declares precision)." + }, + { + "pattern": "CultMath\\.glsl", + "scope": "packages/cultmath/unity/**: 0 matches; the Unity package does not ship the GLSL." + }, + { + "pattern": "git diff c49c76ee..HEAD -- packages/cultmath/shaders/CultMath.hlsl | grep '^[-+]' | grep -v '^[-+][-+]'", + "scope": "every changed HLSL line is listed in the cut report with the reason (dialect gap it closes); none changes a value, proven by the mirror test and the existing goldens." + } + ], + "operator": [] + }, + "estimate": { + "lines_added": 1100, + "lines_removed": 8, + "dependencies_added": [], + "dependencies_removed": [], + "formats_added": ["GLSL ES 3.00 library file (generated)", "glsl-parity.json fixture"], + "formats_removed": [], + "targets_added": [], + "targets_removed": [] + }, + "rulings": [], + "questions": ["Q1 in the map: campaign home (cultmath-tapes, recommended)"] +} diff --git a/docs/cultmath-interval-ground-cut-interval-ops.spec.json b/docs/cultmath-interval-ground-cut-interval-ops.spec.json new file mode 100644 index 00000000..02bba4c5 --- /dev/null +++ b/docs/cultmath-interval-ground-cut-interval-ops.spec.json @@ -0,0 +1,140 @@ +{ + "campaign": "cultmath-tapes", + "cut": "interval-ops", + "revision": 1, + "title": "Interval ops: cultmath_iv_* over float2(lo, hi) in C# and HLSL with enclosure tests, a committed Lipschitz constant for snoise, and ball bounds for snoise and fbm", + "repo": "GameCult/CultLib", + "branch": "hands/cultmath-interval-ops", + "base": "c49c76ee", + "depends_on": [], + "first": [ + "Map: docs/cultmath-interval-ground-cut.md, sections 'Ownership', 'Interval culling along the ray' and 'The proving-ground contract'. Parked target: docs/cultmath-tape-target.md, sketch step 1 (:59-64) and 'Open before unparking' (:106-115). This cut is step 1 and nothing after it: no tape, no pruning, no min/max choice tracking, no affine arithmetic (map D1).", + "Common rules from the Asura cut map (Asura docs/cut-map.md, 'Common rules for every addition', :453-489): C# in packages/cultmath/src/CultMath as a partial of math (the Phacelle pattern: math.Phacelle.cs beside math.cs), HLSL in a new shaders/CultMath.Interval.hlsl included from CultMath.hlsl the way CultMath.Phacelle.hlsl is (:506), names prefixed cultmath_, both tracked HLSL copies one blob, bodies inside design.md's transformation list (:92-134), THIRD-PARTY-NOTICES untouched (nothing is ported; Fidget's ideas are used, not its code).", + "Representation: an interval is float2(lo, hi), lo <= hi, both finite. The empty interval does not exist; a caller that needs 'provably empty' tests hi < cutoff. Point intervals are iv_point(x) = float2(x, x).", + "Op set, each with the C# twin the mirror test demands: iv_point, iv_add, iv_sub, iv_neg, iv_mul, iv_scale(iv, float), iv_abs, iv_min, iv_max, iv_sqr, iv_sqrt (lo clamped at 0), iv_exp, iv_clamp(iv, float, float), iv_saturate, iv_smoothstep(float e0, float e1, iv) (monotone: endpoints), iv_lerp(iv, iv, float t). No others until a consumer names one.", + "Noise bounds: CULTMATH_SNOISE_LIPSCHITZ (static const float, provenance in the comment: measured max |snoise_grad| over 1e6 seeded points plus 1e4 gradient-ascent refinements, times 1.10; the test that measures it is committed as a slow, explicitly-run test and the constant is pinned by a fast test). iv_snoise_ball(float3 c, float r) = [snoise(c) - L r, snoise(c) + L r] intersected with [-1, 1]. iv_fbm_ball(c, r, octaves, lacunarity, gain) = the octave sum of iv_snoise_ball(c * f_i, r * f_i) scaled by a_i, octaves clamped to [0, 16] like fbm_grad.", + "Write the enclosure property first, as the shared harness: for each op, 10,000 seeded random intervals (widths from 1e-4 to 10, centres in [-20, 20]) and 16 points inside each; assert f(x) in op(I) with no tolerance (the bound is computed in the same float32 arithmetic; where rounding could exclude an endpoint, widen the op by one ulp in the implementation, not the test, and say so in design.md). For the ball bounds: 2,000 balls, r in [1e-3, 2], 64 points inside each.", + "The saving test: a representative coverage field (one snoise octave at F0 = 0.35, cutoff 0.25) and 1,000 seeded rays through a slab of depth 12; march once at the dense step and once with the adaptive interval march from the map (Δ0, ΔMAX = 8 Δ0, ΔDENSE = Δ0/2, grow on skip, halve on maybe); count snoise evaluations; assert the integrated transmittance agrees within 1e-3 and the evaluation count is at least 2x lower. Print both counts and the ratio; the cut report quotes them.", + "Tightness: a committed test prints the mean width ratio (interval width / true range over the 64 points) for iv_snoise_ball at r = 0.05, 0.25, 1.0 and for iv_fbm_ball at 4 octaves. No assertion beyond finiteness; the number is for the report and for a later affine cut to beat.", + "Verification on Yggdrasil: dotnet test from packages/cultmath/tests/CultMath.Tests; Stryker --since:c49c76ee from a plain clone. Starfire: FXC cs_5_0 kernel calling every iv_* function and both ball bounds; dxc -T lib_6_3 -HV 2021. Detached with a log, polled in the foreground; never a background shell task. Numbers in comments or docs come from committed tests only.", + "If glsl-lowering has merged to main before this branch does, rebase and regenerate shaders/CultMath.glsl (CULTMATH_WRITE_GLSL=1) so the pin test is green on the merge; if not, the lowering cut regenerates after this one. Either order works because the GLSL is derived." + ], + "deletes": [], + "keeps_moves": [ + "snoise, snoise_grad, fbm_grad, ridged_grad, cellular, phacelle: untouched. The bounds call snoise (value) only; snoise_grad is used by the Lipschitz measurement test, not by any bound (map D2).", + "design.md's invariant 8 section (136-) is unchanged; intervals are not value-and-gradient primitives and do not claim the float4(grad, value) layout.", + "HlslMirrorTests' ban on erosion kernels stands; nothing named interval touches it." + ], + "adds": [ + "packages/cultmath/src/CultMath/math.Interval.cs: public static partial class math with iv_point, iv_add, iv_sub, iv_neg, iv_mul, iv_scale, iv_abs, iv_min, iv_max, iv_sqr, iv_sqrt, iv_exp, iv_clamp, iv_saturate, iv_smoothstep, iv_lerp, iv_snoise_ball, iv_fbm_ball, and the constant SNOISE_LIPSCHITZ; each with a doc comment stating the enclosure it guarantees and the ulp widening where one is needed.", + "packages/cultmath/shaders/CultMath.Interval.hlsl: the HLSL mirrors with the same names prefixed cultmath_, and CULTMATH_SNOISE_LIPSCHITZ as static const; included from CultMath.hlsl after the Phacelle include (:506). Both tracked HLSL copies.", + "tests/CultMath.Tests/IntervalTests.cs: the enclosure harness over every op; iv_mul sign cases (all four quadrant combinations and a zero-straddling factor); iv_sqrt with lo < 0; iv_abs straddling zero gives [0, max(|lo|,|hi|)]; iv_smoothstep monotonicity; iv_min/iv_max against the pointwise min/max; a mutant that shrinks any bound by one ulp dies (hand-mutation list in the file header for the float arithmetic Stryker cannot reach, as in 2a-ii-a).", + "tests/CultMath.Tests/NoiseBoundTests.cs: iv_snoise_ball and iv_fbm_ball enclosure; LipschitzConstantPinsSampledGradients (fast, 1e5 points); MeasureLipschitz (slow, explicit trait, prints the max and the refined max); TightnessReport; the saving test (InvalSkipHalvesEvaluations) with its printed counts.", + "packages/cultmath/docs/design.md: a section 'Intervals' after the invariant 8 section: representation, the op list, the ulp-widening rule, the Lipschitz provenance and margin, what the ball bounds guarantee and what they do not (nothing about tapes), and that the site's ground shader and Aetheria's nebula raymarch are the consumers.", + "packages/cultmath/README.md: one paragraph under the noise entry naming the interval family and its purpose (empty-space culling with a proof)." + ], + "file_changes": [ + { + "location": { "path": "packages/cultmath/shaders/CultMath.hlsl", "line": 506 }, + "change": "add #include \"CultMath.Interval.hlsl\" after the Phacelle include; both tracked copies." + }, + { + "location": { "path": "packages/cultmath/src/CultMath/math.cs", "line": 602 }, + "change": "no change to snoise; a comment pointer from snoise to SNOISE_LIPSCHITZ in math.Interval.cs so the next kernel change knows the constant must be re-measured." + }, + { + "location": { "path": "packages/cultmath/docs/design.md", "line": 136 }, + "change": "new 'Intervals' section after invariant 8." + }, + { + "location": { "path": "packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs", "line": 348 }, + "change": "none expected; confirm the mirror resolves the second #include and that every cultmath_iv_* finds its C# twin (a mirror without a twin fails Assert.Contains MirrorOnly)." + } + ], + "authority_map": { + "owner": "CultMath owns interval arithmetic and the noise bounds in C# and HLSL (and GLSL by derivation). The Lipschitz constant is owned by the committed measurement test; the kernel of snoise owns its value.", + "inputs": [ + "the existing snoise(float3) value function; snoise_grad for the measurement test only", + "seeded random points and intervals in tests" + ], + "outputs": [ + "cultmath_iv_* and the two ball bounds, each enclosing its function over its input region", + "three printed numbers for the report: the Lipschitz max, the tightness ratios, the evaluation saving" + ], + "derived_state": [ + "CULTMATH_SNOISE_LIPSCHITZ is derived from the snoise kernel; a kernel change must re-run MeasureLipschitz and re-pin", + "shaders/CultMath.glsl (if the lowering has landed) is derived and regenerated, never edited" + ], + "forbidden_writers": [ + "no interval op without the enclosure test and a C# twin", + "no bound that reads snoise_grad; no value-only/gradient twin of any iv_* function", + "no tape, bytecode, pruning, choice flag or affine form in this cut; names containing tape, prune or affine do not appear", + "no number in a comment or design.md that a committed test did not print" + ], + "shared_paths": [ + "the same IntervalTests enclosure harness runs every op; a new op is one entry in its table", + "the existing HLSL mirror test covers every HLSL interval function with no new comparison path" + ], + "deletion_line": "Nothing is deleted. The liability is one C# file, one HLSL file, two test files and a doc section; it buys the invariant intervals-enclose for every GPU consumer, and it is step 1 of the parked tapes campaign landed in advance." + }, + "verification": { + "builds": [ + "Yggdrasil: dotnet test packages/cultmath/tests/CultMath.Tests green (MeasureLipschitz excluded by trait); paste counts", + "Yggdrasil: dotnet stryker --since:c49c76ee from a plain clone; 0 survivors in math.Interval.cs except listed equivalents; hand mutations for float3 arithmetic listed and killed", + "Starfire: FXC cs_5_0 kernel over every new function; dxc -T lib_6_3 -HV 2021 on both HLSL copies" + ], + "tests": [ + { + "name": "IntervalTests.EveryOpEnclosesItsPoints", + "pins": "intervals-enclose for every op, no tolerance." + }, + { + "name": "NoiseBoundTests.SnoiseBallEnclosesPoints / FbmBallEnclosesPoints", + "pins": "the ball bounds enclose snoise and fbm over 2,000 balls x 64 points." + }, + { + "name": "NoiseBoundTests.LipschitzConstantPinsSampledGradients", + "pins": "no sampled |snoise_grad| exceeds the constant; a constant lowered by 1% fails." + }, + { + "name": "NoiseBoundTests.IntervalSkipHalvesEvaluations", + "pins": "the adaptive march needs <= half the evaluations of the dense march for the same transmittance within 1e-3." + }, + { + "name": "HlslSourceCompatibilityTests.EveryMirrorFunctionMatchesCSharpMath (existing)", + "pins": "every cultmath_iv_* and both bounds match C# bit for bit." + } + ], + "negative": [ + { + "pattern": "tape|prune|affine|choice", + "scope": "packages/cultmath/src/CultMath/math.Interval.cs and shaders/CultMath.Interval.hlsl: 0 matches (case-insensitive)." + }, + { + "pattern": "snoise_grad|fbm_grad", + "scope": "math.Interval.cs and CultMath.Interval.hlsl: 0 matches; the bounds use values only." + }, + { + "pattern": "spherical_erosion|AdvancedErosionFilter", + "scope": "packages/cultmath: 0 matches (HlslMirrorTests' standing rule)." + }, + { + "pattern": "git diff --name-only c49c76ee..HEAD", + "scope": "only packages/cultmath/** (and shaders/CultMath.glsl if regenerated); no other package or src tree." + } + ], + "operator": [] + }, + "estimate": { + "lines_added": 900, + "lines_removed": 0, + "dependencies_added": [], + "dependencies_removed": [], + "formats_added": [], + "formats_removed": [], + "targets_added": [], + "targets_removed": [] + }, + "rulings": [], + "questions": ["Q1 in the map: campaign home (cultmath-tapes, recommended)"] +} diff --git a/docs/cultmath-interval-ground-cut-site-ground.spec.json b/docs/cultmath-interval-ground-cut-site-ground.spec.json new file mode 100644 index 00000000..d6a4934f --- /dev/null +++ b/docs/cultmath-interval-ground-cut-site-ground.spec.json @@ -0,0 +1,181 @@ +{ + "campaign": "cultmath-tapes", + "cut": "site-ground", + "revision": 1, + "title": "Site ground: a full-screen per-pixel WebGL2 cloud shader under every page, interval-culled, TAA-accumulated, driven by the body tokens, budget-controlled by measurement, CSS wash as fallback", + "repo": "GameCult/gamecult-site", + "branch": "main", + "base": "535d170", + "depends_on": [ + "site-masthead:cut_spec:wash-home-only.r1", + "cultmath-tapes:cut_spec:glsl-lowering.r1", + "cultmath-tapes:cut_spec:interval-ops.r1" + ], + "first": [ + "Map: F:/Projects/CultLib/docs/cultmath-interval-ground-cut.md, 'The shader design', 'Budget and how it is measured', D3-D6, Q2 and Q3. Rulings in force: site-masthead:ruling:operator-chromeless-column; the wash-home-only authority map (no second wash token, no class toggled by script, no page rule setting a radial alpha). Re-pin base to main after wash-home-only lands; line numbers below are from 535d170 and shift; re-read by selector.", + "Aetheria reference, read once, copy nothing: Raymarching/CloudShader.shader IntegrateRaymarch (:83-104) for the transmittance integration; its pass 2 (:261-314) for what not to do (gamma 0.5 variance clip, fixed 0.05 blend, packed depth, the density2 bug at :311). Volumetric.cginc for the fill+coverage structure only.", + "Engine facts to confirm before writing: how GameCult-Quartz (sibling checkout or GAMECULT_QUARTZ_ROOT) bundles a component's afterDOMLoaded (esbuild) and whether a dynamic import() of /static/ground/ground.js is allowed, else a module script tag emitted from the component; that site/quartz/static/** is served at /static/**; enableSPA is false (quartz.config.ts:15) so a route change is a page load. Local build: scripts/quartz/quartz.ps1 dev.", + "Tokens (Q3 a): declare on body beside --gamecult-wash: --gamecult-ground-0/1/2 (#03070d #07111a #09141f), and for N in 0..2: --gamecult-light-N (\"255 138 42\" / \"109 96 255\" / \"89 183 255\"), --gamecult-light-N-a (0.18/0.16/0.14), --gamecult-light-N-at (\"78% 14%\" / \"18% 10%\" / \"52% 0%\"), --gamecult-light-N-r (18% / 24% / 28%). The body background becomes radial-gradient(circle at var(--gamecult-light-0-at), rgb(var(--gamecult-light-0) / calc(var(--gamecult-light-0-a) * var(--gamecult-wash))), transparent var(--gamecult-light-0-r)) x3 over linear-gradient(180deg, var(--gamecult-ground-0) 0%, var(--gamecult-ground-1) 44%, var(--gamecult-ground-2) 100%). The ritual block (custom.scss:119-124) overrides the fifteen tokens with its values (yellow 255 178 30 .15 at 78% 8% 24rem; cobalt 49 88 255 .22 at 18% 4% 30rem; violet 91 54 184 .19 at 44% 20% 34rem; stops #030414 0%, #070b24 42%, #040514 100%) and its own background declaration is deleted; it inherits body's.", + "ground.js owns: WebGL2 context on #gamecult-ground (alpha:false, antialias:false, powerPreference 'low-power'); capability check (WebGL2, EXT_color_buffer_half_float or float); token read via getComputedStyle(document.body) -> uniforms, resolving % radii as CSS does (circle, farthest-corner of the background positioning area) and rem/px lengths via the root font size; two RGBA16F history targets; the march pass and the resolve pass; the scheduler (30 fps cadence while accumulating or drifting, visibilityState pause, reduced-motion stop at 32 frames); the budget controller; the debug flag (?ground=debug) that logs measurements and switches the march to evals/unfinished output.", + "Budget controller, one function, one state machine: measure GPU time per frame with EXT_disjoint_timer_query_webgl2 when present, else a fenceSync after the resolve polled to completion, else rAF cadence. Over a 60-frame window: if the median exceeds the budget (4.0 ms), step down: S 16 -> 8 -> 4, then dpr -> 1 (Q2 a), then remove the canvas (CSS wash). Never step up within a session. A median rising 50% over 5 minutes also steps down (thermal). No storage, no userAgent, no maxTouchPoints.", + "cloud.frag.glsl: #version 300 es; precision highp float; precision highp int; then the vendored CultMath.glsl is concatenated by ground.js before this file's body. The field, march and integration exactly as the map's pseudocode; uniforms: resolution, time, frame, jitter, S, intensity, three lights (rgb, alpha, centre px, radius px), three stops, Z0/Z1, F0, CUTOFF, K, drift. The output luminance clamp at 0.035. taa.frag.glsl: history + current, 3x3 min/max clamp, alpha = max(1/frames, 1/32), writes the new history and the screen in one pass via drawBuffers or two cheap draws.", + "Vendoring (D3): site/quartz/static/ground/CultMath.glsl is byte-equal to CultLib shaders/CultMath.glsl at the commit named in its first line (a comment: generated by CultLib ). A script scripts/ground/check-cultmath-glsl.ps1 diffs the vendored file against git show :packages/cultmath/shaders/CultMath.glsl from a CultLib checkout and exits non-zero on drift; Hands runs it in the report.", + "Parity on the device (closes the GLSL leg of the proving ground): with ?ground=parity, ground.js evaluates the fixture from CultLib tests/CultMath.Tests/fixtures/glsl-parity.json (vendored beside CultMath.glsl, same pin) in a 1-pixel-per-point pass, reads back float bit patterns, and reports per function the max ulp distance and the count outside the fixture's tolerance class. Hands runs it in the browser pane and quotes the numbers and the GPU/driver string.", + "Prove in the browser pane: readback of the max relative luminance over the canvas after 32 frames on / at intensity 1 (<= 0.035); the token parity probe (density forced to 0: canvas vs CSS wash at 16 points within 2/255, on / and on a ritual essay); the debug readback (mean evals per pixel and unfinished-ray fraction < 1%); GPU ms per pass with the timer query at the pane's desktop size and at the mobile preset's pixel count. Phone GPU time is operator verification." + ], + "deletes": [ + { + "path": "site/quartz/styles/custom.scss", + "lines": 6, + "note": "ritual body block 119-124: its own background (three radials and the linear gradient) goes; it overrides the tokens instead." + }, + { + "path": "site/quartz/styles/custom.scss", + "lines": 9, + "note": "body 10-27: the six literal colours and three literal stops leave as literals (rewritten as token references in the same lines; counted 9 removed, 9 added)." + } + ], + "keeps_moves": [ + "--gamecult-wash and the index override from wash-home-only: untouched; the shader reads the same token as its intensity.", + ".page::before (the grid overlay), the tour/Pitch VN ground, the Thing deck's .hero-bg, the masthead, the engine: untouched.", + "The CSS wash stays the ground when the canvas is absent, not yet drawn, or removed by the controller; it is the same tokens.", + "docs/brand-design-language.md 'The ground is a wash, not a flat fill' (69-84): rewritten to show the token form and to say the shader is the same ground rendered volumetrically, with the CSS as the fallback." + ], + "adds": [ + "site/quartz/components/GameCultGround.tsx: renders and mounts /static/ground/ground.js after DOM load; added to sharedPageComponents.header after GameCultThemeLock (quartz.layout.ts:19).", + "site/quartz/static/ground/ground.js (~300 lines, no dependencies, no build step): context, tokens, buffers, scheduler, controller, debug/parity modes.", + "site/quartz/static/ground/cloud.frag.glsl and taa.frag.glsl; a shared 3-vertex full-screen vertex shader inline in ground.js.", + "site/quartz/static/ground/CultMath.glsl and glsl-parity.json, vendored from CultLib with the pin in the header.", + "scripts/ground/check-cultmath-glsl.ps1: the vendoring drift check.", + "custom.scss: the fifteen tokens on body with one comment each line group; #gamecult-ground { position: fixed; inset: 0; width: 100%; height: 100%; z-index: -1; pointer-events: none; } ; the ritual override block.", + "docs/brand-design-language.md: the wash section in token form; one paragraph on the ground shader: what it reads, what it may not hold, and the fallback." + ], + "file_changes": [ + { + "location": { "path": "site/quartz/styles/custom.scss", "line": 10, "end_line": 31 }, + "change": "body: fifteen ground tokens declared; radials and the linear gradient reference them; alphas keep the wash-home-only calc." + }, + { + "location": { "path": "site/quartz/styles/custom.scss", "line": 103, "end_line": 124 }, + "change": "ritual block: token overrides replace its background declaration." + }, + { + "location": { "path": "site/quartz.layout.ts", "line": 19 }, + "change": "header: [GameCultThemeLock(), GameCultGround(), GameCultMasthead()]." + }, + { + "location": { "path": "docs/brand-design-language.md", "line": 69, "end_line": 84 }, + "change": "wash section rewritten in token form plus the shader paragraph." + } + ], + "authority_map": { + "owner": "custom.scss body tokens own the ground's colours, lights and intensity; ground.js owns scheduling, budget and TAA; cloud.frag.glsl owns the field; CultLib owns every noise and interval function the field calls.", + "inputs": [ + "computed body tokens (15 + --gamecult-wash)", + "prefers-reduced-motion, visibilityState, canvas size, devicePixelRatio", + "measured GPU frame time (timer query, fence, or rAF cadence)", + "the vendored CultMath.glsl at its pinned CultLib commit" + ], + "outputs": [ + "one opaque canvas under the page, luminance <= 0.035, identical to the CSS wash at zero density", + "debug and parity readbacks (console, flag only)" + ], + "derived_state": [ + "every uniform colour, position, radius and the intensity are derived from the tokens; the shader holds no colour", + "the TAA history is a cache; reset on resize and first frame", + "S and dpr are derived from measurement within the session; never stored", + "CultMath.glsl in the site is derived from CultLib at the pinned commit; the drift check pins it" + ], + "forbidden_writers": [ + "no colour, alpha, position or radius literal in ground.js or any GLSL file", + "no navigator.userAgent, platform, maxTouchPoints, or any device-name branch", + "no class or attribute set on body or html by ground.js; no second wash token; no page rule setting a radial alpha", + "no noise or interval function defined in the site's GLSL; only cultmath_* calls", + "no localStorage/sessionStorage/cookies; no setInterval; one requestAnimationFrame scheduler" + ], + "shared_paths": [ + "home, every content page and the ritual essays paint through the same tokens in CSS and in the shader", + "slow device, hidden tab, reduced motion, missing WebGL2 and missing half-float all pass through the one controller", + "the same Deploy Quartz workflow; static files ship with the overlay" + ], + "deletion_line": "The ritual block's own background and the nine body literals go in the same commit the tokens are declared. The canvas, the two shaders, ground.js and the vendored library are the whole addition; nothing else in the engine or the content changes." + }, + "verification": { + "builds": [ + "Deploy Quartz green on the landing commit: gh run list -R GameCult/gamecult-site -w \"Deploy Quartz\" -L 1", + "scripts/ground/check-cultmath-glsl.ps1 exits 0 against a CultLib checkout at the pinned commit", + "the built stylesheet contains rgb(var(--gamecult-light-0) / calc(var(--gamecult-light-0-a) * var(--gamecult-wash))) verbatim" + ], + "tests": [ + { + "name": "browser pane, /?ground=debug: max relative luminance over the canvas after 32 frames <= 0.035", + "pins": "text contrast: body text keeps >= 7:1 on every ground pixel." + }, + { + "name": "browser pane, /?ground=parity-wash and a ritual essay: canvas vs CSS wash at 16 points within 2/255 per channel with density forced to 0", + "pins": "the shader and the CSS render the same tokens; no second palette." + }, + { + "name": "browser pane, /?ground=parity: every fixture function within its tolerance class on WebGL2; numbers and GPU string in the report", + "pins": "GLSL = C# on a device; the proving ground's third runtime." + }, + { + "name": "browser pane, /?ground=debug at desktop and at the mobile preset: mean evals per pixel, unfinished-ray fraction < 1%, GPU ms per pass by timer query", + "pins": "the step budget and the interval saving on the shipped field." + }, + { + "name": "reduced motion emulated: frames stop at 32 and drift is 0; hidden tab: no frames; WebGL2 disabled: no canvas in the DOM and the CSS wash paints", + "pins": "every fallback goes through the controller and lands on the same CSS ground." + }, + { + "name": "git diff base..head --stat: custom.scss, quartz.layout.ts, docs/brand-design-language.md, the new component, static/ground/*, scripts/ground/* only", + "pins": "no engine, content or masthead change." + } + ], + "negative": [ + { + "pattern": "#[0-9a-fA-F]{6}\\b|rgba?\\(|\\b(255|138|109|183)\\b", + "scope": "site/quartz/static/ground/ground.js, cloud.frag.glsl, taa.frag.glsl: 0 matches." + }, + { + "pattern": "userAgent|navigator\\.platform|maxTouchPoints|localStorage|sessionStorage|setInterval|classList|setAttribute\\(", + "scope": "site/quartz/static/ground/ground.js: 0 matches (the canvas is created by the component, not by script)." + }, + { + "pattern": "float cultmath_|vec4 cultmath_|float snoise|hash\\(", + "scope": "cloud.frag.glsl and taa.frag.glsl: 0 matches; the only definitions of cultmath_* live in the vendored CultMath.glsl." + }, + { + "pattern": "radial-gradient\\([^)]*rgba?\\([0-9]", + "scope": "site/quartz/styles/custom.scss, body rule and ritual block: 0 matches (every radial colour is a token)." + }, + { + "pattern": "gamecult-titlebar|gamecult-nav-link|sidebar|composite|GameCult-Quartz", + "scope": "git diff base..head changed lines: 0 matches." + } + ], + "operator": [ + "open / on the desktop and on the phone; say whether the clouds are unobtrusive enough and whether the drift speed is right (one uniform, drift)", + "on the phone with ?ground=debug, read the logged GPU ms and the controller's final S/dpr; say whether it got warm after five minutes", + "open a ritual essay and confirm its ground still reads as its own paper" + ] + }, + "estimate": { + "lines_added": 760, + "lines_removed": 15, + "dependencies_added": [], + "dependencies_removed": [], + "formats_added": ["GLSL ES 3.00 shader files in static/ground", "vendored glsl-parity.json"], + "formats_removed": [], + "targets_added": [], + "targets_removed": [] + }, + "rulings": [ + "site-masthead:ruling:operator-chromeless-column" + ], + "questions": [ + "Q1 in the map: campaign home (cultmath-tapes, recommended)", + "Q2 in the map: dpr step before the CSS fallback (a, recommended)", + "Q3 in the map: ground tokens on body (a, recommended)" + ] +} diff --git a/docs/cultmath-interval-ground-cut.md b/docs/cultmath-interval-ground-cut.md new file mode 100644 index 00000000..dea9827d --- /dev/null +++ b/docs/cultmath-interval-ground-cut.md @@ -0,0 +1,413 @@ +# CultMath intervals and the gamecult.org ground: cut map + +Status: Imagination pass 1, 2026-10-02. Nothing here is ruled except what the +operator said, quoted below. The campaign named here does not exist in the mind +yet; the Self admits it if the operator takes Q1. Where this map and the Body +disagree, the Body wins and this map is stale. + +Pinned HEADs (every `file:line` below is against these): + +| Repo | Ref | SHA | +| --- | --- | --- | +| CultLib | `main` | `c49c76ee` (CultMath 0.3.0 merged at `614fd445`) | +| gamecult-site | `main` | `535d170` (before `wash-home-only` lands) | +| Aetheria | local checkout | read only; `Volumetric.cginc`, `Raymarching/CloudShader.shader`, `Clouds.shader`, `Zone Display/VolumeCloudRenderer.cs` | + +## The operator's words + +1. "Can we replace the site's background with a fancy yet unobtrusive and + inexpensive shader thing? It's odd that my main site wouldn't have that, + considering my specialization. Would it be too much to have some optimized + subset of Aetheria's volumetric clouds shader in there?" +2. After the Self proposed a quarter-resolution, 8–16 step, static-on-phones + design: "map it as a cut that includes the GPU interval arithmetic we're + borrowing from Fidget for a planned Asura campaign. I'd like this shader to + be the proving ground for that - with the right math we can absolutely run + this fullscreen on mobile, per pixel as long as the sample count is low and + we're accumulating samples with TAA (Aetheria's TAA is honestly + embarrassing and it still handles smooth 1080p clouds on my tired old + 1070)" + +So: full screen, per pixel, on phones too; few samples per frame; TAA +accumulates them; interval arithmetic makes the few samples count. The +"static frame on phones" idea is overruled. The static frame survives only +under `prefers-reduced-motion`. + +## Ownership + +### Where the interval math lives + +**CultLib, `packages/cultmath`.** This is the parked campaign's own first step +(`docs/cultmath-tape-target.md`, sketch step 1: "CultMath `interval` in C# and +HLSL with parity tests ... It stands alone, and is the first cut to take even +if the rest stays parked"). Nothing about that reasoning changed. The "planned +Asura campaign" in the operator's words is that document: the tapes campaign, +whose first consumer named there is Aetheria's volumetric raymarching. Asura +itself does not need intervals (`cultmath-tape-target.md:103`). + +The site speaks WebGL2 GLSL ES 3.00, not HLSL. Three routes were weighed: + +| Route | What | Why not | +| --- | --- | --- | +| A | Hand-port the needed functions to GLSL inside gamecult-site | A second noise authority with no parity test; the exact thing Aetheria's `GPU Noise` copies are (follow-up `aetheria-snoise-pin-bump`). | +| B | `dxc -spirv` then SPIRV-Cross to GLSL ES, using the existing `tools/compile-hlsl-spirv.ps1` chain | SPIRV-Cross emits one whole shader with mangled names; there is no library a site shader can call `cultmath_snoise` from. | +| C | **A textual lowering HLSL → GLSL in CultLib, with a complete, enumerated transformation list, the same discipline as the HLSL → C# mirror (`packages/cultmath/docs/design.md:92-134`)** | Chosen. | + +Under C, `shaders/CultMath.glsl` is a committed generated artifact, like +`Swizzles.g.cs`. One implementation of the lowering lives in the test project, +a test pins the committed file equal to the lowering of `CultMath.hlsl`, and +the same test regenerates it when asked. GLSL's stricter typing (no implicit +`int`/`uint` → `float`, `step(vec4, float)` does not exist) is not patched in +the lowering: the HLSL is written in the common subset, which is legal HLSL +and bit-identical, and glslang compiles the lowered text in CultLib's tooling +so it stays there. Parity then runs in two legs, each with one owner: + +- HLSL ⇔ C#: the existing bit-for-bit mirror test, automatic for every new + function. +- GLSL ⇔ C#: a committed golden fixture (sample points and expected bit + patterns, exported from C#) that the site's Hands evaluates on WebGL2 in the + browser pane and reads back. CultLib has no GPU harness (follow-up + `gpu-snoise-parity`); the browser pane is one. This cut does not close that + follow-up, which asks for FXC-on-D3D11, but it gives it a second device. + +The site vendors `CultMath.glsl` with a header naming the CultLib commit it was +copied from. The site is a xenos consumer of CultLib at that boundary; it does +not take a package. + +### Campaign + +Recommend a **new campaign, `cultmath-tapes`**, repos `GameCult/CultLib` and +`GameCult/gamecult-site`, target doc `docs/cultmath-tape-target.md` unparked +for step 1 only (Q1). Not `asura`: Asura's target names intervals as not +needed, and its invariants are about planets. Not `site-masthead`: that +campaign is one repo and its target lists "the shader (a separate campaign if +ruled)" under `not_in_scope` (`masthead-campaign.md:822`). The site cut cites +`site-masthead:ruling:operator-chromeless-column` and depends on +`wash-home-only` landing first, because it rewrites the same six lines. + +### Owner, consumers, invariant + +- Owner: CultMath owns interval arithmetic and the noise bounds, in C# and + HLSL, with GLSL as a derived lowering. The site owns its density field, its + march, its TAA and its budget controller. CSS tokens on `body` own the + ground's colours, lights and intensity; the shader derives its uniforms from + them. +- Consumers: the site ground shader now; Aetheria's nebula raymarch at its + CultMath pin bump; the tapes campaign's HLSL interpreter later. +- Protected invariant, **`intervals-enclose`**: every interval function + returns a `[lo, hi]` that contains `f(x)` for every `x` in its input + interval or ball, in C#, HLSL and GLSL alike. A consumer that skips a region + because `hi < cutoff` has skipped nothing that was there. This is what the + site proves and what the tapes campaign inherits. + +## The authority map (all three cuts) + +- Owner: `packages/cultmath` for `iv_*` and `iv_snoise_ball`/`iv_fbm_ball`; + `GlslLowering` (test project) for `shaders/CultMath.glsl`; `custom.scss` + `body` tokens for ground colour, light colour/alpha/position/radius and + `--gamecult-wash`; `ground.js` for scheduling, budget and TAA; the two site + GLSL files for the field and the resolve. +- Inputs: CultMath reads nothing new. The lowering reads `CultMath.hlsl` and + `CultMath.Phacelle.hlsl` only. `ground.js` reads the computed `body` tokens, + `prefers-reduced-motion`, `visibilityState`, canvas size and the measured + GPU frame time. The field reads uniforms only. +- Outputs: `CultMath.glsl`; the interval functions; one canvas under the + page; a per-session measurement log (console, debug flag only). +- Derived state: the shader's palette, light geometry and intensity are + derived from the CSS tokens; nothing in JS or GLSL holds a colour. The CSS + wash is the same tokens rendered by CSS: it is the fallback, not a second + ground. `CultMath.glsl` is derived from `CultMath.hlsl`; editing it by hand + fails the pin test. The TAA history is a cache; a reset costs 32 frames and + no correctness. +- Forbidden writers: no colour literal, radius or position in `ground.js` or + the GLSL; no user-agent, platform or touch-point sniffing anywhere; no + class toggled on `body` by script; no second wash token; no page rule + setting a radial alpha (carried from `wash-home-only`); no GLSL edited by + hand; no `iv_*` function without a C# twin; no second noise copy in the + site. +- Shared paths: every ground on the site, the ritual essays included, paints + through the same tokens, in CSS and in the shader. Every route to a + reduced budget (slow device, hidden tab, reduced motion, missing WebGL2 or + half-float) goes through the one controller in `ground.js`; there is no + second "mobile" path. +- Deletion line: in the site, the six literal radial colours and the three + literal gradient stops become token references in the same commit the + tokens are declared. In CultLib nothing is deleted; the GLSL file is new and + the interval file is new. The subtraction this buys is upstream: at + Aetheria's pin bump, `Assets/Plugins/GPU Noise/*.cginc` can go, and the + tapes campaign's step 1 is already landed when it unparks. + +## The shader design + +### Density field (site-owned, in `cloud.frag.glsl`) + +The subset of Aetheria taken: `Volumetric.cginc`'s structure of a fill term +plus a coverage term shaped by noise, and `CloudShader.shader`'s transmittance +integration (`IntegrateRaymarch`, `:83-104`). Not taken: the height-field +textures, the fluid flow map, `triNoise3d`, the tint LOD lookup, the packed +depth, and the three-pass Unity plumbing. `Clouds.shader`'s `1-abs(snoise)` +envelope over an fBm is the shape of the detail term. The noise is CultMath +`cultmath_snoise` via the lowering, and nothing else. + +```text +camera at the origin, looking +z, static; the slab z in [Z0, Z1] fills the view +p(t) = dir * t + drift * time (drift slow: ~0.02 units/s) +coverage = snoise(p * F0) (one octave, F0 ~ 0.35) +occupancy = max(0, coverage - CUTOFF) * K (CUTOFF ~ 0.25: most space is empty) +detail = 1 - abs(snoise(p * F0 * 4 + 17)) (one octave; the dune envelope) +density = occupancy * mix(0.6, 1.0, detail) +colour = sum_i light_i.rgb * light_i.alpha * falloff_i(screen uv) (the three CSS lights) +``` + +Two `snoise` per dense sample, one per empty probe. The lights are the three +CSS radials with the same centre, radius and colour; a point in the volume is +"lit" by the radial falloff at its screen position, so the clouds are the wash +made structured, with no 3D lighting. + +### Interval culling along the ray + +`cultmath_iv_snoise_ball(c, r)` returns `[n(c) - L r, n(c) + L r] ∩ [-1, 1]`, +where `L` is CultMath's committed Lipschitz constant for `snoise(float3)`. Over +a ray segment `[t, t + Δ]` the ball is centred at `t + Δ/2` with radius `Δ/2`, +scaled by `F0`. The march is adaptive subdivision, which is Fidget's region +test on a 1-D region: + +```text +Δ = Δ0; t = Z0/dir.z + jitter * Δ0 +while t < t_exit and evals < S: + iv = iv_snoise_ball(p(t + Δ/2) * F0, F0 * Δ/2) -- 1 eval + if iv.hi < CUTOFF: t += Δ; Δ = min(Δ * 2, ΔMAX) -- provably empty: skip, grow + elif Δ > ΔDENSE: Δ = Δ / 2 -- maybe dense: refine + else: integrate density(p(t + Δ/2)) over Δ; t += Δ -- 1 more eval + if transmittance < 0.02: break +if t < t_exit: integrate one coarse sample over the rest -- the budget ran out; measured, must be rare +``` + +The `iv.hi < CUTOFF` test is the interval proof that the `0` branch of +`max(0, coverage - CUTOFF)` wins on the whole segment: Fidget's `min`/`max` +pruning rule at its smallest, applied to a two-clause expression by hand. Tape +and automatic pruning stay parked; this cut proves the arithmetic they rest on. + +### Step budget + +`S` is the per-pixel, per-frame evaluation budget (each `snoise` call is one +eval, so a dense sample costs 2). `S = 16` on desktop, `S = 8` on a phone, +`S = 4` the floor; the controller sets it from measurement, not from the +device. A debug mode writes `evals / S` and an "unfinished ray" flag into the +colour so Hands can read back the mean and the unfinished fraction. The +contract: at the chosen `S` on the shipped field, under 1% of rays are +unfinished. + +### TAA + +The camera never moves and the canvas is fixed, so there is no reprojection: +history is the same pixel. What remains is temporal supersampling with +rejection: + +- Jitter: a Halton(2,3) frame offset for the ray start, plus interleaved + gradient noise per pixel, rotated per frame, so neighbours decorrelate. +- Accumulation: `α = max(1 / frames, 1/32)`: the first frames converge fast, + then settle. The accumulated value is colour plus transmittance. +- Rejection: a 3×3 min/max box of the current frame clamps the history + (AABB clamp, not variance clipping). The field's drift is slow enough that + the clamp only bites where the field really changed. +- Reset on resize, on a token change (route change: Quartz has `enableSPA: + false` at `quartz.config.ts:15`, so a route change is a page load and the + reset is free) and on the first frame. +- Buffers: two RGBA16F history targets at canvas size. 8-bit history stalls + convergence at `α = 1/32` for a ground this dark, so half-float is required; + if `EXT_color_buffer_half_float` is missing, the controller falls back to + the CSS wash. + +What is not copied from Aetheria's `CloudShader.shader` pass 2: variance +clipping at `γ = 0.5` on an undersampled input (`:303-308`), a fixed 5% blend +with out-of-bounds forced to 100% (`:311`), the packed depth/density float +(`:181`, `:270`), and the bug at `:311`, which blends the alpha with +`density2`, the last 3×3 neighbour's density from the loop above, not the +pixel's own. + +### Resolution + +Full device pixels: `canvas.width = innerWidth * devicePixelRatio`. The +controller's steps are in order: lower `S` (16 → 8 → 4), then render at CSS +pixels (`dpr = 1`), then the CSS wash. The second step is Q2. + +### Palette and intensity + +Fifteen tokens on `body` in `custom.scss`, read by CSS and by `ground.js`: + +```text +--gamecult-ground-0/1/2 three gradient stop colours (#03070d #07111a #09141f) +--gamecult-light-N "255 138 42" (N = 0..2) +--gamecult-light-N-a 0.18 +--gamecult-light-N-at "78% 14%" +--gamecult-light-N-r "18%" (or a length; the ritual ground uses rem) +--gamecult-wash from wash-home-only: 1 on /, 0.5 elsewhere +``` + +The CSS radials and the linear gradient reference the tokens. The ritual essays' +block overrides the tokens instead of painting its own ground, which deletes +its three literal radials. `ground.js` resolves `%` radii as CSS does (circle, +farthest corner of the body's background positioning area) and lengths through +the root font size. The parity test: with density forced to 0 the canvas equals +the CSS wash within 2/255 per channel at 16 probe points, home and ritual. +Intensity multiplies the cloud term; at 0 both paths show the plain gradient. + +### Pausing and fallbacks + +- `visibilityState !== "visible"`: no frames. On return, keep history. +- `prefers-reduced-motion: reduce`: drift is 0, render until 32 accumulated + frames, then stop; resize re-renders. The clouds are still there, still. +- No WebGL2, context lost, no half-float: canvas removed, CSS wash shows. +- Too slow: measured, see below. Never a user-agent branch. +- The canvas is `position: fixed; inset: 0; z-index: -1; pointer-events: none; + aria-hidden`. The root background paints first, so the canvas covers the CSS + wash only once it has drawn; until then, and if it never does, the wash is + what the reader sees. + +### Text contrast + +The shader clamps its output so relative luminance never exceeds 0.035, about +the current orange hotspot (`#07111a` plus `rgba(255,138,42,.18)` is roughly +`(53, 42, 34)`, luminance 0.025). Body text `#b7c7d9` (luminance 0.55) keeps a +contrast ratio of at least 7:1 against any ground pixel. A readback test +asserts the max over the canvas after 32 frames on `/` at intensity 1. + +## Budget and how it is measured + +| Device | Pixels | GPU per frame at 30 fps | Proxy | +| --- | --- | --- | --- | +| Desktop, GTX 1070 class, 2560×1440 | 3.7 M | ≤ 1.0 ms | 3% GPU duty | +| Laptop iGPU, Iris Xe, 1920×1080 at dpr 1.25 | 3.2 M | ≤ 3.0 ms | 9% duty | +| Mid-range phone, Pixel 6a / Galaxy A54 class, 1080×2400 | 2.6 M | ≤ 4.0 ms | ≤ 12% duty; no upward drift of the median over 5 minutes (a thermal detector by measurement, not a sensor) | + +The cost model that sizes `S`: one 3D simplex is ~150 flops; a phone GPU +delivers ~1 TFLOP; 2.6 M × 8 evals × 150 is 3.1 GFLOP, about 3 ms, plus ~1 ms +for the resolve pass (10 texel reads per pixel). Those are estimates; the +measurements replace them. + +Measurement, in this order of preference, all in `ground.js` behind a debug +flag and used by the controller: + +1. `EXT_disjoint_timer_query_webgl2` where present (Chrome desktop): + per-frame GPU time of the march pass and the resolve pass. +2. A `fenceSync` after the resolve pass, polled; the time from issue to + signalled is the GPU time when the queue is otherwise empty, which a + background page's queue is. Available on every WebGL2, including Safari + and phones. +3. `requestAnimationFrame` cadence as the last signal: if frames are + delivered under 24 fps for 30 consecutive frames while the page is idle, + the controller steps down. + +Hands proves it in the browser pane: desktop numbers from the pane with the +timer query, phone numbers from the pane's mobile viewport emulation for the +pixel count and from the operator's phone for the real GPU time (operator +verification). Each landed number goes into the cut report, not into prose. + +## The proving-ground contract (what Asura and the tapes campaign inherit) + +1. **Enclosure tests in C#** (and so in HLSL by the mirror): for every `iv_*` + op, random intervals and random points inside them, `f(x) ∈ op(I)`. For + `iv_snoise_ball` and `iv_fbm_ball`, 2,000 random balls with 64 points each. + A mutant that shrinks any bound dies. +2. **The Lipschitz constant has provenance**: `CULTMATH_SNOISE_LIPSCHITZ` is + the max of `|snoise_grad|` over 10⁶ random points refined by gradient + ascent, times a stated margin (1.10). The test that measures it is + committed and the constant is pinned by a test that fails if any sampled + gradient exceeds it. It is empirical with a margin, not a proof; the map + says so, and the enclosure tests are the defence. +3. **Tightness is a number**: the mean ratio of interval width to the true + range over the sampled balls, printed by a committed test and quoted in + the cut report, so a later affine-arithmetic cut has something to beat. +4. **The saving is a number**: a C# test marches 1,000 random rays through a + representative coverage field with and without interval skipping and + asserts at least a 2× reduction in evaluations; the real field's mean + evals per pixel and unfinished-ray fraction come from the browser readback. +5. **Three runtimes agree**: the GLSL golden fixture (256 points, bit + patterns from C#) passes on WebGL2 within 1 ulp for the integer-hash paths + and a stated tolerance for the transcendental ones, with the tolerance and + the device named in the report. + +What this cut does **not** prove, said plainly: tape evaluation, automatic +pruning, the `min`/`max` choice tracking, and interval ops over anything but +plain `[lo, hi]`. Those unpark with steps 2–4. + +## Cut order + +```text +glsl-lowering (CultLib) ─┐ +interval-ops (CultLib) ─┴─> site-ground (gamecult-site, after wash-home-only) +``` + +Three cuts, not one. One cut would be three repos' worth of concerns and +three Soul vocabularies (a text transformer, numerical bounds, a browser +budget); CultMath cuts have overrun 2× when they carried two concerns +(`Asura cut-map.md:131`). `glsl-lowering` and `interval-ops` are independent +and can run in parallel worktrees; `interval-ops` gets its GLSL for free from +the lowering test once both are on `main`. No CultMath release is in this +sequence: the site consumes a commit, not a package. The next CultMath release +carries the intervals to Unity consumers. + +Specs: `docs/cultmath-interval-ground-cut-glsl-lowering.spec.json`, +`docs/cultmath-interval-ground-cut-interval-ops.spec.json`, +`docs/cultmath-interval-ground-cut-site-ground.spec.json`. + +## Standing design decisions (means; Self may overrule) + +- D1. Intervals are `float2(lo, hi)`. Affine arithmetic is not taken; the + tightness number from the contract says whether it is ever worth it. +- D2. No `iv_*` function has a value-only or gradient twin. The bounds take + the point value only; `snoise_grad` is used by the Lipschitz test, not by + the bound. +- D3. The site vendors `CultMath.glsl` by CultLib commit, with the SHA in the + file header and a check in the site cut that the bytes equal CultLib's at + that SHA. A build-time fetch would make the site's build depend on another + repo being reachable. +- D4. The ground shader is opaque and reproduces the gradient and the lights + from the tokens. A transparent canvas over the CSS wash would need the CSS + radials hidden by a class (two ground states, a flash on load), and parsing + the computed `background-image` string would make the palette authority a + serializer's whim. +- D5. The history reset on token change is a page load, because SPA is off. If + SPA is ever enabled, `ground.js` listens for Quartz's `nav` event and + re-reads the tokens; the spec names the hook so it is not forgotten. +- D6. The budget controller holds state for the session only (no storage). + Measuring costs under a second and a stored verdict would outlive a driver + update. + +## Questions + +**Q1. Campaign home.** +- (a) New campaign `cultmath-tapes`, target `docs/cultmath-tape-target.md` + unparked for step 1, repos CultLib and gamecult-site. **Recommended.** It is + the campaign the operator called "planned", and the site is its first + consumer. +- (b) File the CultLib cuts under `asura` as 2a-iii and the site cut under + `site-masthead`. Rejected: both targets say this work is not theirs. + +**Q2. The second step of the slow-device ladder.** +- (a) After `S` hits its floor, render at CSS pixels (`dpr = 1`) before giving + up to the CSS wash. **Recommended.** It is still a measured response, and a + 2× pixel cut is a 2× GPU cut, which keeps clouds on more phones. +- (b) Never drop below device pixels; a device that fails at `S = 4` gets the + CSS wash. Purer to the order, but it loses the phones one notch too slow. + +**Q3. Ground authority in CSS.** +- (a) Fifteen tokens on `body`, referenced by the CSS gradients and read by + the shader; the ritual block overrides tokens. **Recommended.** One + definition of the ground, two renderers. +- (b) Keep the literals in CSS and duplicate the palette in `ground.js`. + Rejected: the brand doc says the brand is defined in `custom.scss`; a copy + in JS is a second authority that drifts. + +## Unsettled + +- The Lipschitz constant is empirical with a margin. If a reader wants a + proof, the Ashima kernel's gradient is a bounded polynomial per simplex + cell and a proof is possible; it is not in this cut. +- The ritual ground's radii are `rem` lengths and its gradient has three + stops but the first has no position (`custom.scss:124`). Hands normalises + it to three positioned stops when tokenising; the appearance is unchanged. +- Whether GameCult-Quartz's bundler lets a component's `afterDOMLoaded` do a + dynamic `import()` of a static module, or whether the loader must be a + classic script tag in `Head`. Hands reads the engine; both are one line.