@wave3d/core 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"shaders.js","names":[],"sources":["../../src/renderer/shaders.ts"],"sourcesContent":["import { MAX_COLORS, MAX_LIGHTS, MAX_MESH_POINTS, MAX_NOISE_BANDS } from \"../config/model\";\nimport { RIBBON_Z_CENTER } from \"./WaveGeometry\";\n\n/**\n * The wave shaders. Vertex: a flat plane is Y-displaced by simplex noise, then\n * twisted by three axis-rotations `freq * expStep(uv, power)` where\n * `expStep(x,n) = exp2(-exp2(n)*pow(x,n))` is a falloff (rotation concentrated at\n * the uv=0 edge), with diagonal axes + an animated X wobble. Fragment: uses NO\n * normal-based lighting — \"thickness\" comes from `crease`, a foreshorten/fold\n * detector built from `dFdy(uv)`, used to lift flat areas toward white\n * (`col += (1-crease)*0.25`) and to localise the striations. Striations are subtle\n * high-frequency simplex noise ADDED to the colour, colour-matched via (1-blue)\n * and end-weighted via a parabola — so they blend rather than form hard lines.\n * Our additions: gradient stops/types for colour, and an optional additive light\n * layer (kept gentle so the default look is preserved).\n */\n\n// Noise function: xxHash-seeded unit-vector gradients + a Gustavson simplex. It uses\n// GLSL ES 3.00 integer ops (floatBitsToUint, unsigned bit-shifts) — available with no\n// glslVersion change because three compiles non-raw ShaderMaterials as \"#version 300 es\"\n// already. `hash` returns a vec2 here — the cheap grain hash in the fragment is named\n// `grainHash` to avoid clashing with it.\nconst simplex2d = /* glsl */ `\nfloat xxhash(vec2 x){\n uvec2 t = floatBitsToUint(x);\n uint h = 0xc2b2ae3du * t.x + 0x165667b9u;\n h = (h << 17u | h >> 15u) * 0x27d4eb2fu;\n h += 0xc2b2ae3du * t.y;\n h = (h << 17u | h >> 15u) * 0x27d4eb2fu;\n h ^= h >> 15u;\n h *= 0x85ebca77u;\n h ^= h >> 13u;\n h *= 0xc2b2ae3du;\n h ^= h >> 16u;\n return uintBitsToFloat(h >> 9u | 0x3f800000u) - 1.0;\n}\nvec2 hash(vec2 x){\n float k = 6.283185307 * xxhash(x);\n return vec2(cos(k), sin(k));\n}\nfloat simplexNoise(in vec2 p){\n const float K1 = 0.366025404; // (sqrt(3)-1)/2\n const float K2 = 0.211324865; // (3-sqrt(3))/6\n vec2 i = floor(p + (p.x + p.y) * K1);\n vec2 a = p - i + (i.x + i.y) * K2;\n float m = step(a.y, a.x);\n vec2 o = vec2(m, 1.0 - m);\n vec2 b = a - o + K2;\n vec2 c = a - 1.0 + 2.0 * K2;\n vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);\n vec3 n = h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0)));\n return dot(n, vec3(32.99)); // analytic factor (= 2916*sqrt(2)/125)\n}\n`;\n\n// Uniforms shared by BOTH fragment shaders (solid + wireframe line): the palette/gradient\n// inputs and the colour-grade knobs. Each shader declares its theme-specific uniforms beside\n// this block. Requires MAX_COLORS / MAX_MESH_POINTS #defines.\nconst colorUniforms = /* glsl */ `\nuniform vec3 uColors[MAX_COLORS];\nuniform float uColorPos[MAX_COLORS];\nuniform int uColorCount;\nuniform int uGradType;\nuniform float uGradAngle;\nuniform float uGradShift;\nuniform vec2 uMeshPointPos[MAX_MESH_POINTS];\nuniform vec3 uMeshPointColor[MAX_MESH_POINTS];\nuniform float uMeshPointInfluence[MAX_MESH_POINTS];\nuniform int uMeshPointCount;\nuniform float uMeshSoftness;\nuniform sampler2D uPalette; // baked 2D palette texture\nuniform float uUsePalette; // >0.5 = sample the texture; else procedural grad()\nuniform float uPaletteRaw; // >0.5 = sample palette by raw (uv.x,uv.y), not gradCoord\nuniform vec2 uPaletteScale;\nuniform vec2 uPaletteOffset;\nuniform float uPaletteRotation;\nuniform float uHueShift;\nuniform float uContrast;\nuniform float uSaturation;\nuniform float uOpacity;\nuniform float uSquared; // 1 = square the output colour (the deep \"squared\" hero look)\n`;\n\n// Colour helpers + the palette/gradient sampler shared by both fragment shaders.\n// Interpolate AFTER ${\"simplex2d\"} and ${\"colorUniforms\"} (gradCoord needs both) and a PI define.\nconst colorFns = /* glsl */ `\nvec3 contrastFn(vec3 v, float a){ return (v - 0.5) * a + 0.5; }\nvec3 desaturate(vec3 color, float factor){\n vec3 gray = vec3(dot(vec3(0.299, 0.587, 0.114), color));\n return mix(color, gray, factor);\n}\nvec3 hueShift(vec3 color, float shift){\n vec3 g = vec3(0.57735);\n vec3 proj = g * dot(g, color);\n vec3 U = color - proj;\n vec3 W = cross(g, U);\n return U * cos(shift) + W * sin(shift) + proj;\n}\n\n// Our gradient: interpolate stops by their positions (uColorPos sorted ascending).\nvec3 grad(float u){\n u = clamp(u, 0.0, 1.0);\n vec3 col = uColors[0];\n for (int i = 0; i < MAX_COLORS - 1; i++){\n if (i >= uColorCount - 1) break;\n float p0 = uColorPos[i];\n float p1 = uColorPos[i + 1];\n if (u >= p0){\n float t = clamp((u - p0) / max(p1 - p0, 1e-5), 0.0, 1.0);\n col = mix(uColors[i], uColors[i + 1], t);\n }\n }\n return col;\n}\n\n// iOS-style 2D colour field. Each control point contributes an inverse-distance\n// weight; normalising the sum fills the whole surface without dark seams.\nvec3 meshGradient(vec2 uv){\n vec3 colorSum = vec3(0.0);\n float weightSum = 0.0;\n float exponent = mix(4.8, 1.35, clamp(uMeshSoftness, 0.0, 1.0));\n for (int i = 0; i < MAX_MESH_POINTS; i++){\n if (i >= uMeshPointCount) break;\n float influence = max(uMeshPointInfluence[i], 0.05);\n float distanceFromPoint = length(uv - uMeshPointPos[i]) / influence;\n float weight = 1.0 / (pow(max(distanceFromPoint, 0.012), exponent) + 0.002);\n colorSum += uMeshPointColor[i] * weight;\n weightSum += weight;\n }\n return colorSum / max(weightSum, 0.0001);\n}\n\n// Map a surface uv to the 0–1 gradient coordinate per gradient type. uGradShift\n// adds a low-frequency simplex warp so the colour varies in 2D (along the length\n// as well as across the width) — a 2D palette feel instead\n// of flat 1-D bands.\nfloat gradCoord(vec2 uv){\n float warp = uGradShift * simplexNoise(uv * 1.6 + 4.0);\n if (uGradType == 1){ return clamp(length(uv - 0.5) * 2.0 + warp, 0.0, 1.0); } // radial\n if (uGradType == 2){ return fract(atan(uv.y - 0.5, uv.x - 0.5) / (2.0 * PI) + 0.5 + warp); } // conic\n vec2 dir = vec2(sin(uGradAngle), cos(uGradAngle)); // linear, angled\n return clamp(dot(uv - 0.5, dir) + 0.5 + warp, 0.0, 1.0);\n}\n\n// One base-colour sample for the whole surface: rotate/scale/offset the raw-palette uv,\n// then pick the mesh field / baked 2D texture / procedural stops by mode. The raw palette\n// is sampled by (uv.x, uv.y) directly; the stops-generated texture is sampled via\n// gradCoord so its angle/type/warp still apply.\nvec3 waveBaseColor(vec2 uv){\n float gc = gradCoord(uv);\n vec2 mediaUv = uv - 0.5;\n float mediaCos = cos(uPaletteRotation);\n float mediaSin = sin(uPaletteRotation);\n mediaUv = vec2(\n mediaCos * mediaUv.x + mediaSin * mediaUv.y,\n -mediaSin * mediaUv.x + mediaCos * mediaUv.y\n );\n mediaUv = mediaUv * uPaletteScale + 0.5 + uPaletteOffset;\n vec2 puv = uPaletteRaw > 0.5\n ? clamp(mediaUv, 0.0, 1.0)\n : vec2(gc, clamp(uv.y, 0.0, 1.0));\n return uGradType == 3\n ? meshGradient(uv)\n : (uUsePalette > 0.5 ? texture2D(uPalette, puv).rgb : grad(gc));\n}\n\n// The shared colour grade: contrast → desaturate → hue rotate (degrees).\nvec3 applyColorGrade(vec3 c){\n c = contrastFn(c, uContrast);\n c = desaturate(c, 1.0 - uSaturation);\n return hueShift(c, radians(uHueShift));\n}\n`;\n\n// The shared wave-shape deform (expStep + rotationMatrix + waveShape), used by BOTH the wave\n// vertex shader and the particle shed emitter, so the ribbon and the dust it sheds ride ONE deform.\nconst waveShapeChunk = /* glsl */ `\n// expStep: a falloff from 1 (at x=0) toward 0, sharpness set by n. The\n// max() guards pow(0, n) (= Infinity → NaN) so negative n is safe — negative n\n// just concentrates the twist toward the OTHER end instead.\nfloat expStep(float x, float n){ return exp2(-exp2(n) * pow(max(x, 1.0e-3), n)); }\n\n// rotationMatrix (mat4), used row-vector style: pos = (vec4(pos,1) * R).xyz\nmat4 rotationMatrix(vec3 axis, float angle){\n axis = normalize(axis);\n float s = sin(angle), c = cos(angle), oc = 1.0 - c;\n return mat4(\n oc*axis.x*axis.x + c, oc*axis.x*axis.y - axis.z*s, oc*axis.z*axis.x + axis.y*s, 0.0,\n oc*axis.x*axis.y + axis.z*s, oc*axis.y*axis.y + c, oc*axis.y*axis.z - axis.x*s, 0.0,\n oc*axis.z*axis.x - axis.y*s, oc*axis.y*axis.z + axis.x*s, oc*axis.z*axis.z + c, 0.0,\n 0.0, 0.0, 0.0, 1.0\n );\n}\n\n// The wave SHAPE deform, shared by the wave vertex shader (below) and the particle SHED emitter\n// (particleVertexShader): a base hairpin position + its uv → the displaced / helixed / twisted /\n// fanned LOCAL position, plus the three twist matrices (the pointer field reads them). Every branch\n// sits behind the SAME #ifdef gates as the code it replaces, so a given compiled program is\n// byte-identical to the former inline version. t / loopOff are the linear / orbit time the\n// caller computed; only the one selected by LOOP_MOTION is read (the other is a dead argument).\nstruct WaveShape { vec3 pos; mat4 rotA; mat4 rotB; mat4 rotC; };\nWaveShape waveShape(vec3 position, vec2 uv, float t, vec2 loopOff){\n // Displacement lifts Y by simplex noise of the (x,z) position.\n vec3 pos = position;\n#ifdef LOOP_MOTION\n pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX, pos.z * uDispFreqZ) + loopOff);\n#else\n pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX + t, pos.z * uDispFreqZ + t));\n#endif\n#ifdef DETAIL_OCTAVE\n // A second, finer octave riding on the broad swell (loop-orbit shared so it stays periodic).\n#ifdef LOOP_MOTION\n pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq, pos.z * uDetailFreq) + loopOff);\n#else\n pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq + t, pos.z * uDetailFreq + t));\n#endif\n#endif\n\n#ifdef HELIX\n // Helix — the periodic sweep the three twists (monotone falloffs) can't reach. Runs AFTER the\n // displacement (so the noise still samples undeformed pos) and BEFORE the twist (so they compose).\n float hAng = 6.28318530718 * uHelixTurns * uv.y + radians(uHelixPhase);\n // Roll about the ribbon's width centre, not the origin — see RIBBON_Z_CENTER in WaveGeometry.\n float rollA = hAng * uHelixRoll;\n float rollC = cos(rollA), rollS = sin(rollA);\n vec2 rel = vec2(pos.y, pos.z - ${RIBBON_Z_CENTER.toFixed(1)});\n pos.y = rel.x * rollC - rel.y * rollS;\n pos.z = ${RIBBON_Z_CENTER.toFixed(1)} + rel.x * rollS + rel.y * rollC;\n pos.y += uHelixRadius * cos(hAng);\n pos.z += uHelixRadius * sin(hAng);\n#endif\n\n // The X-twist frequency feeding rotB; the TWIST_MOTION variant modulates it with simplex noise\n // indexed along the ribbon (uv.y) so the twist breathes over time.\n float twistXFreq = uTwFreqX;\n#ifdef TWIST_MOTION\n#ifdef LOOP_MOTION\n float twistXNoise = simplexNoise(vec2(uv.y * 2.0, 0.0) + loopOff);\n#else\n float twistXNoise = simplexNoise(vec2(uv.y * 2.0, t));\n#endif\n twistXFreq = uTwFreqX - twistXNoise * 0.1;\n#endif\n\n // Three-axis twist (see the falloff-axis note: rotA keys off uv.x/WIDTH, rotB/rotC off uv.y/LENGTH).\n mat4 rotA = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqY * expStep(uv.x, uTwPowY));\n mat4 rotB = rotationMatrix(vec3(0.0, 0.5, 0.5), twistXFreq * expStep(uv.y, uTwPowX));\n mat4 rotC = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqZ * expStep(uv.y, uTwPowZ));\n pos = (vec4(pos, 1.0) * rotA).xyz;\n pos = (vec4(pos, 1.0) * rotB).xyz;\n pos = (vec4(pos, 1.0) * rotC).xyz;\n\n#ifdef RADIAL\n // Radial fan: remap the ribbon to polar around the LOCAL origin so its LENGTH fans into a plume.\n // uv.x (folded WIDTH) → fan ANGLE across uRadialArc; uv.y (LENGTH) → RADIUS, so a constant-uv.x\n // combed fiber becomes a constant-angle radial spoke. mix(pos, fanned, 0) is identity → off is\n // byte-identical. (Placement is the wave's position transform — the fan has no separate pivot.)\n {\n float rAng = radians(uRadialCenter) + (clamp(uv.x, 0.0, 1.0) - 0.5) * radians(uRadialArc);\n float rRho = uRadialRadius + uv.y * 400.0 * uRadialSpread; // 400 = native ribbon length\n vec3 rEr = vec3(cos(rAng), sin(rAng), 0.0); // radial dir, in local X–Y (screen plane)\n vec3 rEt = vec3(-sin(rAng), cos(rAng), 0.0); // tangential\n vec3 fanned = rEr * rRho\n + rEt * (pos.z - ${RIBBON_Z_CENTER.toFixed(1)}) * 0.5\n + vec3(0.0, 0.0, pos.y);\n pos = mix(pos, fanned, clamp(uRadialAmount, 0.0, 1.0));\n }\n#endif\n\n WaveShape s;\n s.pos = pos;\n s.rotA = rotA;\n s.rotB = rotB;\n s.rotC = rotC;\n return s;\n}\n`;\n\nexport const vertexShader = /* glsl */ `\n${simplex2d}\n\nuniform float uTime, uSpeed, uSeed;\nuniform float uDispFreqX, uDispFreqZ, uDispAmount;\nuniform float uDetailFreq, uDetailAmount; // 2nd displacement octave (only read under DETAIL_OCTAVE)\nuniform float uTwFreqX, uTwFreqY, uTwFreqZ, uTwPowX, uTwPowY, uTwPowZ;\nuniform float uLoopSeconds; // seamless-loop period (only read under LOOP_MOTION)\n\n// Helix (optional). Behind HELIX so a wave without one compiles the exact same program — same\n// byte-identity contract as the pointer block below.\n#ifdef HELIX\nuniform float uHelixTurns; // full turns from one end of the ribbon to the other\nuniform float uHelixRadius; // orbit radius: carries the whole ribbon around the axis\nuniform float uHelixRoll; // cross-section roll, as a fraction of the turns (1 = rigid ladder)\nuniform float uHelixPhase; // degrees\n#endif\n\n// Radial fan (optional). Behind RADIAL so a wave without one compiles the exact same program (same\n// byte-identity contract as HELIX / POINTER_FX above).\n#ifdef RADIAL\nuniform float uRadialAmount; // 0..1 blend (0 = identity)\nuniform float uRadialArc; // fan spread, degrees\nuniform float uRadialSpread; // length → radius scale\nuniform float uRadialRadius; // source / inner radius\nuniform float uRadialCenter; // base angle, degrees\n#endif\n\nvarying vec2 vUv;\nvarying vec3 vWorldPos;\nvarying vec3 vViewDir;\nvarying vec4 vClipPosition; // = gl_Position, for the wireframe theme's depth fade\n\n// Pointer field (optional, additive). ALL declarations here sit behind POINTER_FX so a wave with\n// no interaction config compiles the exact same program (JS-side uniform entries are always present\n// — see makeUniforms — but three only uploads uniforms the compiled program actually declares).\n#ifdef POINTER_FX\nuniform vec2 uPointer; // smoothed pointer, NDC (-1..1)\nuniform float uPointerActive; // presence ramp 0..1 × per-wave influence\nuniform float uPointerRadius; // falloff radius in NDC-y units (config radius × 2)\nuniform float uPointerAspect; // drawing-buffer dw/dh (circular screen falloff)\nuniform float uPointerAgitate;\nuniform float uPointerPush; // signed membrane dome at the cursor (+ repel / − attract)\nuniform float uPointerWake; // drag-wake trough amplitude (behind the moving cursor)\nuniform vec2 uPointerVel; // smoothed pointer velocity, NDC/s (drag-wake direction)\n// Ribbon flow: stretch the falloff along the strip's length axis so the field reaches ALONG the\n// ribbon rather than as a screen disc. 0 = the plain circular smoothstep (byte-identical when off).\nuniform float uShapeFlow;\nvarying float vPointerFall; // falloff × presence — consumed by both fragment themes\n#ifdef POINTER_RIPPLES\nuniform vec2 uRippleOrigin[4]; // NDC\nuniform float uRippleAge[4]; // seconds since spawn (CPU-computed)\nuniform float uRippleAmp[4]; // shared 0..1 decay envelope per slot (CPU-computed; 0 = slot free)\nuniform float uPointerRipple; // THIS wave's ripple amplitude (scales the shared envelope)\nconst float RIPPLE_WAVE_SPEED = 0.85; // NDC/s the ring crest travels outward\nconst float RIPPLE_SIGMA = 0.14; // gaussian half-width of the travelling packet (NDC)\nconst float RIPPLE_FREQ = 11.0; // oscillation within the packet (one crest + faint troughs)\nconst float RIPPLE_MAX_R = 1.2; // reach where the crest has fully left the frame\n#endif\n#endif\n\n${waveShapeChunk}\n\nvoid main(){\n vUv = uv;\n#ifndef LOOP_MOTION\n float t = uTime * uSpeed + uSeed;\n vec2 loopOff = vec2(0.0); // unused under linear time; kept so waveShape's signature is uniform\n#endif\n\n#ifdef LOOP_MOTION\n // Seamless loop: rather than scrolling the noise field linearly by t (which never repeats),\n // sample it on a circle of radius loopR at angle loopTheta — exactly periodic with period\n // uLoopSeconds. The tangential speed loopR·dθ/dt equals uSpeed, so the looped motion advances\n // at the same rate as the linear drift, just curved into a closed orbit (it orbits rather than\n // drifts — the trade-off for a seamless loop, hence opt-in). uSeed offsets the phase so stacked\n // waves keep their relative motion while sharing the single period.\n float loopTheta = uTime * (6.28318530718 / uLoopSeconds) + uSeed;\n float loopR = uSpeed * uLoopSeconds * 0.159154943092; // = uSpeed·uLoopSeconds / (2π)\n vec2 loopOff = loopR * vec2(cos(loopTheta), sin(loopTheta));\n float t = 0.0; // unused under loop time\n#endif\n\n // Deform the baked hairpin via the shared waveShape chunk (displacement + helix + twist + radial),\n // which also drives the particle shed emitter. It returns the deformed local pos + the twist\n // matrices the pointer field reads below.\n WaveShape ws = waveShape(position, uv, t, loopOff);\n vec3 pos = ws.pos;\n\n#ifdef POINTER_FX\n // Pointer field: displace along the wave's own (post-twist) up-axis, weighted by a screen-space\n // falloff around the smoothed cursor — a circle at uShapeFlow 0, stretched along the ribbon as it\n // rises. Everything here is ADDITIVE and fenced, so the shared path above/below is untouched and\n // byte-identical when POINTER_FX is off.\n // Shared clip-space transform, computed once and reused for the cursor metric and the ribbon\n // tangent (the compiler is not guaranteed to CSE the triple product otherwise). Associativity is\n // unchanged, so preClip is bit-for-bit what the plain P*V*M*v product produced.\n mat4 mvp = projectionMatrix * viewMatrix * modelMatrix;\n vec4 preClip = mvp * vec4(pos, 1.0);\n // Screen-space offset from the cursor (aspect-corrected → round in pixels). The DEFAULT metric.\n vec2 ndcHere = preClip.xy / max(preClip.w, 1.0e-6);\n vec2 dp = (ndcHere - uPointer) * vec2(uPointerAspect, 1.0);\n // Ribbon flow: stretch the metric along the strip's own LENGTH axis so the field reaches ALONG the\n // ribbon and stays tight across it — the \"flows with the material\" feel, per-vertex (so it follows\n // the strip's curve) with no CPU surface pick. The length axis is local +X (uv.x runs with x)\n // carried through the SAME twist as the surface. The camera is orthographic (affine, w=1), so the\n // axis's screen image is the linear map of the DIRECTION (w=0): one mat·dir, no second\n // point-projection and no perspective divide. (A true per-pixel uv would need GPU picking — the\n // visible surface is shader-displaced, so a CPU raycast of the base geometry misses.)\n if (uShapeFlow > 0.0) {\n vec3 tangentLocal = (((vec4(1.0, 0.0, 0.0, 0.0) * ws.rotA) * ws.rotB) * ws.rotC).xyz;\n vec2 tang = (mvp * vec4(tangentLocal, 0.0)).xy * vec2(uPointerAspect, 1.0);\n float tl = length(tang);\n if (tl > 1.0e-6) {\n tang /= tl;\n vec2 nrm = vec2(-tang.y, tang.x);\n dp = vec2(dot(dp, tang) / (1.0 + uShapeFlow * 2.5), dot(dp, nrm)); // up to 3.5× reach along length\n }\n }\n float fall = smoothstep(uPointerRadius, 0.0, length(dp));\n vPointerFall = fall * uPointerActive;\n // Displacement axis = local +Y carried through the SAME three twist rotations as pos (row-vector\n // convention). Rotations are linear, so post-twist axis displacement equals pre-twist Y displacement.\n vec3 dispAxis = (((vec4(0.0, 1.0, 0.0, 0.0) * ws.rotA) * ws.rotB) * ws.rotC).xyz;\n // Agitation: a fast churn octave near the cursor (additive — never rewrites base noise t, which\n // would force restructuring the shared path). Loop-safe under both time variants.\n#ifdef LOOP_MOTION\n float disp = uPointerAgitate * vPointerFall\n * simplexNoise(vec2(pos.x * uDispFreqX * 3.0, pos.z * uDispFreqZ * 3.0) + loopOff * 4.0);\n#else\n float disp = uPointerAgitate * vPointerFall\n * simplexNoise(vec2(pos.x * uDispFreqX * 3.0 + t * 4.0, pos.z * uDispFreqZ * 3.0));\n#endif\n // Membrane push/pull: a smooth dome (vPointerFall is the falloff) that swells toward you (+ repel)\n // or dents away (− attract) at the cursor, riding along with the sprung field.\n disp += uPointerPush * vPointerFall;\n // Drag-wake: pull the surface just BEHIND the moving cursor into a trailing trough. dp points\n // from cursor to vertex; \"behind\" is how far the vertex sits opposite the velocity (0 ahead → 1 a\n // radius behind), gated by speed so it only forms while dragging and heals when the cursor stops.\n vec2 velC = uPointerVel * vec2(uPointerAspect, 1.0);\n float wakeSpeed = length(velC);\n if (uPointerWake != 0.0 && wakeSpeed > 1.0e-4) {\n float behind = clamp(dot(-dp, velC) / (wakeSpeed * uPointerRadius), 0.0, 1.0);\n disp -= uPointerWake * vPointerFall * behind * smoothstep(0.05, 0.6, wakeSpeed);\n }\n#ifdef POINTER_RIPPLES\n for (int i = 0; i < 4; i++) {\n if (uRippleAmp[i] > 0.0) {\n float rd = length((preClip.xy / max(preClip.w, 1.0e-6) - uRippleOrigin[i]) * vec2(uPointerAspect, 1.0));\n // A wave PACKET whose crest travels outward at RIPPLE_WAVE_SPEED: a gaussian window centred on\n // the moving front carrying a short oscillation (a raised ring with faint trailing troughs),\n // so the energy radiates instead of throbbing at the click point. The shared uRippleAmp\n // envelope fades the whole packet over its lifetime; reach fades it as the crest leaves frame.\n float front = uRippleAge[i] * RIPPLE_WAVE_SPEED;\n float band = rd - front;\n float packet = exp(-band * band / (2.0 * RIPPLE_SIGMA * RIPPLE_SIGMA)) * cos(band * RIPPLE_FREQ);\n float reach = 1.0 - smoothstep(RIPPLE_MAX_R * 0.7, RIPPLE_MAX_R, front);\n disp += uPointerRipple * uRippleAmp[i] * packet * reach;\n }\n }\n#endif\n pos += dispAxis * disp;\n#endif\n\n // The scale / rotation / position transform lives on the mesh (modelMatrix), so the\n // orientation matches THREE's Euler-XYZ rather than an in-shader rotation order.\n vec4 world = modelMatrix * vec4(pos, 1.0);\n vWorldPos = world.xyz;\n vViewDir = cameraPosition - world.xyz;\n gl_Position = projectionMatrix * viewMatrix * world;\n vClipPosition = gl_Position;\n}\n`;\n\nexport const fragmentShader = /* glsl */ `\n#define MAX_COLORS ${MAX_COLORS}\n#define MAX_MESH_POINTS ${MAX_MESH_POINTS}\n#define MAX_LIGHTS ${MAX_LIGHTS}\n#define MAX_NOISE_BANDS ${MAX_NOISE_BANDS}\n#define PI 3.14159265359\n\n${simplex2d}\n\n${colorUniforms}\nuniform float uDebug; // dev: 1 = show crease, 2 = show derivative normal\nuniform float uSheen; // white-lift on the flat (low-crease) areas (1 = full)\nuniform float uRoundness; // pose-robust normal-based roundness/thickness strength\nuniform float uIridescence; // thin-film hue shift with view angle (0 = off)\nuniform float uFiberCount;\nuniform float uFiberStrength;\nuniform float uTexture;\nuniform float uCreaseLight;\nuniform float uCreaseSharpness;\nuniform float uCreaseSoftness;\nuniform float uEdgeFade;\nuniform vec2 uResolution;\nuniform float uAmbient;\nuniform int uNumLights;\nuniform vec3 uLightPos[MAX_LIGHTS];\nuniform vec3 uLightColor[MAX_LIGHTS];\nuniform float uLightIntensity[MAX_LIGHTS];\nuniform int uNumNoiseBands;\nuniform vec4 uNoiseBandBounds[MAX_NOISE_BANDS]; // (startX, endX, startY, endY)\nuniform vec4 uNoiseBandParams[MAX_NOISE_BANDS]; // (feather, strength, frequency, colorAttenuation)\nuniform float uNoiseBandParaPow[MAX_NOISE_BANDS];\n\nvarying vec2 vUv;\nvarying vec3 vWorldPos;\nvarying vec3 vViewDir;\n#ifdef DEPTH_TINT\nuniform float uDepthTint;\nuniform vec3 uDepthTintColor;\nvarying vec4 vClipPosition; // clip-space depth (written by the vertex shader for both programs)\n#endif\n#ifdef EDGE_FEATHER\nuniform float uEdgeFeather; // softness of the ribbon's two ENDS (only when it differs from 0.1)\n#endif\n#ifdef POINTER_FX\nuniform float uPointerThin; // 0..1 local translucency near the cursor\nuniform float uPointerHue; // degrees, local hue rotation near the cursor\nuniform float uPointerLighten; // -1..1 local brightness lift near the cursor\nvarying float vPointerFall; // falloff × presence, written by the vertex shader\n#endif\n\n// Cheap value hash for the optional grain overlay (distinct from the simplex hash).\nfloat grainHash(vec2 p){ return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\n\nfloat parabola(float x, float k){ return pow(4.0 * x * (1.0 - x), k); }\nfloat mapLinear(float v, float a, float b, float c, float d){ return c + (v - a) * (d - c) / (b - a); }\n\n${colorFns}\n\n// Striations: a subtle high-frequency simplex-noise grain ADDED to the\n// colour — colour-matched (weaker where blue is high), only near folds (crease), and\n// concentrated toward the ends (parabola). Blends in rather than reading as hard lines.\nvec3 surfaceStreaks(vec2 uv, vec3 color, float crease){\n float strength = uFiberStrength; // default 0.2\n float freq = uFiberCount; // default 600\n float colorAtten = 0.9;\n float paraPow = 3.0;\n // Noise bands: inside each rectangular uv region the\n // fiber params are overridden, so the streaks vary per region instead of uniform.\n for (int i = 0; i < MAX_NOISE_BANDS; i++) {\n if (i >= uNumNoiseBands) break;\n vec4 b = uNoiseBandBounds[i];\n vec4 prm = uNoiseBandParams[i];\n float feather = max(prm.x, 1.0e-4);\n float blend =\n smoothstep(b.x - feather, b.x, uv.x) * (1.0 - smoothstep(b.y, b.y + feather, uv.x)) *\n smoothstep(b.z - feather, b.z, uv.y) * (1.0 - smoothstep(b.w, b.w + feather, uv.y));\n strength = mix(strength, prm.y, blend);\n freq = mix(freq, prm.z, blend);\n colorAtten = mix(colorAtten, prm.w, blend);\n paraPow = mix(paraPow, uNoiseBandParaPow[i], blend);\n }\n // The high frequency runs along uv.x (the folded WIDTH — see WaveGeometry's UV AXES note),\n // packing many thin stripes across the cross-section while uv.y is barely scaled, so each\n // one stretches out into a fine LENGTHWISE fiber. 1 - parabola(uv.x) then weights them\n // toward the two long edges and away from the width centreline.\n float p = 1.0 - parabola(uv.x, paraPow);\n float n0 = simplexNoise(vec2(uv.x * 0.1, uv.y * 0.5));\n float n1 = simplexNoise(vec2(uv.x * (freq + freq * 0.5 * n0), uv.y * 4.0 * n0));\n n1 = mapLinear(n1, -1.0, 1.0, 0.0, 1.0);\n color += n1 * strength * (1.0 - color.b * colorAtten) * crease * p;\n return color;\n}\n\nvoid main(){\n // crease: a foreshortening / fold detector from the screen-space uv derivative.\n // It drives BOTH the roundness shading and where the streaks appear — this is what\n // gives the wave its thickness without any normal-based lighting.\n float crease = dFdy(vUv).y * uResolution.y * uCreaseLight;\n crease = clamp(mapLinear(crease, -1.0, 1.0, 0.0, 1.0), 0.0, 1.0);\n crease = pow(crease, uCreaseSharpness);\n crease = clamp(smoothstep(0.0, uCreaseSoftness, crease), 0.0, 1.0);\n\n // Debug visualisations (dev): 1 = crease value, 2 = derivative surface normal.\n if (uDebug > 0.5) {\n if (uDebug < 1.5) { gl_FragColor = vec4(vec3(crease), 1.0); return; }\n vec3 dn = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n gl_FragColor = vec4(dn * 0.5 + 0.5, 1.0); return;\n }\n\n // Colour: sample the baked 2D palette texture, or fall back to the procedural 1-D\n // gradient (see waveBaseColor).\n vec3 col = waveBaseColor(vUv);\n col = surfaceStreaks(vUv, col, crease);\n col = applyColorGrade(col);\n\n#ifdef POINTER_FX\n // Local hue rotation + brightness lift near the cursor (both fade out with vPointerFall).\n col = hueShift(col, radians(uPointerHue) * vPointerFall);\n col *= 1.0 + uPointerLighten * vPointerFall;\n#endif\n\n // Iridescence: a thin-film / holographic hue that shifts with view angle. Reuses the same\n // camera-facing ratio as roundness (recomputed here, since roundness may be off): grazing parts\n // of the ribbon (low facing) shift hue most, so the colour flows as the ribbon curves. Skipped\n // at 0, so the compiled result is unchanged when off.\n if (uIridescence > 0.001) {\n vec3 iridN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n float iridFacing = abs(dot(iridN, normalize(vViewDir)));\n col = hueShift(col, (1.0 - iridFacing) * uIridescence * PI);\n }\n\n // Sheen: lift the flat (low-crease) areas toward white. This is\n // pose-dependent (it keys off dFdy(uv.y)), so we keep it gentle and add a robust term.\n col += (1.0 - crease) * 0.25 * uSheen;\n\n // Pose-robust roundness: shade by the camera-facing ratio of the derivative surface\n // normal so the ribbon reads as a rounded, grabbable solid from any angle. Grazing\n // edges darken into shadow (defining the rounded form), the body keeps its full colour,\n // and the most face-on sliver catches a soft highlight. uRoundness = strength.\n if (uRoundness > 0.001) {\n vec3 volN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n float facing = abs(dot(volN, normalize(vViewDir))); // 1 = facing camera, 0 = edge-on\n col *= mix(1.0 - 0.6 * uRoundness, 1.0, facing); // deepen grazing edges → solid form\n col += smoothstep(0.65, 1.0, facing) * uRoundness * 0.18; // soft highlight on the facing body\n }\n\n // Optional positionable lights (our feature) — additive & gentle, on top of the\n // base shading so the default look is preserved. A finely-subdivided mesh\n // keeps this derivative normal smooth.\n if (uNumLights > 0) {\n vec3 N = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n vec3 Vd = normalize(vViewDir);\n if (dot(N, Vd) < 0.0) N = -N;\n for (int i = 0; i < MAX_LIGHTS; i++) {\n if (i >= uNumLights) break;\n vec3 L = normalize(uLightPos[i] - vWorldPos);\n vec3 lc = uLightColor[i] * uLightIntensity[i];\n float diff = max(dot(N, L), 0.0);\n float spec = pow(max(dot(N, normalize(L + Vd)), 0.0), 28.0);\n col += col * diff * lc * 0.16 + spec * lc * 0.10;\n }\n }\n col *= 0.55 + clamp(uAmbient, 0.0, 1.0); // overall level; default 0.45 => x1.0 (neutral)\n\n#ifdef DEPTH_TINT\n // Depth tint: fade far fragments toward a colour so a multi-wave stack gains atmospheric\n // separation — near strands keep their colour, far ones recede. Reuses the clip-space depth the\n // wireframe theme fades with (clamp(z*6), where 1 = far).\n col = mix(col, uDepthTintColor, clamp(vClipPosition.z * 6.0, 0.0, 1.0) * uDepthTint);\n#endif\n\n if (uTexture > 0.001) col *= 1.0 + (grainHash(vUv * 850.0) - 0.5) * uTexture * 0.25;\n\n // Soft ribbon ENDS (it fades on vUv.y, the length) + optional viewport-edge fade. The edge\n // softness is the hardcoded 0.1 by\n // default (literal branch → byte-identical); EDGE_FEATHER swaps in the uEdgeFeather knob only\n // when it differs, so razor-crisp or vapor-soft edges are both reachable.\n#ifdef EDGE_FEATHER\n float ribEdge =\n smoothstep(0.0, uEdgeFeather, vUv.y) * (1.0 - smoothstep(1.0 - uEdgeFeather, 1.0, vUv.y));\n#else\n float ribEdge = smoothstep(0.0, 0.1, vUv.y) * (1.0 - smoothstep(0.9, 1.0, vUv.y));\n#endif\n float alpha = uOpacity * ribEdge;\n#ifdef POINTER_FX\n alpha *= clamp(1.0 - uPointerThin * vPointerFall, 0.0, 1.0); // solid: local translucency\n#endif\n if (uEdgeFade > 0.001) {\n vec2 sc = gl_FragCoord.xy / max(uResolution, vec2(1.0));\n float vig =\n smoothstep(0.0, uEdgeFade, sc.x) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.x)) *\n smoothstep(0.0, uEdgeFade, sc.y) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.y));\n alpha *= vig;\n }\n\n // Deep \"squared\" hero colour: formerly done by a framebuffer-squaring blend that REPLACED the\n // destination (punching holes at soft edges / where waves overlap). Squaring here + normal\n // premultiplied compositing (see applyBlendMode) keeps the deep colour and blends correctly.\n col = clamp(col, 0.0, 1.0);\n // Square colour AND alpha so the soft ribbon edges keep the crisp, thin feather of the original\n // squared-blend look — but now composited (premultiplied) rather than replace-blended, so they\n // no longer punch holes. Over an opaque background alpha² still resolves to fully opaque.\n if (uSquared > 0.5) { col *= col; alpha *= alpha; }\n gl_FragColor = vec4(col, alpha);\n#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n}\n`;\n\n// ---- Wireframe \"thin-line\" theme ----\n// The same wave geometry, but instead of a solid surface the colour is carved into fine\n// LENGTHWISE strands (abs(sin(uv.x * lineAmount)) — uv.x is the folded width, so lineAmount\n// counts strands ACROSS the cross-section and each runs end to end) whose thickness scales\n// with the screen-space uv derivative, then mixed line<->background with a depth fade. Used by the dark\n// hero preset. hueShift takes degrees (radians() here) to match the light shader.\nexport const lineFragmentShader = /* glsl */ `\n#define MAX_COLORS ${MAX_COLORS}\n#define MAX_MESH_POINTS ${MAX_MESH_POINTS}\n#define PI 3.14159265359\n\n${simplex2d}\n\n${colorUniforms}\nuniform float uLineAmount; // default 425\nuniform float uLineThickness; // default 1\nuniform float uLineDerivativePower; // default 0.95\nuniform float uMaxWidth; // default 1232\n// Cross-wise rungs (optional) — behind RUNGS so a wave without them compiles the same program.\n#ifdef RUNGS\nuniform float uRungAmount; // frequency across the ribbon (rungs ≈ amount / π)\nuniform float uRungThickness; // rung width in pixels\n#endif\nuniform vec3 uClearColor; // = page background colour (shown between the lines)\n\nvarying vec2 vUv;\nvarying vec4 vClipPosition;\n#ifdef POINTER_FX\nuniform float uPointerThin; // 0..1 — strands taper to hairlines near the cursor\nuniform float uPointerHue; // degrees, local hue rotation near the cursor\nuniform float uPointerLighten; // -1..1 local brightness lift near the cursor\nvarying float vPointerFall; // falloff × presence, written by the vertex shader\n#endif\n\n${colorFns}\n\nvoid main(){\n // Same 2D palette sample + colour ops as the solid theme.\n vec3 color = applyColorGrade(waveBaseColor(vUv));\n\n#ifdef POINTER_FX\n color = hueShift(color, radians(uPointerHue) * vPointerFall);\n color *= 1.0 + uPointerLighten * vPointerFall;\n#endif\n\n // Carve into fine lengthwise strands; thickness from the screen-space uv derivative.\n vec2 dy = dFdy(vUv);\n float lineThickness = uLineThickness * pow(abs(dy.x * uMaxWidth), uLineDerivativePower);\n#ifdef POINTER_FX\n lineThickness *= clamp(1.0 - uPointerThin * vPointerFall, 0.0, 1.0); // wireframe: taper strands\n#endif\n float a = abs(sin(vUv.x * uLineAmount));\n a = smoothstep(lineThickness, 0.0, a);\n\n#ifdef RUNGS\n // Rungs: the same carve at constant uv.y instead of uv.x, so this family runs ACROSS the ribbon\n // where the one above runs along it — together they read as a ladder. Width comes from fwidth()\n // rather than the lengthwise term's dFdy(vUv).x, which is the derivative of the wrong axis for\n // this direction: |sin| climbs by ~uRungAmount·fwidth(vUv.y) per pixel, so scaling by that keeps\n // a rung uRungThickness pixels wide at any zoom or ribbon scale.\n float rung = abs(sin(vUv.y * uRungAmount));\n a = max(a, smoothstep(uRungThickness * uRungAmount * fwidth(vUv.y), 0.0, rung));\n#endif\n\n // Depth fade: the wave recedes into the background colour with depth. Watch the\n // argument order: clamp(0.0, 1.0, z*6) is a swapped-args trap — it clamps the\n // constant 0.0 into [1.0, z*6], i.e. min(1.0, z*6), which (with our ortho clip.z\n // range) collapses the whole wave to the background. The correct clamp(z*6, 0, 1)\n // gives the proper subtle far-end fade and thin-line look.\n float depthFade = clamp(vClipPosition.z * 6.0, 0.0, 1.0);\n color = mix(uClearColor, color, a * (1.0 - depthFade));\n if (uSquared > 0.5) color *= color; // deep \"squared\" look, now composited not replace-blended\n gl_FragColor = vec4(color, uOpacity);\n#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n}\n`;\n\n// ---- Post pass: viewport-edge soft-focus blur + dither grain ----\n\nexport const postVertexShader = /* glsl */ `\nvarying vec2 vUv;\nvoid main(){\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n`;\n\nexport const postFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform vec2 uResolution;\nuniform float uBlurAmount;\nuniform int uBlurSamples;\nuniform float uGrainAmount;\nuniform float uTime;\nvarying vec2 vUv;\n\nfloat random2(vec2 st){ return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453); }\n\n// Angular (spin) blur: rotate the sample coord around the centre and\n// accumulate — a tangential smear that grows toward the edges. Carries alpha so a\n// transparent background survives the post pass.\nvec4 blurAngular(sampler2D tex, vec2 uv, float angle, int samples){\n vec4 total = vec4(0.0);\n vec2 coord = uv - 0.5;\n float dist = 1.0 / float(samples);\n vec2 dir = vec2(cos(angle * dist), sin(angle * dist));\n mat2 rot = mat2(dir.x, dir.y, -dir.y, dir.x);\n for (int i = 0; i < 64; i++){\n if (i >= samples) break;\n total += texture2D(tex, coord + 0.5);\n coord = coord * rot; // row-vector order (coord * rot) sets the spin direction\n }\n return total * dist;\n}\n\nvoid main(){\n vec4 sceneColor = texture2D(tDiffuse, vUv);\n vec4 blurColor = blurAngular(tDiffuse, vUv, uBlurAmount, uBlurSamples);\n // blurPower: keep a sharp band weighted to the middle, blurring toward top & bottom.\n float blurPower = smoothstep(0.0, 0.7, vUv.y) - smoothstep(0.2, 1.0, vUv.y);\n vec4 color = mix(blurColor, sceneColor, blurPower);\n // Static film grain: keyed off gl_FragCoord only (no uTime), so it doesn't flicker.\n color.rgb += mix(uGrainAmount, -uGrainAmount, random2(gl_FragCoord.xy * 0.01)) * (4.0 / 255.0);\n gl_FragColor = color; // preserve alpha → transparent background works\n}\n`;\n\n// ---- Post pass: ordered (Bayer) dithering ----\n//\n// DERIVED FROM @paper-design/shaders `image-dithering` (https://github.com/paper-design/shaders,\n// Apache-2.0 — see THIRD-PARTY-NOTICES.md). The Bayer matrices, getBayerValue, and the brightness /\n// luminance-quantization / hue-preserving \"original colours\" recolour are paper's. Adapted to a\n// post pass: samples the composited scene (tDiffuse) at full-frame vUv instead of paper's sized/fit\n// u_image UV, drops the frame/aspect machinery, fixes the 8x8 matrix (paper's default), and gates\n// via uDitherStrength. The int[] arrays + dynamic indexing compile because three builds\n// ShaderMaterials as \"#version 300 es\". Runs AFTER OutputPass, so it dithers display-space colour;\n// keyed off gl_FragCoord/tDiffuse only (no uTime) → deterministic, friendly to pixel-digest checks.\nexport const ditherFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform vec2 uResolution;\nuniform float uDitherStrength; // 0..1 mix back toward the original\nuniform float uDitherScale; // pixel-block size in device px (paper: u_pxSize)\nuniform float uDitherSteps; // quantization levels (paper: u_colorSteps)\nvarying vec2 vUv;\n\nconst int bayer2x2[4] = int[4](0, 2, 3, 1);\nconst int bayer4x4[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5);\nconst int bayer8x8[64] = int[64](\n 0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26,\n 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30, 54, 22,\n 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25,\n 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21\n);\nfloat getBayerValue(vec2 uv, int size){\n ivec2 pos = ivec2(fract(uv / float(size)) * float(size));\n int index = pos.y * size + pos.x;\n if (size == 2) return float(bayer2x2[index]) / 4.0;\n else if (size == 4) return float(bayer4x4[index]) / 16.0;\n else if (size == 8) return float(bayer8x8[index]) / 64.0;\n return 0.0;\n}\n\nvoid main(){\n float pxSize = max(uDitherScale, 1.0);\n vec2 pxSizeUV = gl_FragCoord.xy / pxSize;\n vec2 sampleUV = (floor(gl_FragCoord.xy / pxSize) + 0.5) * pxSize / max(uResolution, vec2(1.0));\n vec4 image = texture2D(tDiffuse, sampleUV);\n\n float lum = dot(vec3(0.2126, 0.7152, 0.0722), image.rgb);\n float colorSteps = max(floor(uDitherSteps), 1.0);\n\n float dithering = getBayerValue(pxSizeUV, 8) - 0.5; // paper's default 8x8 ordered screen\n float brightness = clamp(lum + dithering / colorSteps, 0.0, 1.0);\n brightness = mix(0.0, brightness, image.a);\n float quantLum = floor(brightness * colorSteps + 0.5) / colorSteps;\n\n // paper's \"original colours\" path: keep the source hue, quantize luminance.\n vec3 color = image.rgb / max(lum, 0.001) * quantLum;\n float quantAlpha = floor(image.a * colorSteps + 0.5) / colorSteps;\n float opacity = mix(quantLum, 1.0, quantAlpha);\n\n gl_FragColor = mix(image, vec4(color, opacity), clamp(uDitherStrength, 0.0, 1.0));\n}\n`;\n\n// ---- Post pass: innerLight (volumetric light streaks) — another \"layered\" post shader ----\n//\n// Radial light-scattering (à la GPU Gems 3): from each pixel, march toward a light point and\n// accumulate the wave's own brightness (weighted by alpha, so only opaque pixels emit), then add\n// the streaks back. Runs in the scene zone so it scatters the raw, pre-tone-map wave like bloom.\nexport const innerLightFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uInnerLight; // 0..1 strength of the added light\nuniform float uInnerLightDensity; // ray length / spread\nuniform float uInnerLightDecay; // per-sample falloff (<1)\nuniform vec2 uInnerLightCenter; // light source, UV (0..1)\nvarying vec2 vUv;\n\nconst int LIGHT_SAMPLES = 24;\n\nfloat luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }\n\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n vec2 delta = (vUv - uInnerLightCenter) * (uInnerLightDensity / float(LIGHT_SAMPLES));\n vec2 coord = vUv;\n float decay = 1.0;\n vec3 rays = vec3(0.0);\n for (int i = 0; i < LIGHT_SAMPLES; i++){\n coord -= delta;\n vec4 s = texture2D(tDiffuse, coord);\n rays += s.rgb * s.a * decay; // only opaque (wave) pixels emit light\n decay *= uInnerLightDecay;\n }\n rays /= float(LIGHT_SAMPLES);\n vec3 outc = src.rgb + rays * uInnerLight;\n float outA = max(src.a, luma(rays) * uInnerLight); // shafts stay visible over the transparent bg\n gl_FragColor = vec4(outc, clamp(outA, 0.0, 1.0));\n}\n`;\n\n// ---- Post pass: halftone (rotated dot screen) ----\n//\n// DERIVED FROM @paper-design/shaders `halftone-dots` (https://github.com/paper-design/shaders,\n// Apache-2.0 — see THIRD-PARTY-NOTICES.md). Ports the \"classic\" dot type + \"original colours\" path:\n// paper's getCircle (dot radius ← 1 − luminance, fwidth-antialiased) and sigmoid-contrast luminance,\n// sampled once per cell centre. Adapted to a post pass — samples the composited scene (tDiffuse)\n// instead of paper's sized u_image, drops the gooey/holes/soft dot types, the diagonal grid and the\n// grain layers, and composites transparent between dots. Contrast/radius fixed at paper's defaults.\nexport const halftoneFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform vec2 uResolution;\nuniform float uHalftone; // 0..1 mix\nuniform float uHalftoneCell; // dot cell size in device px (paper: u_size)\nuniform float uHalftoneAngle; // screen rotation (radians, paper: u_rotation)\nvarying vec2 vUv;\n\nfloat sigmoid(float x, float k){ return 1.0 / (1.0 + exp(-k * (x - 0.5))); }\n// paper's classic dot: radius grows as the sampled cell darkens (1 - lum), soft edge via fwidth.\nfloat getCircle(vec2 uv, float lum, float baseR){\n float r = mix(0.25 * baseR, 0.0, lum);\n float d = length(uv - 0.5);\n float aa = fwidth(d);\n return 1.0 - smoothstep(r - aa, r + aa, d);\n}\n\nvoid main(){\n float ca = cos(uHalftoneAngle);\n float sa = sin(uHalftoneAngle);\n mat2 rot = mat2(ca, sa, -sa, ca);\n float cell = max(uHalftoneCell, 2.0);\n vec2 gridPx = rot * gl_FragCoord.xy; // rotate the screen into the dot grid\n vec2 cellId = floor(gridPx / cell);\n vec2 inCell = fract(gridPx / cell); // position within the cell (0..1)\n vec2 centrePx = transpose(rot) * ((cellId + 0.5) * cell); // cell centre, back in screen px\n vec4 tex = texture2D(tDiffuse, centrePx / max(uResolution, vec2(1.0)));\n\n float k = 2.0; // sigmoid contrast (paper default)\n vec3 c = vec3(sigmoid(tex.r, k), sigmoid(tex.g, k), sigmoid(tex.b, k));\n float lum = dot(vec3(0.2126, 0.7152, 0.0722), c);\n lum = mix(1.0, lum, tex.a);\n float dot = getCircle(inCell, lum, 1.3); // baseR 1.3 ≈ paper original-colours default\n vec4 dots = vec4(tex.rgb, tex.a * dot); // wave-coloured dots, transparent between\n gl_FragColor = mix(texture2D(tDiffuse, vUv), dots, clamp(uHalftone, 0.0, 1.0));\n}\n`;\n\n// ---- Post pass: heatmap (map luminance → thermal palette) — a finish-zone filter ----\nexport const heatmapFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uHeatmap; // 0..1 mix\nvarying vec2 vUv;\nvec3 heat(float t){\n t = clamp(t, 0.0, 1.0);\n vec3 c = mix(vec3(0.0, 0.0, 0.4), vec3(0.0, 0.6, 1.0), smoothstep(0.0, 0.25, t));\n c = mix(c, vec3(0.0, 1.0, 0.4), smoothstep(0.25, 0.5, t));\n c = mix(c, vec3(1.0, 1.0, 0.0), smoothstep(0.5, 0.75, t));\n c = mix(c, vec3(1.0, 0.1, 0.0), smoothstep(0.75, 1.0, t));\n return c;\n}\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n float l = dot(src.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(mix(src.rgb, heat(l), clamp(uHeatmap, 0.0, 1.0)), src.a);\n}\n`;\n\n// ---- Post pass: paper texture (fibrous substrate shading) — a finish-zone overlay ----\nexport const paperTextureFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uPaper; // 0..1 strength\nuniform float uPaperScale; // grain scale\nvarying vec2 vUv;\nfloat h21(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n vec2 p = gl_FragCoord.xy / max(uPaperScale, 0.5);\n float fiber = h21(floor(p)) * 0.5 + h21(floor(p * vec2(0.3, 3.0))) * 0.5; // directional fibers\n float tex = mix(fiber, h21(gl_FragCoord.xy), 0.3); // + fine speckle\n float shade = 1.0 - (tex - 0.5) * 0.35;\n gl_FragColor = vec4(src.rgb * mix(1.0, shade, clamp(uPaper, 0.0, 1.0)), src.a);\n}\n`;\n\n// ---- Post pass: CMYK halftone (four rotated dot screens) — a finish-zone filter ----\nexport const halftoneCmykFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uHalftoneCmyk; // 0..1 mix\nuniform float uHalftoneCmykCell; // dot cell size in device px\nvarying vec2 vUv;\n// One rotated halftone dot screen for a channel value.\nfloat dotScreen(vec2 coord, float value, float angle, float cell){\n float ca = cos(angle);\n float sa = sin(angle);\n vec2 r = mat2(ca, sa, -sa, ca) * coord;\n vec2 c = fract(r / max(cell, 2.0)) - 0.5;\n float radius = sqrt(clamp(value, 0.0, 1.0)) * 0.5;\n return smoothstep(radius, radius - 0.06, length(c));\n}\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n float k = 1.0 - max(max(src.r, src.g), src.b); // RGB → CMYK\n float invK = max(1.0 - k, 1e-3);\n float cyan = (1.0 - src.r - k) / invK;\n float mag = (1.0 - src.g - k) / invK;\n float yel = (1.0 - src.b - k) / invK;\n vec2 coord = gl_FragCoord.xy;\n float cell = uHalftoneCmykCell;\n float dc = dotScreen(coord, cyan, 1.309, cell); // 75°\n float dm = dotScreen(coord, mag, 0.262, cell); // 15°\n float dy = dotScreen(coord, yel, 0.0, cell); // 0°\n float dk = dotScreen(coord, k, 0.785, cell); // 45°\n // Subtractive: cyan ink absorbs red, magenta absorbs green, yellow absorbs blue, black absorbs all.\n vec3 outc = vec3(1.0) - vec3(dc, 0.0, 0.0) - vec3(0.0, dm, 0.0) - vec3(0.0, 0.0, dy) - vec3(dk);\n outc = clamp(outc, 0.0, 1.0);\n gl_FragColor = vec4(mix(src.rgb, outc, clamp(uHalftoneCmyk, 0.0, 1.0)), src.a);\n}\n`;\n\n// ---------------------------------------------------------------------------------------------\n// Particle field (additive dust / sparkle) — ONE per wave. A THREE.Points ShaderMaterial: every\n// particle's position + life is a pure function of uTime + baked per-particle attributes (aSeed / aRnd\n// / aUv), so the whole field is deterministic (timeOffset scrub / loopSeconds / paused all hold).\n// Every particle spawns on the OWNING wave's DEFORMED surface / edge (via the shared waveShape chunk,\n// riding the exact deform the ribbon uses) and drifts outward from the wave centre as it ages. The\n// wave's shape #defines (HELIX/RADIAL/…) are mirrored onto this material in configure().\n// ---------------------------------------------------------------------------------------------\nexport const particleVertexShader = /* glsl */ `\nattribute float aSeed;\nattribute vec4 aRnd;\nattribute vec2 aUv; // where this particle spawns on the ribbon (x = flank, y = along length; edge-biased at build)\n\nuniform float uTime, uLoopSeconds, uLife, uSize, uSizeJitter, uTwinkle, uPixelRatio;\nuniform float uPartSpeed;\nuniform vec3 uColor, uColor2, uCenter, uRight, uUp;\nuniform float uDrift, uRise, uSwirl, uWander;\n\n// The owning wave's shape, mirrored in configure() so the dust rides the SAME deform as the ribbon.\n// The HELIX/RADIAL uniform blocks are declared only when the matching #define is set.\n${simplex2d}\nuniform float uDispFreqX, uDispFreqZ, uDispAmount;\nuniform float uDetailFreq, uDetailAmount;\nuniform float uTwFreqX, uTwFreqY, uTwFreqZ, uTwPowX, uTwPowY, uTwPowZ;\n#ifdef HELIX\nuniform float uHelixTurns, uHelixRadius, uHelixRoll, uHelixPhase;\n#endif\n#ifdef RADIAL\nuniform float uRadialAmount, uRadialArc, uRadialSpread, uRadialRadius, uRadialCenter;\n#endif\nuniform mat4 uShedModel; // the wave's matrixWorld (deformed LOCAL → world)\nuniform float uShedSpeed, uShedSeed;\n${waveShapeChunk}\n\nvarying float vAlpha;\nvarying vec3 vColor;\nvarying vec2 vDir; // screen-space motion direction (for the streak sprite)\n\nconst float TAU = 6.28318530718;\n\nvoid main(){\n // Deterministic life: age 0..1 from uTime + a per-particle seed. Advances once per loop period when\n // looping (so the whole field repeats seamlessly), else once per uLife seconds. uPartSpeed scales the\n // cadence (motion speed); under a loop it snaps to a whole number of cycles so the seam stays seamless.\n float cyc = max(1.0, floor(uPartSpeed + 0.5));\n float rate = (uLoopSeconds > 0.0) ? (uTime / uLoopSeconds * cyc) : (uTime * uPartSpeed / max(uLife, 0.001));\n float age = fract(rate + aSeed);\n float fade = sin(3.14159265 * age); // 0 at birth/death, 1 mid-life\n\n // Spawn on the owning wave's DEFORMED surface / edge at aUv (via the shared waveShape), then peel\n // outward from the wave centre as the particle ages — silk dissolving into glitter.\n float ts = uTime * uShedSpeed + uShedSeed;\n vec2 loopOff = vec2(0.0);\n#ifdef LOOP_MOTION\n float loopTheta = uTime * (TAU / uLoopSeconds) + uShedSeed;\n float loopR = uShedSpeed * uLoopSeconds * 0.159154943092;\n loopOff = loopR * vec2(cos(loopTheta), sin(loopTheta));\n ts = 0.0;\n#endif\n // Approximate the base hairpin point for this uv (length from uv.y; width centre), then deform it\n // exactly as the wave does. Good enough for dust — the fan / displacement dominate.\n vec3 base = vec3((aUv.y - 0.5) * 400.0, 0.0, ${RIBBON_Z_CENTER.toFixed(1)});\n vec3 origin = (uShedModel * vec4(waveShape(base, aUv, ts, loopOff).pos, 1.0)).xyz;\n vec3 outward = normalize(origin - uCenter + vec3(1e-4));\n vec3 p = origin + outward * age * uDrift + (aRnd.xyz - 0.5) * age * uDrift * 0.35;\n\n // Motion styles, each 0 = off, all riding age so they stay loop-safe (the age wrap is hidden by\n // fade→0 at birth/death). rise = screen-vertical buoyancy (embers up / snow down); swirl = orbit\n // around the wave centre in the screen plane; wander = curl-noise turbulence (fireflies / motes).\n p += uUp * age * uRise;\n if (uSwirl != 0.0) {\n vec3 nrm = cross(uRight, uUp);\n vec3 rel = p - uCenter;\n float rx = dot(rel, uRight), ry = dot(rel, uUp), rz = dot(rel, nrm);\n float a = age * uSwirl * TAU;\n float ca = cos(a), sa = sin(a);\n p = uCenter + uRight * (rx * ca - ry * sa) + uUp * (rx * sa + ry * ca) + nrm * rz;\n }\n if (uWander != 0.0) {\n vec2 wan = vec2(simplexNoise(vec2(aSeed * 17.0, age * 3.0)),\n simplexNoise(vec2(age * 3.0, aSeed * 23.0)));\n p += (uRight * wan.x + uUp * wan.y) * uWander;\n }\n\n float tw = 0.5 + 0.5 * sin((age * 9.0 + aSeed) * TAU); // loop-safe flicker (rides age)\n vAlpha = fade * mix(1.0, tw, clamp(uTwinkle, 0.0, 1.0));\n vColor = mix(uColor, uColor2, aRnd.w); // two-tone dust: per-particle blend of the two colours\n vDir = normalize(vec2(dot(outward, uRight), dot(outward, uUp)) + vec2(1e-4)); // outward, in screen space\n gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);\n // Orthographic camera → point size is constant in device pixels (no perspective depth divide).\n float jitter = 1.0 + uSizeJitter * (aSeed - 0.5) * 2.0;\n gl_PointSize = max(uSize * uPixelRatio * jitter * fade, 0.0);\n}\n`;\n\nexport const particleFragmentShader = /* glsl */ `\nprecision highp float;\nuniform float uShape; // 0 glitter · 1 soft · 2 ring · 3 star · 4 streak\nvarying float vAlpha;\nvarying vec3 vColor;\nvarying vec2 vDir;\nvoid main(){\n vec2 pc = gl_PointCoord - 0.5;\n float d = length(pc);\n int s = int(uShape + 0.5);\n float a;\n if (s == 1) { // soft: a diffuse gaussian blob (motes / pollen)\n a = exp(-d * d * 7.0);\n } else if (s == 2) { // ring: a hollow band (bubbles)\n a = smoothstep(0.09, 0.0, abs(d - 0.34));\n } else if (s == 3) { // star: a 4-point sparkle\n float ang = atan(pc.y, pc.x);\n float spike = pow(abs(cos(ang * 2.0)), 6.0);\n a = smoothstep(1.0, 0.0, d / (0.14 + 0.5 * spike));\n } else if (s == 4) { // streak: an elongated comet along the motion direction\n float along = dot(pc, vDir);\n float perp = dot(pc, vec2(-vDir.y, vDir.x));\n a = smoothstep(0.5, 0.0, length(vec2(along * 0.42, perp * 2.2)));\n } else { // glitter (0): the soft round additive disc\n a = smoothstep(0.5, 0.0, d);\n }\n a *= vAlpha;\n if (a <= 0.0) discard;\n gl_FragColor = vec4(vColor, a); // AdditiveBlending (src = SrcAlpha) → adds vColor·a\n}\n`;\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,YAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC7B,MAAM,gBAA2B;;;;;;;;;;;;;;;;;;;;;;;;AA2BjC,MAAM,WAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2F5B,MAAM,iBAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCAiDiB,IAAA,CAAA,QAAQ,CAAC,EAAE;;YAElC,IAAA,CAAA,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCAoCY,IAAA,CAAA,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;AAe9D,MAAa,eAA0B;EACrC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4DV,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHjB,MAAa,iBAA4B;;;;;;;EAOvC,UAAU;;EAEV,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+Cd,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgKX,MAAa,qBAAgC;;;;;EAK3C,UAAU;;EAEV,cAAc;;;;;;;;;;;;;;;;;;;;;EAqBd,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CX,MAAa,mBAA8B;;;;;;;AAQ3C,MAAa,qBAAgC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD7C,MAAa,uBAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqD/C,MAAa,2BAAsC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCnD,MAAa,yBAAoC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCjD,MAAa,wBAAmC;;;;;;;;;;;;;;;;;;AAoBhD,MAAa,6BAAwC;;;;;;;;;;;;;;;AAiBrD,MAAa,6BAAwC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CrD,MAAa,uBAAkC;;;;;;;;;;;;EAY7C,UAAU;;;;;;;;;;;;EAYV,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iDA6BgD,IAAA,CAAA,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkC5E,MAAa,yBAAoC"}
1
+ {"version":3,"file":"shaders.js","names":[],"sources":["../../src/renderer/shaders.ts"],"sourcesContent":["import { MAX_COLORS, MAX_LIGHTS, MAX_MESH_POINTS, MAX_NOISE_BANDS } from \"../config/model\";\nimport { RIBBON_Z_CENTER } from \"./WaveGeometry\";\n\n/**\n * The wave shaders. Vertex: a flat plane is Y-displaced by simplex noise, then\n * twisted by three axis-rotations `freq * expStep(uv, power)` where\n * `expStep(x,n) = exp2(-exp2(n)*pow(x,n))` is a falloff (rotation concentrated at\n * the uv=0 edge), with diagonal axes + an animated X wobble. Fragment: uses NO\n * normal-based lighting — \"thickness\" comes from `crease`, a foreshorten/fold\n * detector built from `dFdy(uv)`, used to lift flat areas toward white\n * (`col += (1-crease)*0.25`) and to localise the striations. Striations are subtle\n * high-frequency simplex noise ADDED to the colour, colour-matched via (1-blue)\n * and end-weighted via a parabola — so they blend rather than form hard lines.\n * Our additions: gradient stops/types for colour, and an optional additive light\n * layer (kept gentle so the default look is preserved).\n */\n\n// Noise function: xxHash-seeded unit-vector gradients + a Gustavson simplex. It uses\n// GLSL ES 3.00 integer ops (floatBitsToUint, unsigned bit-shifts) — available with no\n// glslVersion change because three compiles non-raw ShaderMaterials as \"#version 300 es\"\n// already. `hash` returns a vec2 here — the cheap grain hash in the fragment is named\n// `grainHash` to avoid clashing with it.\nconst simplex2d = /* glsl */ `\nfloat xxhash(vec2 x){\n uvec2 t = floatBitsToUint(x);\n uint h = 0xc2b2ae3du * t.x + 0x165667b9u;\n h = (h << 17u | h >> 15u) * 0x27d4eb2fu;\n h += 0xc2b2ae3du * t.y;\n h = (h << 17u | h >> 15u) * 0x27d4eb2fu;\n h ^= h >> 15u;\n h *= 0x85ebca77u;\n h ^= h >> 13u;\n h *= 0xc2b2ae3du;\n h ^= h >> 16u;\n return uintBitsToFloat(h >> 9u | 0x3f800000u) - 1.0;\n}\nvec2 hash(vec2 x){\n float k = 6.283185307 * xxhash(x);\n return vec2(cos(k), sin(k));\n}\nfloat simplexNoise(in vec2 p){\n const float K1 = 0.366025404; // (sqrt(3)-1)/2\n const float K2 = 0.211324865; // (3-sqrt(3))/6\n vec2 i = floor(p + (p.x + p.y) * K1);\n vec2 a = p - i + (i.x + i.y) * K2;\n float m = step(a.y, a.x);\n vec2 o = vec2(m, 1.0 - m);\n vec2 b = a - o + K2;\n vec2 c = a - 1.0 + 2.0 * K2;\n vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);\n vec3 n = h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0)));\n return dot(n, vec3(32.99)); // analytic factor (= 2916*sqrt(2)/125)\n}\n`;\n\n// Uniforms shared by BOTH fragment shaders (solid + wireframe line): the palette/gradient\n// inputs and the colour-grade knobs. Each shader declares its theme-specific uniforms beside\n// this block. Requires MAX_COLORS / MAX_MESH_POINTS #defines.\nconst colorUniforms = /* glsl */ `\nuniform vec3 uColors[MAX_COLORS];\nuniform float uColorPos[MAX_COLORS];\nuniform int uColorCount;\nuniform int uGradType;\nuniform float uGradAngle;\nuniform float uGradShift;\nuniform vec2 uMeshPointPos[MAX_MESH_POINTS];\nuniform vec3 uMeshPointColor[MAX_MESH_POINTS];\nuniform float uMeshPointInfluence[MAX_MESH_POINTS];\nuniform int uMeshPointCount;\nuniform float uMeshSoftness;\nuniform sampler2D uPalette; // baked 2D palette texture\nuniform float uUsePalette; // >0.5 = sample the texture; else procedural grad()\nuniform float uPaletteRaw; // >0.5 = sample palette by raw (uv.x,uv.y), not gradCoord\nuniform vec2 uPaletteScale;\nuniform vec2 uPaletteOffset;\nuniform float uPaletteRotation;\nuniform float uHueShift;\nuniform float uContrast;\nuniform float uSaturation;\nuniform float uOpacity;\nuniform float uSquared; // 1 = square the output colour (the deep \"squared\" hero look)\n`;\n\n// Colour helpers + the palette/gradient sampler shared by both fragment shaders.\n// Interpolate AFTER ${\"simplex2d\"} and ${\"colorUniforms\"} (gradCoord needs both) and a PI define.\nconst colorFns = /* glsl */ `\nvec3 contrastFn(vec3 v, float a){ return (v - 0.5) * a + 0.5; }\nvec3 desaturate(vec3 color, float factor){\n vec3 gray = vec3(dot(vec3(0.299, 0.587, 0.114), color));\n return mix(color, gray, factor);\n}\nvec3 hueShift(vec3 color, float shift){\n vec3 g = vec3(0.57735);\n vec3 proj = g * dot(g, color);\n vec3 U = color - proj;\n vec3 W = cross(g, U);\n return U * cos(shift) + W * sin(shift) + proj;\n}\n\n// Our gradient: interpolate stops by their positions (uColorPos sorted ascending).\nvec3 grad(float u){\n u = clamp(u, 0.0, 1.0);\n vec3 col = uColors[0];\n for (int i = 0; i < MAX_COLORS - 1; i++){\n if (i >= uColorCount - 1) break;\n float p0 = uColorPos[i];\n float p1 = uColorPos[i + 1];\n if (u >= p0){\n float t = clamp((u - p0) / max(p1 - p0, 1e-5), 0.0, 1.0);\n col = mix(uColors[i], uColors[i + 1], t);\n }\n }\n return col;\n}\n\n// iOS-style 2D colour field. Each control point contributes an inverse-distance\n// weight; normalising the sum fills the whole surface without dark seams.\nvec3 meshGradient(vec2 uv){\n vec3 colorSum = vec3(0.0);\n float weightSum = 0.0;\n float exponent = mix(4.8, 1.35, clamp(uMeshSoftness, 0.0, 1.0));\n for (int i = 0; i < MAX_MESH_POINTS; i++){\n if (i >= uMeshPointCount) break;\n float influence = max(uMeshPointInfluence[i], 0.05);\n float distanceFromPoint = length(uv - uMeshPointPos[i]) / influence;\n float weight = 1.0 / (pow(max(distanceFromPoint, 0.012), exponent) + 0.002);\n colorSum += uMeshPointColor[i] * weight;\n weightSum += weight;\n }\n return colorSum / max(weightSum, 0.0001);\n}\n\n// Map a surface uv to the 0–1 gradient coordinate per gradient type. uGradShift\n// adds a low-frequency simplex warp so the colour varies in 2D (along the length\n// as well as across the width) — a 2D palette feel instead\n// of flat 1-D bands.\nfloat gradCoord(vec2 uv){\n float warp = uGradShift * simplexNoise(uv * 1.6 + 4.0);\n if (uGradType == 1){ return clamp(length(uv - 0.5) * 2.0 + warp, 0.0, 1.0); } // radial\n if (uGradType == 2){ return fract(atan(uv.y - 0.5, uv.x - 0.5) / (2.0 * PI) + 0.5 + warp); } // conic\n vec2 dir = vec2(sin(uGradAngle), cos(uGradAngle)); // linear, angled\n return clamp(dot(uv - 0.5, dir) + 0.5 + warp, 0.0, 1.0);\n}\n\n// One base-colour sample for the whole surface: rotate/scale/offset the raw-palette uv,\n// then pick the mesh field / baked 2D texture / procedural stops by mode. The raw palette\n// is sampled by (uv.x, uv.y) directly; the stops-generated texture is sampled via\n// gradCoord so its angle/type/warp still apply.\nvec3 waveBaseColor(vec2 uv){\n float gc = gradCoord(uv);\n vec2 mediaUv = uv - 0.5;\n float mediaCos = cos(uPaletteRotation);\n float mediaSin = sin(uPaletteRotation);\n mediaUv = vec2(\n mediaCos * mediaUv.x + mediaSin * mediaUv.y,\n -mediaSin * mediaUv.x + mediaCos * mediaUv.y\n );\n mediaUv = mediaUv * uPaletteScale + 0.5 + uPaletteOffset;\n vec2 puv = uPaletteRaw > 0.5\n ? clamp(mediaUv, 0.0, 1.0)\n : vec2(gc, clamp(uv.y, 0.0, 1.0));\n return uGradType == 3\n ? meshGradient(uv)\n : (uUsePalette > 0.5 ? texture2D(uPalette, puv).rgb : grad(gc));\n}\n\n// The shared colour grade: contrast → desaturate → hue rotate (degrees).\nvec3 applyColorGrade(vec3 c){\n c = contrastFn(c, uContrast);\n c = desaturate(c, 1.0 - uSaturation);\n return hueShift(c, radians(uHueShift));\n}\n`;\n\n// The shared wave-shape deform (expStep + rotationMatrix + waveShape), used by BOTH the wave\n// vertex shader and the particle shed emitter, so the ribbon and the dust it sheds ride ONE deform.\nconst waveShapeChunk = /* glsl */ `\n// expStep: a falloff from 1 (at x=0) toward 0, sharpness set by n. The\n// max() guards pow(0, n) (= Infinity → NaN) so negative n is safe — negative n\n// just concentrates the twist toward the OTHER end instead.\nfloat expStep(float x, float n){ return exp2(-exp2(n) * pow(max(x, 1.0e-3), n)); }\n\n// rotationMatrix (mat4), used row-vector style: pos = (vec4(pos,1) * R).xyz\nmat4 rotationMatrix(vec3 axis, float angle){\n axis = normalize(axis);\n float s = sin(angle), c = cos(angle), oc = 1.0 - c;\n return mat4(\n oc*axis.x*axis.x + c, oc*axis.x*axis.y - axis.z*s, oc*axis.z*axis.x + axis.y*s, 0.0,\n oc*axis.x*axis.y + axis.z*s, oc*axis.y*axis.y + c, oc*axis.y*axis.z - axis.x*s, 0.0,\n oc*axis.z*axis.x - axis.y*s, oc*axis.y*axis.z + axis.x*s, oc*axis.z*axis.z + c, 0.0,\n 0.0, 0.0, 0.0, 1.0\n );\n}\n\n// The wave SHAPE deform, shared by the wave vertex shader (below) and the particle SHED emitter\n// (particleVertexShader): a base hairpin position + its uv → the displaced / helixed / twisted /\n// fanned LOCAL position, plus the three twist matrices (the pointer field reads them). Every branch\n// sits behind the SAME #ifdef gates as the code it replaces, so a given compiled program is\n// byte-identical to the former inline version. t / loopOff are the linear / orbit time the\n// caller computed; only the one selected by LOOP_MOTION is read (the other is a dead argument).\nstruct WaveShape { vec3 pos; mat4 rotA; mat4 rotB; mat4 rotC; };\nWaveShape waveShape(vec3 position, vec2 uv, float t, vec2 loopOff){\n // Displacement lifts Y by simplex noise of the (x,z) position.\n vec3 pos = position;\n#ifdef LOOP_MOTION\n pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX, pos.z * uDispFreqZ) + loopOff);\n#else\n pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX + t, pos.z * uDispFreqZ + t));\n#endif\n#ifdef DETAIL_OCTAVE\n // A second, finer octave riding on the broad swell (loop-orbit shared so it stays periodic).\n#ifdef LOOP_MOTION\n pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq, pos.z * uDetailFreq) + loopOff);\n#else\n pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq + t, pos.z * uDetailFreq + t));\n#endif\n#endif\n\n#ifdef HELIX\n // Helix — the periodic sweep the three twists (monotone falloffs) can't reach. Runs AFTER the\n // displacement (so the noise still samples undeformed pos) and BEFORE the twist (so they compose).\n float hAng = 6.28318530718 * uHelixTurns * uv.y + radians(uHelixPhase);\n // Roll about the ribbon's width centre, not the origin — see RIBBON_Z_CENTER in WaveGeometry.\n float rollA = hAng * uHelixRoll;\n float rollC = cos(rollA), rollS = sin(rollA);\n vec2 rel = vec2(pos.y, pos.z - ${RIBBON_Z_CENTER.toFixed(1)});\n pos.y = rel.x * rollC - rel.y * rollS;\n pos.z = ${RIBBON_Z_CENTER.toFixed(1)} + rel.x * rollS + rel.y * rollC;\n pos.y += uHelixRadius * cos(hAng);\n pos.z += uHelixRadius * sin(hAng);\n#endif\n\n // The X-twist frequency feeding rotB; the TWIST_MOTION variant modulates it with simplex noise\n // indexed along the ribbon (uv.y) so the twist breathes over time.\n float twistXFreq = uTwFreqX;\n#ifdef TWIST_MOTION\n#ifdef LOOP_MOTION\n float twistXNoise = simplexNoise(vec2(uv.y * 2.0, 0.0) + loopOff);\n#else\n float twistXNoise = simplexNoise(vec2(uv.y * 2.0, t));\n#endif\n twistXFreq = uTwFreqX - twistXNoise * 0.1;\n#endif\n\n // Three-axis twist (see the falloff-axis note: rotA keys off uv.x/WIDTH, rotB/rotC off uv.y/LENGTH).\n mat4 rotA = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqY * expStep(uv.x, uTwPowY));\n mat4 rotB = rotationMatrix(vec3(0.0, 0.5, 0.5), twistXFreq * expStep(uv.y, uTwPowX));\n mat4 rotC = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqZ * expStep(uv.y, uTwPowZ));\n pos = (vec4(pos, 1.0) * rotA).xyz;\n pos = (vec4(pos, 1.0) * rotB).xyz;\n pos = (vec4(pos, 1.0) * rotC).xyz;\n\n#ifdef RADIAL\n // Radial fan: remap the ribbon to polar around the LOCAL origin so its LENGTH fans into a plume.\n // uv.x (folded WIDTH) → fan ANGLE across uRadialArc; uv.y (LENGTH) → RADIUS, so a constant-uv.x\n // combed fiber becomes a constant-angle radial spoke. mix(pos, fanned, 0) is identity → off is\n // byte-identical. (Placement is the wave's position transform — the fan has no separate pivot.)\n {\n float rAng = radians(uRadialCenter) + (clamp(uv.x, 0.0, 1.0) - 0.5) * radians(uRadialArc);\n float rRho = uRadialRadius + uv.y * 400.0 * uRadialSpread; // 400 = native ribbon length\n vec3 rEr = vec3(cos(rAng), sin(rAng), 0.0); // radial dir, in local X–Y (screen plane)\n vec3 rEt = vec3(-sin(rAng), cos(rAng), 0.0); // tangential\n vec3 fanned = rEr * rRho\n + rEt * (pos.z - ${RIBBON_Z_CENTER.toFixed(1)}) * 0.5\n + vec3(0.0, 0.0, pos.y);\n pos = mix(pos, fanned, clamp(uRadialAmount, 0.0, 1.0));\n }\n#endif\n\n WaveShape s;\n s.pos = pos;\n s.rotA = rotA;\n s.rotB = rotB;\n s.rotC = rotC;\n return s;\n}\n`;\n\n// The POINTER FIELD, shared by the wave vertex shader and the particle emitter (particleVertexShader)\n// exactly as waveShapeChunk shares the deform — so a wave's dust reacts to the cursor through the SAME\n// footprint, falloff and displacement its ribbon does instead of staying pinned to the un-poked\n// surface. The whole chunk is interpolated INSIDE `#ifdef POINTER_FX` in both callers, so a wave with\n// no interaction config compiles the exact same program as before (JS-side uniform entries are always\n// present — see makeUniforms — but three only uploads uniforms the compiled program declares).\n// Requires simplexNoise and the uDispFreqX / uDispFreqZ shape uniforms declared above.\nconst pointerFieldChunk = /* glsl */ `\nuniform vec2 uPointer; // smoothed pointer, NDC (-1..1)\nuniform float uPointerActive; // presence ramp 0..1 × per-wave influence\nuniform float uPointerRadius; // falloff radius in NDC-y units (config radius × 2)\nuniform float uPointerAspect; // drawing-buffer dw/dh (circular screen falloff)\nuniform float uPointerAgitate;\nuniform float uPointerPush; // signed membrane dome at the cursor (+ repel / − attract)\nuniform float uPointerWake; // drag-wake trough amplitude (behind the moving cursor)\nuniform vec2 uPointerVel; // smoothed pointer velocity, NDC/s (drag-wake direction)\n// Ribbon flow: stretch the falloff along the strip's length axis so the field reaches ALONG the\n// ribbon rather than as a screen disc. 0 = the plain circular smoothstep (byte-identical when off).\nuniform float uShapeFlow;\n#ifdef POINTER_RIPPLES\nuniform vec2 uRippleOrigin[4]; // NDC\nuniform float uRippleAge[4]; // seconds since spawn (CPU-computed)\nuniform float uRippleAmp[4]; // shared 0..1 decay envelope per slot (CPU-computed; 0 = slot free)\nuniform float uPointerRipple; // THIS wave's ripple amplitude (scales the shared envelope)\nconst float RIPPLE_WAVE_SPEED = 0.85; // NDC/s the ring crest travels outward\nconst float RIPPLE_SIGMA = 0.14; // gaussian half-width of the travelling packet (NDC)\nconst float RIPPLE_FREQ = 11.0; // oscillation within the packet (one crest + faint troughs)\nconst float RIPPLE_MAX_R = 1.2; // reach where the crest has fully left the frame\n#endif\n\n// fall = screen falloff × presence (the wave's vPointerFall, which both fragment themes consume);\n// disp = the signed displacement along the surface's own up-axis, which the CALLER applies (the wave\n// in its local space, the dust through the wave's world matrix).\nstruct PointerHit { float fall; float disp; };\n\n// Sample the field for ONE point. ndc is that point's screen position; mvp the clip transform of the\n// space rotA/rotB/rotC and churnPos live in (the owning wave's local space); t / loopOff the caller's\n// linear / orbit time — only the one selected by LOOP_MOTION is read.\nPointerHit pointerField(vec2 ndc, mat4 mvp, mat4 rotA, mat4 rotB, mat4 rotC, vec3 churnPos,\n float t, vec2 loopOff){\n // Screen-space offset from the cursor (aspect-corrected → round in pixels). The DEFAULT metric.\n vec2 dp = (ndc - uPointer) * vec2(uPointerAspect, 1.0);\n // Ribbon flow: stretch the metric along the strip's own LENGTH axis so the field reaches ALONG the\n // ribbon and stays tight across it — the \"flows with the material\" feel, per-vertex (so it follows\n // the strip's curve) with no CPU surface pick. The length axis is local +X (uv.x runs with x)\n // carried through the SAME twist as the surface. The camera is orthographic (affine, w=1), so the\n // axis's screen image is the linear map of the DIRECTION (w=0): one mat·dir, no second\n // point-projection and no perspective divide. (A true per-pixel uv would need GPU picking — the\n // visible surface is shader-displaced, so a CPU raycast of the base geometry misses.)\n if (uShapeFlow > 0.0) {\n vec3 tangentLocal = (((vec4(1.0, 0.0, 0.0, 0.0) * rotA) * rotB) * rotC).xyz;\n vec2 tang = (mvp * vec4(tangentLocal, 0.0)).xy * vec2(uPointerAspect, 1.0);\n float tl = length(tang);\n if (tl > 1.0e-6) {\n tang /= tl;\n vec2 nrm = vec2(-tang.y, tang.x);\n dp = vec2(dot(dp, tang) / (1.0 + uShapeFlow * 2.5), dot(dp, nrm)); // up to 3.5× reach along length\n }\n }\n float fall = smoothstep(uPointerRadius, 0.0, length(dp)) * uPointerActive;\n // Agitation: a fast churn octave near the cursor (additive — never rewrites base noise t, which\n // would force restructuring the shared path). Loop-safe under both time variants.\n#ifdef LOOP_MOTION\n float disp = uPointerAgitate * fall\n * simplexNoise(vec2(churnPos.x * uDispFreqX * 3.0, churnPos.z * uDispFreqZ * 3.0) + loopOff * 4.0);\n#else\n float disp = uPointerAgitate * fall\n * simplexNoise(vec2(churnPos.x * uDispFreqX * 3.0 + t * 4.0, churnPos.z * uDispFreqZ * 3.0));\n#endif\n // Membrane push/pull: a smooth dome (fall is the falloff) that swells toward you (+ repel) or dents\n // away (− attract) at the cursor, riding along with the sprung field.\n disp += uPointerPush * fall;\n // Drag-wake: pull the surface just BEHIND the moving cursor into a trailing trough. dp points\n // from cursor to vertex; \"behind\" is how far the vertex sits opposite the velocity (0 ahead → 1 a\n // radius behind), gated by speed so it only forms while dragging and heals when the cursor stops.\n vec2 velC = uPointerVel * vec2(uPointerAspect, 1.0);\n float wakeSpeed = length(velC);\n if (uPointerWake != 0.0 && wakeSpeed > 1.0e-4) {\n float behind = clamp(dot(-dp, velC) / (wakeSpeed * uPointerRadius), 0.0, 1.0);\n disp -= uPointerWake * fall * behind * smoothstep(0.05, 0.6, wakeSpeed);\n }\n#ifdef POINTER_RIPPLES\n for (int i = 0; i < 4; i++) {\n if (uRippleAmp[i] > 0.0) {\n float rd = length((ndc - uRippleOrigin[i]) * vec2(uPointerAspect, 1.0));\n // A wave PACKET whose crest travels outward at RIPPLE_WAVE_SPEED: a gaussian window centred on\n // the moving front carrying a short oscillation (a raised ring with faint trailing troughs),\n // so the energy radiates instead of throbbing at the click point. The shared uRippleAmp\n // envelope fades the whole packet over its lifetime; reach fades it as the crest leaves frame.\n float front = uRippleAge[i] * RIPPLE_WAVE_SPEED;\n float band = rd - front;\n float packet = exp(-band * band / (2.0 * RIPPLE_SIGMA * RIPPLE_SIGMA)) * cos(band * RIPPLE_FREQ);\n float reach = 1.0 - smoothstep(RIPPLE_MAX_R * 0.7, RIPPLE_MAX_R, front);\n disp += uPointerRipple * uRippleAmp[i] * packet * reach;\n }\n }\n#endif\n PointerHit hit;\n hit.fall = fall;\n hit.disp = disp;\n return hit;\n}\n`;\n\nexport const vertexShader = /* glsl */ `\n${simplex2d}\n\nuniform float uTime, uSpeed, uSeed;\nuniform float uDispFreqX, uDispFreqZ, uDispAmount;\nuniform float uDetailFreq, uDetailAmount; // 2nd displacement octave (only read under DETAIL_OCTAVE)\nuniform float uTwFreqX, uTwFreqY, uTwFreqZ, uTwPowX, uTwPowY, uTwPowZ;\nuniform float uLoopSeconds; // seamless-loop period (only read under LOOP_MOTION)\n\n// Helix (optional). Behind HELIX so a wave without one compiles the exact same program — same\n// byte-identity contract as the pointer block below.\n#ifdef HELIX\nuniform float uHelixTurns; // full turns from one end of the ribbon to the other\nuniform float uHelixRadius; // orbit radius: carries the whole ribbon around the axis\nuniform float uHelixRoll; // cross-section roll, as a fraction of the turns (1 = rigid ladder)\nuniform float uHelixPhase; // degrees\n#endif\n\n// Radial fan (optional). Behind RADIAL so a wave without one compiles the exact same program (same\n// byte-identity contract as HELIX / POINTER_FX above).\n#ifdef RADIAL\nuniform float uRadialAmount; // 0..1 blend (0 = identity)\nuniform float uRadialArc; // fan spread, degrees\nuniform float uRadialSpread; // length → radius scale\nuniform float uRadialRadius; // source / inner radius\nuniform float uRadialCenter; // base angle, degrees\n#endif\n\nvarying vec2 vUv;\nvarying vec3 vWorldPos;\nvarying vec3 vViewDir;\nvarying vec4 vClipPosition; // = gl_Position, for the wireframe theme's depth fade\n\n// Pointer field (optional, additive) — the shared chunk, gated so a wave with no interaction config\n// compiles the exact same program. The particle emitter interpolates the SAME chunk, so dust reacts\n// through one implementation of the footprint / falloff / displacement.\n#ifdef POINTER_FX\n${pointerFieldChunk}\nvarying float vPointerFall; // falloff × presence — consumed by both fragment themes\n#endif\n\n${waveShapeChunk}\n\nvoid main(){\n vUv = uv;\n#ifndef LOOP_MOTION\n float t = uTime * uSpeed + uSeed;\n vec2 loopOff = vec2(0.0); // unused under linear time; kept so waveShape's signature is uniform\n#endif\n\n#ifdef LOOP_MOTION\n // Seamless loop: rather than scrolling the noise field linearly by t (which never repeats),\n // sample it on a circle of radius loopR at angle loopTheta — exactly periodic with period\n // uLoopSeconds. The tangential speed loopR·dθ/dt equals uSpeed, so the looped motion advances\n // at the same rate as the linear drift, just curved into a closed orbit (it orbits rather than\n // drifts — the trade-off for a seamless loop, hence opt-in). uSeed offsets the phase so stacked\n // waves keep their relative motion while sharing the single period.\n float loopTheta = uTime * (6.28318530718 / uLoopSeconds) + uSeed;\n float loopR = uSpeed * uLoopSeconds * 0.159154943092; // = uSpeed·uLoopSeconds / (2π)\n vec2 loopOff = loopR * vec2(cos(loopTheta), sin(loopTheta));\n float t = 0.0; // unused under loop time\n#endif\n\n // Deform the baked hairpin via the shared waveShape chunk (displacement + helix + twist + radial),\n // which also drives the particle shed emitter. It returns the deformed local pos + the twist\n // matrices the pointer field reads below.\n WaveShape ws = waveShape(position, uv, t, loopOff);\n vec3 pos = ws.pos;\n\n#ifdef POINTER_FX\n // Pointer field: displace along the wave's own (post-twist) up-axis, weighted by a screen-space\n // falloff around the smoothed cursor — a circle at uShapeFlow 0, stretched along the ribbon as it\n // rises. Everything here is ADDITIVE and fenced, so the shared path above/below is untouched and\n // byte-identical when POINTER_FX is off. The field itself lives in pointerFieldChunk, which the\n // particle emitter also calls — so dust reacts through this exact footprint and falloff.\n // Shared clip-space transform, computed once and reused for the cursor metric and the ribbon\n // tangent (the compiler is not guaranteed to CSE the triple product otherwise). Associativity is\n // unchanged, so preClip is bit-for-bit what the plain P*V*M*v product produced.\n mat4 mvp = projectionMatrix * viewMatrix * modelMatrix;\n vec4 preClip = mvp * vec4(pos, 1.0);\n PointerHit hit = pointerField(preClip.xy / max(preClip.w, 1.0e-6), mvp,\n ws.rotA, ws.rotB, ws.rotC, pos, t, loopOff);\n vPointerFall = hit.fall;\n // Displacement axis = local +Y carried through the SAME three twist rotations as pos (row-vector\n // convention). Rotations are linear, so post-twist axis displacement equals pre-twist Y displacement.\n vec3 dispAxis = (((vec4(0.0, 1.0, 0.0, 0.0) * ws.rotA) * ws.rotB) * ws.rotC).xyz;\n pos += dispAxis * hit.disp;\n#endif\n\n // The scale / rotation / position transform lives on the mesh (modelMatrix), so the\n // orientation matches THREE's Euler-XYZ rather than an in-shader rotation order.\n vec4 world = modelMatrix * vec4(pos, 1.0);\n vWorldPos = world.xyz;\n vViewDir = cameraPosition - world.xyz;\n gl_Position = projectionMatrix * viewMatrix * world;\n vClipPosition = gl_Position;\n}\n`;\n\nexport const fragmentShader = /* glsl */ `\n#define MAX_COLORS ${MAX_COLORS}\n#define MAX_MESH_POINTS ${MAX_MESH_POINTS}\n#define MAX_LIGHTS ${MAX_LIGHTS}\n#define MAX_NOISE_BANDS ${MAX_NOISE_BANDS}\n#define PI 3.14159265359\n\n${simplex2d}\n\n${colorUniforms}\nuniform float uDebug; // dev: 1 = show crease, 2 = show derivative normal\nuniform float uSheen; // white-lift on the flat (low-crease) areas (1 = full)\nuniform float uRoundness; // pose-robust normal-based roundness/thickness strength\nuniform float uIridescence; // thin-film hue shift with view angle (0 = off)\nuniform float uFiberCount;\nuniform float uFiberStrength;\nuniform float uTexture;\nuniform float uCreaseLight;\nuniform float uCreaseSharpness;\nuniform float uCreaseSoftness;\nuniform float uEdgeFade;\nuniform vec2 uResolution;\nuniform float uAmbient;\nuniform int uNumLights;\nuniform vec3 uLightPos[MAX_LIGHTS];\nuniform vec3 uLightColor[MAX_LIGHTS];\nuniform float uLightIntensity[MAX_LIGHTS];\nuniform int uNumNoiseBands;\nuniform vec4 uNoiseBandBounds[MAX_NOISE_BANDS]; // (startX, endX, startY, endY)\nuniform vec4 uNoiseBandParams[MAX_NOISE_BANDS]; // (feather, strength, frequency, colorAttenuation)\nuniform float uNoiseBandParaPow[MAX_NOISE_BANDS];\n\nvarying vec2 vUv;\nvarying vec3 vWorldPos;\nvarying vec3 vViewDir;\n#ifdef DEPTH_TINT\nuniform float uDepthTint;\nuniform vec3 uDepthTintColor;\nvarying vec4 vClipPosition; // clip-space depth (written by the vertex shader for both programs)\n#endif\n#ifdef EDGE_FEATHER\nuniform float uEdgeFeather; // softness of the ribbon's two ENDS (only when it differs from 0.1)\n#endif\n#ifdef POINTER_FX\nuniform float uPointerThin; // 0..1 local translucency near the cursor\nuniform float uPointerHue; // degrees, local hue rotation near the cursor\nuniform float uPointerLighten; // -1..1 local brightness lift near the cursor\nvarying float vPointerFall; // falloff × presence, written by the vertex shader\n#endif\n\n// Cheap value hash for the optional grain overlay (distinct from the simplex hash).\nfloat grainHash(vec2 p){ return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\n\nfloat parabola(float x, float k){ return pow(4.0 * x * (1.0 - x), k); }\nfloat mapLinear(float v, float a, float b, float c, float d){ return c + (v - a) * (d - c) / (b - a); }\n\n${colorFns}\n\n// Striations: a subtle high-frequency simplex-noise grain ADDED to the\n// colour — colour-matched (weaker where blue is high), only near folds (crease), and\n// concentrated toward the ends (parabola). Blends in rather than reading as hard lines.\nvec3 surfaceStreaks(vec2 uv, vec3 color, float crease){\n float strength = uFiberStrength; // default 0.2\n float freq = uFiberCount; // default 600\n float colorAtten = 0.9;\n float paraPow = 3.0;\n // Noise bands: inside each rectangular uv region the\n // fiber params are overridden, so the streaks vary per region instead of uniform.\n for (int i = 0; i < MAX_NOISE_BANDS; i++) {\n if (i >= uNumNoiseBands) break;\n vec4 b = uNoiseBandBounds[i];\n vec4 prm = uNoiseBandParams[i];\n float feather = max(prm.x, 1.0e-4);\n float blend =\n smoothstep(b.x - feather, b.x, uv.x) * (1.0 - smoothstep(b.y, b.y + feather, uv.x)) *\n smoothstep(b.z - feather, b.z, uv.y) * (1.0 - smoothstep(b.w, b.w + feather, uv.y));\n strength = mix(strength, prm.y, blend);\n freq = mix(freq, prm.z, blend);\n colorAtten = mix(colorAtten, prm.w, blend);\n paraPow = mix(paraPow, uNoiseBandParaPow[i], blend);\n }\n // The high frequency runs along uv.x (the folded WIDTH — see WaveGeometry's UV AXES note),\n // packing many thin stripes across the cross-section while uv.y is barely scaled, so each\n // one stretches out into a fine LENGTHWISE fiber. 1 - parabola(uv.x) then weights them\n // toward the two long edges and away from the width centreline.\n float p = 1.0 - parabola(uv.x, paraPow);\n float n0 = simplexNoise(vec2(uv.x * 0.1, uv.y * 0.5));\n float n1 = simplexNoise(vec2(uv.x * (freq + freq * 0.5 * n0), uv.y * 4.0 * n0));\n n1 = mapLinear(n1, -1.0, 1.0, 0.0, 1.0);\n color += n1 * strength * (1.0 - color.b * colorAtten) * crease * p;\n return color;\n}\n\nvoid main(){\n // crease: a foreshortening / fold detector from the screen-space uv derivative.\n // It drives BOTH the roundness shading and where the streaks appear — this is what\n // gives the wave its thickness without any normal-based lighting.\n float crease = dFdy(vUv).y * uResolution.y * uCreaseLight;\n crease = clamp(mapLinear(crease, -1.0, 1.0, 0.0, 1.0), 0.0, 1.0);\n crease = pow(crease, uCreaseSharpness);\n crease = clamp(smoothstep(0.0, uCreaseSoftness, crease), 0.0, 1.0);\n\n // Debug visualisations (dev): 1 = crease value, 2 = derivative surface normal.\n if (uDebug > 0.5) {\n if (uDebug < 1.5) { gl_FragColor = vec4(vec3(crease), 1.0); return; }\n vec3 dn = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n gl_FragColor = vec4(dn * 0.5 + 0.5, 1.0); return;\n }\n\n // Colour: sample the baked 2D palette texture, or fall back to the procedural 1-D\n // gradient (see waveBaseColor).\n vec3 col = waveBaseColor(vUv);\n col = surfaceStreaks(vUv, col, crease);\n col = applyColorGrade(col);\n\n#ifdef POINTER_FX\n // Local hue rotation + brightness lift near the cursor (both fade out with vPointerFall).\n col = hueShift(col, radians(uPointerHue) * vPointerFall);\n col *= 1.0 + uPointerLighten * vPointerFall;\n#endif\n\n // Iridescence: a thin-film / holographic hue that shifts with view angle. Reuses the same\n // camera-facing ratio as roundness (recomputed here, since roundness may be off): grazing parts\n // of the ribbon (low facing) shift hue most, so the colour flows as the ribbon curves. Skipped\n // at 0, so the compiled result is unchanged when off.\n if (uIridescence > 0.001) {\n vec3 iridN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n float iridFacing = abs(dot(iridN, normalize(vViewDir)));\n col = hueShift(col, (1.0 - iridFacing) * uIridescence * PI);\n }\n\n // Sheen: lift the flat (low-crease) areas toward white. This is\n // pose-dependent (it keys off dFdy(uv.y)), so we keep it gentle and add a robust term.\n col += (1.0 - crease) * 0.25 * uSheen;\n\n // Pose-robust roundness: shade by the camera-facing ratio of the derivative surface\n // normal so the ribbon reads as a rounded, grabbable solid from any angle. Grazing\n // edges darken into shadow (defining the rounded form), the body keeps its full colour,\n // and the most face-on sliver catches a soft highlight. uRoundness = strength.\n if (uRoundness > 0.001) {\n vec3 volN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n float facing = abs(dot(volN, normalize(vViewDir))); // 1 = facing camera, 0 = edge-on\n col *= mix(1.0 - 0.6 * uRoundness, 1.0, facing); // deepen grazing edges → solid form\n col += smoothstep(0.65, 1.0, facing) * uRoundness * 0.18; // soft highlight on the facing body\n }\n\n // Optional positionable lights (our feature) — additive & gentle, on top of the\n // base shading so the default look is preserved. A finely-subdivided mesh\n // keeps this derivative normal smooth.\n if (uNumLights > 0) {\n vec3 N = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n vec3 Vd = normalize(vViewDir);\n if (dot(N, Vd) < 0.0) N = -N;\n for (int i = 0; i < MAX_LIGHTS; i++) {\n if (i >= uNumLights) break;\n vec3 L = normalize(uLightPos[i] - vWorldPos);\n vec3 lc = uLightColor[i] * uLightIntensity[i];\n float diff = max(dot(N, L), 0.0);\n float spec = pow(max(dot(N, normalize(L + Vd)), 0.0), 28.0);\n col += col * diff * lc * 0.16 + spec * lc * 0.10;\n }\n }\n col *= 0.55 + clamp(uAmbient, 0.0, 1.0); // overall level; default 0.45 => x1.0 (neutral)\n\n#ifdef DEPTH_TINT\n // Depth tint: fade far fragments toward a colour so a multi-wave stack gains atmospheric\n // separation — near strands keep their colour, far ones recede. Reuses the clip-space depth the\n // wireframe theme fades with (clamp(z*6), where 1 = far).\n col = mix(col, uDepthTintColor, clamp(vClipPosition.z * 6.0, 0.0, 1.0) * uDepthTint);\n#endif\n\n if (uTexture > 0.001) col *= 1.0 + (grainHash(vUv * 850.0) - 0.5) * uTexture * 0.25;\n\n // Soft ribbon ENDS (it fades on vUv.y, the length) + optional viewport-edge fade. The edge\n // softness is the hardcoded 0.1 by\n // default (literal branch → byte-identical); EDGE_FEATHER swaps in the uEdgeFeather knob only\n // when it differs, so razor-crisp or vapor-soft edges are both reachable.\n#ifdef EDGE_FEATHER\n float ribEdge =\n smoothstep(0.0, uEdgeFeather, vUv.y) * (1.0 - smoothstep(1.0 - uEdgeFeather, 1.0, vUv.y));\n#else\n float ribEdge = smoothstep(0.0, 0.1, vUv.y) * (1.0 - smoothstep(0.9, 1.0, vUv.y));\n#endif\n float alpha = uOpacity * ribEdge;\n#ifdef POINTER_FX\n alpha *= clamp(1.0 - uPointerThin * vPointerFall, 0.0, 1.0); // solid: local translucency\n#endif\n if (uEdgeFade > 0.001) {\n vec2 sc = gl_FragCoord.xy / max(uResolution, vec2(1.0));\n float vig =\n smoothstep(0.0, uEdgeFade, sc.x) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.x)) *\n smoothstep(0.0, uEdgeFade, sc.y) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.y));\n alpha *= vig;\n }\n\n // Deep \"squared\" hero colour: formerly done by a framebuffer-squaring blend that REPLACED the\n // destination (punching holes at soft edges / where waves overlap). Squaring here + normal\n // premultiplied compositing (see applyBlendMode) keeps the deep colour and blends correctly.\n col = clamp(col, 0.0, 1.0);\n // Square colour AND alpha so the soft ribbon edges keep the crisp, thin feather of the original\n // squared-blend look — but now composited (premultiplied) rather than replace-blended, so they\n // no longer punch holes. Over an opaque background alpha² still resolves to fully opaque.\n if (uSquared > 0.5) { col *= col; alpha *= alpha; }\n gl_FragColor = vec4(col, alpha);\n#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n}\n`;\n\n// ---- Wireframe \"thin-line\" theme ----\n// The same wave geometry, but instead of a solid surface the colour is carved into fine\n// LENGTHWISE strands (abs(sin(uv.x * lineAmount)) — uv.x is the folded width, so lineAmount\n// counts strands ACROSS the cross-section and each runs end to end) whose thickness scales\n// with the screen-space uv derivative, then mixed line<->background with a depth fade. Used by the dark\n// hero preset. hueShift takes degrees (radians() here) to match the light shader.\nexport const lineFragmentShader = /* glsl */ `\n#define MAX_COLORS ${MAX_COLORS}\n#define MAX_MESH_POINTS ${MAX_MESH_POINTS}\n#define PI 3.14159265359\n\n${simplex2d}\n\n${colorUniforms}\nuniform float uLineAmount; // default 425\nuniform float uLineThickness; // default 1\nuniform float uLineDerivativePower; // default 0.95\nuniform float uMaxWidth; // default 1232\n// Cross-wise rungs (optional) — behind RUNGS so a wave without them compiles the same program.\n#ifdef RUNGS\nuniform float uRungAmount; // frequency across the ribbon (rungs ≈ amount / π)\nuniform float uRungThickness; // rung width in pixels\n#endif\nuniform vec3 uClearColor; // = page background colour (shown between the lines)\n\nvarying vec2 vUv;\nvarying vec4 vClipPosition;\n#ifdef POINTER_FX\nuniform float uPointerThin; // 0..1 — strands taper to hairlines near the cursor\nuniform float uPointerHue; // degrees, local hue rotation near the cursor\nuniform float uPointerLighten; // -1..1 local brightness lift near the cursor\nvarying float vPointerFall; // falloff × presence, written by the vertex shader\n#endif\n\n${colorFns}\n\nvoid main(){\n // Same 2D palette sample + colour ops as the solid theme.\n vec3 color = applyColorGrade(waveBaseColor(vUv));\n\n#ifdef POINTER_FX\n color = hueShift(color, radians(uPointerHue) * vPointerFall);\n color *= 1.0 + uPointerLighten * vPointerFall;\n#endif\n\n // Carve into fine lengthwise strands; thickness from the screen-space uv derivative.\n vec2 dy = dFdy(vUv);\n float lineThickness = uLineThickness * pow(abs(dy.x * uMaxWidth), uLineDerivativePower);\n#ifdef POINTER_FX\n lineThickness *= clamp(1.0 - uPointerThin * vPointerFall, 0.0, 1.0); // wireframe: taper strands\n#endif\n float a = abs(sin(vUv.x * uLineAmount));\n a = smoothstep(lineThickness, 0.0, a);\n\n#ifdef RUNGS\n // Rungs: the same carve at constant uv.y instead of uv.x, so this family runs ACROSS the ribbon\n // where the one above runs along it — together they read as a ladder. Width comes from fwidth()\n // rather than the lengthwise term's dFdy(vUv).x, which is the derivative of the wrong axis for\n // this direction: |sin| climbs by ~uRungAmount·fwidth(vUv.y) per pixel, so scaling by that keeps\n // a rung uRungThickness pixels wide at any zoom or ribbon scale.\n float rung = abs(sin(vUv.y * uRungAmount));\n a = max(a, smoothstep(uRungThickness * uRungAmount * fwidth(vUv.y), 0.0, rung));\n#endif\n\n // Depth fade: the wave recedes into the background colour with depth. Watch the\n // argument order: clamp(0.0, 1.0, z*6) is a swapped-args trap — it clamps the\n // constant 0.0 into [1.0, z*6], i.e. min(1.0, z*6), which (with our ortho clip.z\n // range) collapses the whole wave to the background. The correct clamp(z*6, 0, 1)\n // gives the proper subtle far-end fade and thin-line look.\n float depthFade = clamp(vClipPosition.z * 6.0, 0.0, 1.0);\n color = mix(uClearColor, color, a * (1.0 - depthFade));\n if (uSquared > 0.5) color *= color; // deep \"squared\" look, now composited not replace-blended\n gl_FragColor = vec4(color, uOpacity);\n#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n}\n`;\n\n// ---- Post pass: viewport-edge soft-focus blur + dither grain ----\n\nexport const postVertexShader = /* glsl */ `\nvarying vec2 vUv;\nvoid main(){\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n`;\n\nexport const postFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform vec2 uResolution;\nuniform float uBlurAmount;\nuniform int uBlurSamples;\nuniform float uGrainAmount;\nuniform float uTime;\nvarying vec2 vUv;\n\nfloat random2(vec2 st){ return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453); }\n\n// Angular (spin) blur: rotate the sample coord around the centre and\n// accumulate — a tangential smear that grows toward the edges. Carries alpha so a\n// transparent background survives the post pass.\nvec4 blurAngular(sampler2D tex, vec2 uv, float angle, int samples){\n vec4 total = vec4(0.0);\n vec2 coord = uv - 0.5;\n float dist = 1.0 / float(samples);\n vec2 dir = vec2(cos(angle * dist), sin(angle * dist));\n mat2 rot = mat2(dir.x, dir.y, -dir.y, dir.x);\n for (int i = 0; i < 64; i++){\n if (i >= samples) break;\n total += texture2D(tex, coord + 0.5);\n coord = coord * rot; // row-vector order (coord * rot) sets the spin direction\n }\n return total * dist;\n}\n\nvoid main(){\n vec4 sceneColor = texture2D(tDiffuse, vUv);\n vec4 blurColor = blurAngular(tDiffuse, vUv, uBlurAmount, uBlurSamples);\n // blurPower: keep a sharp band weighted to the middle, blurring toward top & bottom.\n float blurPower = smoothstep(0.0, 0.7, vUv.y) - smoothstep(0.2, 1.0, vUv.y);\n vec4 color = mix(blurColor, sceneColor, blurPower);\n // Static film grain: keyed off gl_FragCoord only (no uTime), so it doesn't flicker.\n color.rgb += mix(uGrainAmount, -uGrainAmount, random2(gl_FragCoord.xy * 0.01)) * (4.0 / 255.0);\n gl_FragColor = color; // preserve alpha → transparent background works\n}\n`;\n\n// ---- Post pass: ordered (Bayer) dithering ----\n//\n// DERIVED FROM @paper-design/shaders `image-dithering` (https://github.com/paper-design/shaders,\n// Apache-2.0 — see THIRD-PARTY-NOTICES.md). The Bayer matrices, getBayerValue, and the brightness /\n// luminance-quantization / hue-preserving \"original colours\" recolour are paper's. Adapted to a\n// post pass: samples the composited scene (tDiffuse) at full-frame vUv instead of paper's sized/fit\n// u_image UV, drops the frame/aspect machinery, fixes the 8x8 matrix (paper's default), and gates\n// via uDitherStrength. The int[] arrays + dynamic indexing compile because three builds\n// ShaderMaterials as \"#version 300 es\". Runs AFTER OutputPass, so it dithers display-space colour;\n// keyed off gl_FragCoord/tDiffuse only (no uTime) → deterministic, friendly to pixel-digest checks.\nexport const ditherFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform vec2 uResolution;\nuniform float uDitherStrength; // 0..1 mix back toward the original\nuniform float uDitherScale; // pixel-block size in device px (paper: u_pxSize)\nuniform float uDitherSteps; // quantization levels (paper: u_colorSteps)\nvarying vec2 vUv;\n\nconst int bayer2x2[4] = int[4](0, 2, 3, 1);\nconst int bayer4x4[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5);\nconst int bayer8x8[64] = int[64](\n 0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26,\n 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30, 54, 22,\n 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25,\n 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21\n);\nfloat getBayerValue(vec2 uv, int size){\n ivec2 pos = ivec2(fract(uv / float(size)) * float(size));\n int index = pos.y * size + pos.x;\n if (size == 2) return float(bayer2x2[index]) / 4.0;\n else if (size == 4) return float(bayer4x4[index]) / 16.0;\n else if (size == 8) return float(bayer8x8[index]) / 64.0;\n return 0.0;\n}\n\nvoid main(){\n float pxSize = max(uDitherScale, 1.0);\n vec2 pxSizeUV = gl_FragCoord.xy / pxSize;\n vec2 sampleUV = (floor(gl_FragCoord.xy / pxSize) + 0.5) * pxSize / max(uResolution, vec2(1.0));\n vec4 image = texture2D(tDiffuse, sampleUV);\n\n float lum = dot(vec3(0.2126, 0.7152, 0.0722), image.rgb);\n float colorSteps = max(floor(uDitherSteps), 1.0);\n\n float dithering = getBayerValue(pxSizeUV, 8) - 0.5; // paper's default 8x8 ordered screen\n float brightness = clamp(lum + dithering / colorSteps, 0.0, 1.0);\n brightness = mix(0.0, brightness, image.a);\n float quantLum = floor(brightness * colorSteps + 0.5) / colorSteps;\n\n // paper's \"original colours\" path: keep the source hue, quantize luminance.\n vec3 color = image.rgb / max(lum, 0.001) * quantLum;\n float quantAlpha = floor(image.a * colorSteps + 0.5) / colorSteps;\n float opacity = mix(quantLum, 1.0, quantAlpha);\n\n gl_FragColor = mix(image, vec4(color, opacity), clamp(uDitherStrength, 0.0, 1.0));\n}\n`;\n\n// ---- Post pass: innerLight (volumetric light streaks) — another \"layered\" post shader ----\n//\n// Radial light-scattering (à la GPU Gems 3): from each pixel, march toward a light point and\n// accumulate the wave's own brightness (weighted by alpha, so only opaque pixels emit), then add\n// the streaks back. Runs in the scene zone so it scatters the raw, pre-tone-map wave like bloom.\nexport const innerLightFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uInnerLight; // 0..1 strength of the added light\nuniform float uInnerLightDensity; // ray length / spread\nuniform float uInnerLightDecay; // per-sample falloff (<1)\nuniform vec2 uInnerLightCenter; // light source, UV (0..1)\nvarying vec2 vUv;\n\nconst int LIGHT_SAMPLES = 24;\n\nfloat luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }\n\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n vec2 delta = (vUv - uInnerLightCenter) * (uInnerLightDensity / float(LIGHT_SAMPLES));\n vec2 coord = vUv;\n float decay = 1.0;\n vec3 rays = vec3(0.0);\n for (int i = 0; i < LIGHT_SAMPLES; i++){\n coord -= delta;\n vec4 s = texture2D(tDiffuse, coord);\n rays += s.rgb * s.a * decay; // only opaque (wave) pixels emit light\n decay *= uInnerLightDecay;\n }\n rays /= float(LIGHT_SAMPLES);\n vec3 outc = src.rgb + rays * uInnerLight;\n float outA = max(src.a, luma(rays) * uInnerLight); // shafts stay visible over the transparent bg\n gl_FragColor = vec4(outc, clamp(outA, 0.0, 1.0));\n}\n`;\n\n// ---- Post pass: halftone (rotated dot screen) ----\n//\n// DERIVED FROM @paper-design/shaders `halftone-dots` (https://github.com/paper-design/shaders,\n// Apache-2.0 — see THIRD-PARTY-NOTICES.md). Ports the \"classic\" dot type + \"original colours\" path:\n// paper's getCircle (dot radius ← 1 − luminance, fwidth-antialiased) and sigmoid-contrast luminance,\n// sampled once per cell centre. Adapted to a post pass — samples the composited scene (tDiffuse)\n// instead of paper's sized u_image, drops the gooey/holes/soft dot types, the diagonal grid and the\n// grain layers, and composites transparent between dots. Contrast/radius fixed at paper's defaults.\nexport const halftoneFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform vec2 uResolution;\nuniform float uHalftone; // 0..1 mix\nuniform float uHalftoneCell; // dot cell size in device px (paper: u_size)\nuniform float uHalftoneAngle; // screen rotation (radians, paper: u_rotation)\nvarying vec2 vUv;\n\nfloat sigmoid(float x, float k){ return 1.0 / (1.0 + exp(-k * (x - 0.5))); }\n// paper's classic dot: radius grows as the sampled cell darkens (1 - lum), soft edge via fwidth.\nfloat getCircle(vec2 uv, float lum, float baseR){\n float r = mix(0.25 * baseR, 0.0, lum);\n float d = length(uv - 0.5);\n float aa = fwidth(d);\n return 1.0 - smoothstep(r - aa, r + aa, d);\n}\n\nvoid main(){\n float ca = cos(uHalftoneAngle);\n float sa = sin(uHalftoneAngle);\n mat2 rot = mat2(ca, sa, -sa, ca);\n float cell = max(uHalftoneCell, 2.0);\n vec2 gridPx = rot * gl_FragCoord.xy; // rotate the screen into the dot grid\n vec2 cellId = floor(gridPx / cell);\n vec2 inCell = fract(gridPx / cell); // position within the cell (0..1)\n vec2 centrePx = transpose(rot) * ((cellId + 0.5) * cell); // cell centre, back in screen px\n vec4 tex = texture2D(tDiffuse, centrePx / max(uResolution, vec2(1.0)));\n\n float k = 2.0; // sigmoid contrast (paper default)\n vec3 c = vec3(sigmoid(tex.r, k), sigmoid(tex.g, k), sigmoid(tex.b, k));\n float lum = dot(vec3(0.2126, 0.7152, 0.0722), c);\n lum = mix(1.0, lum, tex.a);\n float dot = getCircle(inCell, lum, 1.3); // baseR 1.3 ≈ paper original-colours default\n vec4 dots = vec4(tex.rgb, tex.a * dot); // wave-coloured dots, transparent between\n gl_FragColor = mix(texture2D(tDiffuse, vUv), dots, clamp(uHalftone, 0.0, 1.0));\n}\n`;\n\n// ---- Post pass: heatmap (map luminance → thermal palette) — a finish-zone filter ----\nexport const heatmapFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uHeatmap; // 0..1 mix\nvarying vec2 vUv;\nvec3 heat(float t){\n t = clamp(t, 0.0, 1.0);\n vec3 c = mix(vec3(0.0, 0.0, 0.4), vec3(0.0, 0.6, 1.0), smoothstep(0.0, 0.25, t));\n c = mix(c, vec3(0.0, 1.0, 0.4), smoothstep(0.25, 0.5, t));\n c = mix(c, vec3(1.0, 1.0, 0.0), smoothstep(0.5, 0.75, t));\n c = mix(c, vec3(1.0, 0.1, 0.0), smoothstep(0.75, 1.0, t));\n return c;\n}\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n float l = dot(src.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(mix(src.rgb, heat(l), clamp(uHeatmap, 0.0, 1.0)), src.a);\n}\n`;\n\n// ---- Post pass: paper texture (fibrous substrate shading) — a finish-zone overlay ----\nexport const paperTextureFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uPaper; // 0..1 strength\nuniform float uPaperScale; // grain scale\nvarying vec2 vUv;\nfloat h21(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n vec2 p = gl_FragCoord.xy / max(uPaperScale, 0.5);\n float fiber = h21(floor(p)) * 0.5 + h21(floor(p * vec2(0.3, 3.0))) * 0.5; // directional fibers\n float tex = mix(fiber, h21(gl_FragCoord.xy), 0.3); // + fine speckle\n float shade = 1.0 - (tex - 0.5) * 0.35;\n gl_FragColor = vec4(src.rgb * mix(1.0, shade, clamp(uPaper, 0.0, 1.0)), src.a);\n}\n`;\n\n// ---- Post pass: CMYK halftone (four rotated dot screens) — a finish-zone filter ----\nexport const halftoneCmykFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform float uHalftoneCmyk; // 0..1 mix\nuniform float uHalftoneCmykCell; // dot cell size in device px\nvarying vec2 vUv;\n// One rotated halftone dot screen for a channel value.\nfloat dotScreen(vec2 coord, float value, float angle, float cell){\n float ca = cos(angle);\n float sa = sin(angle);\n vec2 r = mat2(ca, sa, -sa, ca) * coord;\n vec2 c = fract(r / max(cell, 2.0)) - 0.5;\n float radius = sqrt(clamp(value, 0.0, 1.0)) * 0.5;\n return smoothstep(radius, radius - 0.06, length(c));\n}\nvoid main(){\n vec4 src = texture2D(tDiffuse, vUv);\n float k = 1.0 - max(max(src.r, src.g), src.b); // RGB → CMYK\n float invK = max(1.0 - k, 1e-3);\n float cyan = (1.0 - src.r - k) / invK;\n float mag = (1.0 - src.g - k) / invK;\n float yel = (1.0 - src.b - k) / invK;\n vec2 coord = gl_FragCoord.xy;\n float cell = uHalftoneCmykCell;\n float dc = dotScreen(coord, cyan, 1.309, cell); // 75°\n float dm = dotScreen(coord, mag, 0.262, cell); // 15°\n float dy = dotScreen(coord, yel, 0.0, cell); // 0°\n float dk = dotScreen(coord, k, 0.785, cell); // 45°\n // Subtractive: cyan ink absorbs red, magenta absorbs green, yellow absorbs blue, black absorbs all.\n vec3 outc = vec3(1.0) - vec3(dc, 0.0, 0.0) - vec3(0.0, dm, 0.0) - vec3(0.0, 0.0, dy) - vec3(dk);\n outc = clamp(outc, 0.0, 1.0);\n gl_FragColor = vec4(mix(src.rgb, outc, clamp(uHalftoneCmyk, 0.0, 1.0)), src.a);\n}\n`;\n\n// ---------------------------------------------------------------------------------------------\n// Particle field (additive dust / sparkle) — ONE per wave. A THREE.Points ShaderMaterial: every\n// particle's position + life is a pure function of uTime + baked per-particle attributes (aSeed / aRnd\n// / aUv), so the whole field is deterministic (timeOffset scrub / loopSeconds / paused all hold).\n// Every particle spawns on the OWNING wave's DEFORMED surface / edge (via the shared waveShape chunk,\n// riding the exact deform the ribbon uses) and drifts outward from the wave centre as it ages. The\n// wave's shape #defines (HELIX/RADIAL/…) are mirrored onto this material in configure().\n// ---------------------------------------------------------------------------------------------\nexport const particleVertexShader = /* glsl */ `\nattribute float aSeed;\nattribute vec4 aRnd;\nattribute vec2 aUv; // where this particle spawns on the ribbon (x = flank, y = along length; edge-biased at build)\n\nuniform float uTime, uLoopSeconds, uLife, uSize, uSizeJitter, uTwinkle, uPixelRatio;\nuniform float uPartSpeed;\nuniform vec3 uColor, uColor2, uCenter, uRight, uUp;\nuniform float uDrift, uRise, uSwirl, uWander;\n\n// The owning wave's shape, mirrored in configure() so the dust rides the SAME deform as the ribbon.\n// The HELIX/RADIAL uniform blocks are declared only when the matching #define is set.\n${simplex2d}\nuniform float uDispFreqX, uDispFreqZ, uDispAmount;\nuniform float uDetailFreq, uDetailAmount;\nuniform float uTwFreqX, uTwFreqY, uTwFreqZ, uTwPowX, uTwPowY, uTwPowZ;\n#ifdef HELIX\nuniform float uHelixTurns, uHelixRadius, uHelixRoll, uHelixPhase;\n#endif\n#ifdef RADIAL\nuniform float uRadialAmount, uRadialArc, uRadialSpread, uRadialRadius, uRadialCenter;\n#endif\nuniform mat4 uShedModel; // the wave's matrixWorld (deformed LOCAL → world)\nuniform float uShedSpeed, uShedSeed;\n${waveShapeChunk}\n\n// The cursor. Same chunk the ribbon uses, mirrored onto this material in ParticleField.configure(),\n// and behind the same POINTER_FX gate — a wave with no hover field compiles the point program it\n// always did. uPartShove is the one particle-only knob (see the two samples in main).\n#ifdef POINTER_FX\n${pointerFieldChunk}\nuniform float uPartShove; // how hard the cursor shoves dust that has already drifted free (0 = off)\n#endif\n\nvarying float vAlpha;\nvarying vec3 vColor;\nvarying vec2 vDir; // screen-space motion direction (for the streak sprite)\n\nconst float TAU = 6.28318530718;\n\nvoid main(){\n // Deterministic life: age 0..1 from uTime + a per-particle seed. Advances once per loop period when\n // looping (so the whole field repeats seamlessly), else once per uLife seconds. uPartSpeed scales the\n // cadence (motion speed); under a loop it snaps to a whole number of cycles so the seam stays seamless.\n float cyc = max(1.0, floor(uPartSpeed + 0.5));\n float rate = (uLoopSeconds > 0.0) ? (uTime / uLoopSeconds * cyc) : (uTime * uPartSpeed / max(uLife, 0.001));\n float age = fract(rate + aSeed);\n float fade = sin(3.14159265 * age); // 0 at birth/death, 1 mid-life\n\n // Spawn on the owning wave's DEFORMED surface / edge at aUv (via the shared waveShape), then peel\n // outward from the wave centre as the particle ages — silk dissolving into glitter.\n float ts = uTime * uShedSpeed + uShedSeed;\n vec2 loopOff = vec2(0.0);\n#ifdef LOOP_MOTION\n float loopTheta = uTime * (TAU / uLoopSeconds) + uShedSeed;\n float loopR = uShedSpeed * uLoopSeconds * 0.159154943092;\n loopOff = loopR * vec2(cos(loopTheta), sin(loopTheta));\n ts = 0.0;\n#endif\n // Approximate the base hairpin point for this uv (length from uv.y; width centre), then deform it\n // exactly as the wave does. Good enough for dust — the fan / displacement dominate.\n vec3 base = vec3((aUv.y - 0.5) * 400.0, 0.0, ${RIBBON_Z_CENTER.toFixed(1)});\n WaveShape ws = waveShape(base, aUv, ts, loopOff);\n vec3 origin = (uShedModel * vec4(ws.pos, 1.0)).xyz;\n vec3 outward = normalize(origin - uCenter + vec3(1e-4));\n\n#ifdef POINTER_FX\n // WELD (applied below, once the mote's own motion is known). The ribbon displaces its surface by\n // pointerField() along its own post-twist up-axis; a mote sitting ON that surface has to take the\n // same ride, or the cursor's dome lifts the silk out from under its own glitter. Sampled at the\n // SPAWN point and carried through the local→world matrix exactly as the ribbon's own\n // pos += dispAxis * disp is, so the two land on the same place. Sampling at the spawn point also\n // leaves outward derived from the UNDISPLACED origin, so a poke never bends the drift direction.\n mat4 pMvp = projectionMatrix * viewMatrix * uShedModel;\n vec4 originClip = pMvp * vec4(ws.pos, 1.0);\n vec3 dispAxis = mat3(uShedModel) * (((vec4(0.0, 1.0, 0.0, 0.0) * ws.rotA) * ws.rotB) * ws.rotC).xyz;\n PointerHit weld = pointerField(originClip.xy / max(originClip.w, 1.0e-6), pMvp,\n ws.rotA, ws.rotB, ws.rotC, ws.pos, ts, loopOff);\n#endif\n\n vec3 p = origin + outward * age * uDrift + (aRnd.xyz - 0.5) * age * uDrift * 0.35;\n\n // Motion styles, each 0 = off, all riding age so they stay loop-safe (the age wrap is hidden by\n // fade→0 at birth/death). rise = screen-vertical buoyancy (embers up / snow down); swirl = orbit\n // around the wave centre in the screen plane; wander = curl-noise turbulence (fireflies / motes).\n p += uUp * age * uRise;\n // How far this mote travels away from its birth patch over a WHOLE life — the straight-line terms\n // plus, under swirl, the arc it sweeps at its own orbit radius. Only the pointer weld reads it\n // (0 for dust that merely clings to the surface, which is exactly the case age would get wrong),\n // so it is fenced like everything else the cursor drives.\n#ifdef POINTER_FX\n float span = abs(uDrift) * 1.35 + abs(uRise) + uWander;\n#endif\n if (uSwirl != 0.0) {\n vec3 nrm = cross(uRight, uUp);\n vec3 rel = p - uCenter;\n#ifdef POINTER_FX\n span += abs(uSwirl) * TAU * length(rel);\n#endif\n float rx = dot(rel, uRight), ry = dot(rel, uUp), rz = dot(rel, nrm);\n float a = age * uSwirl * TAU;\n float ca = cos(a), sa = sin(a);\n p = uCenter + uRight * (rx * ca - ry * sa) + uUp * (rx * sa + ry * ca) + nrm * rz;\n }\n if (uWander != 0.0) {\n vec2 wan = vec2(simplexNoise(vec2(aSeed * 17.0, age * 3.0)),\n simplexNoise(vec2(age * 3.0, aSeed * 23.0)));\n p += (uRight * wan.x + uUp * wan.y) * uWander;\n }\n\n#ifdef POINTER_FX\n // How attached to its birth patch this mote still is: 1 while it sits on the surface, 0 once it\n // has travelled a full life's worth away. Measured from the DISTANCE it actually moved rather than\n // from age, because dust with no drift / rise / swirl / wander never leaves the surface at all —\n // an age fade would quietly stop that dust from following the ribbon halfway through its life.\n float attach = span > 1.0e-4 ? 1.0 - clamp(length(p - origin) / span, 0.0, 1.0) : 1.0;\n p += dispAxis * (weld.disp * attach);\n // SHOVE: the exact complement. The same field sampled at the mote's OWN screen position, so the\n // cursor also pushes dust that has already left the surface — and a click ripple visibly blows\n // through the cloud instead of stopping dead at the ribbon. Uniform branch (warp-coherent), so\n // uPartShove 0 costs nothing.\n if (uPartShove != 0.0) {\n vec4 pClip = projectionMatrix * viewMatrix * vec4(p, 1.0);\n PointerHit shove = pointerField(pClip.xy / max(pClip.w, 1.0e-6), pMvp,\n ws.rotA, ws.rotB, ws.rotC, ws.pos, ts, loopOff);\n p += dispAxis * (shove.disp * (1.0 - attach) * uPartShove);\n }\n#endif\n\n float tw = 0.5 + 0.5 * sin((age * 9.0 + aSeed) * TAU); // loop-safe flicker (rides age)\n vAlpha = fade * mix(1.0, tw, clamp(uTwinkle, 0.0, 1.0));\n vColor = mix(uColor, uColor2, aRnd.w); // two-tone dust: per-particle blend of the two colours\n vDir = normalize(vec2(dot(outward, uRight), dot(outward, uUp)) + vec2(1e-4)); // outward, in screen space\n gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);\n // Orthographic camera → point size is constant in device pixels (no perspective depth divide).\n float jitter = 1.0 + uSizeJitter * (aSeed - 0.5) * 2.0;\n gl_PointSize = max(uSize * uPixelRatio * jitter * fade, 0.0);\n}\n`;\n\nexport const particleFragmentShader = /* glsl */ `\nprecision highp float;\nuniform float uShape; // 0 glitter · 1 soft · 2 ring · 3 star · 4 streak\nvarying float vAlpha;\nvarying vec3 vColor;\nvarying vec2 vDir;\n// User artwork (shape \"sprite\"), behind a define so a field without one compiles the exact same\n// program — and so the sampler only exists once a texture is actually bound to it. ONE texture is\n// shared by every particle in the field; see ParticleField.loadSprite for the rasterization.\n#ifdef PARTICLE_SPRITE\nuniform sampler2D uSprite;\n#endif\nvoid main(){\n#ifdef PARTICLE_SPRITE\n // gl_PointCoord's origin is the sprite's TOP-left with y running DOWN, so it has to be flipped or\n // every sprite draws upside down. The procedural shapes below never needed this — they are all\n // symmetric about y, which is exactly why the bug would have gone unnoticed.\n vec4 tex = texture2D(uSprite, vec2(gl_PointCoord.x, 1.0 - gl_PointCoord.y));\n float a = tex.a * vAlpha;\n if (a <= 0.0) discard;\n // Tinted by the dust colour so color / color2 keep working: white artwork takes the tint\n // exactly, coloured artwork multiplies it.\n gl_FragColor = vec4(vColor * tex.rgb, a);\n#else\n vec2 pc = gl_PointCoord - 0.5;\n float d = length(pc);\n int s = int(uShape + 0.5);\n float a;\n if (s == 1) { // soft: a diffuse gaussian blob (motes / pollen)\n a = exp(-d * d * 7.0);\n } else if (s == 2) { // ring: a hollow band (bubbles)\n a = smoothstep(0.09, 0.0, abs(d - 0.34));\n } else if (s == 3) { // star: a 4-point sparkle\n float ang = atan(pc.y, pc.x);\n float spike = pow(abs(cos(ang * 2.0)), 6.0);\n a = smoothstep(1.0, 0.0, d / (0.14 + 0.5 * spike));\n } else if (s == 4) { // streak: an elongated comet along the motion direction\n float along = dot(pc, vDir);\n float perp = dot(pc, vec2(-vDir.y, vDir.x));\n a = smoothstep(0.5, 0.0, length(vec2(along * 0.42, perp * 2.2)));\n } else { // glitter (0): the soft round additive disc\n a = smoothstep(0.5, 0.0, d);\n }\n a *= vAlpha;\n if (a <= 0.0) discard;\n gl_FragColor = vec4(vColor, a); // AdditiveBlending (src = SrcAlpha) → adds vColor·a\n#endif\n}\n`;\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,YAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC7B,MAAM,gBAA2B;;;;;;;;;;;;;;;;;;;;;;;;AA2BjC,MAAM,WAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2F5B,MAAM,iBAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCAiDiB,IAAA,CAAA,QAAQ,CAAC,EAAE;;YAElC,IAAA,CAAA,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCAoCY,IAAA,CAAA,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;AAsB9D,MAAM,oBAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGrC,MAAa,eAA0B;EACrC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoCV,kBAAkB;;;;EAIlB,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DjB,MAAa,iBAA4B;;;;;;;EAOvC,UAAU;;EAEV,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+Cd,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgKX,MAAa,qBAAgC;;;;;EAK3C,UAAU;;EAEV,cAAc;;;;;;;;;;;;;;;;;;;;;EAqBd,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CX,MAAa,mBAA8B;;;;;;;AAQ3C,MAAa,qBAAgC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD7C,MAAa,uBAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqD/C,MAAa,2BAAsC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCnD,MAAa,yBAAoC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCjD,MAAa,wBAAmC;;;;;;;;;;;;;;;;;;AAoBhD,MAAa,6BAAwC;;;;;;;;;;;;;;;AAiBrD,MAAa,6BAAwC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CrD,MAAa,uBAAkC;;;;;;;;;;;;EAY7C,UAAU;;;;;;;;;;;;EAYV,eAAe;;;;;;EAMf,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iDA+B6C,IAAA,CAAA,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+E5E,MAAa,yBAAoC"}