Skip to content

GLSL and Shadertoy shader skills for Claude Code, Codex, Cursor, Copilot and Gemini CLI. 186 functions, SDF raymarching, procedural terrain, water, clouds and generative art, with a bundler, checker and 11 examples.

Extend the library: simplex, 3D derivative noise and curl, ocean template

Gökay50260cc305e3
diff --git a/CREDITS.md b/CREDITS.md
index 6834157..3c89c03 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -27,3 +27,9 @@ default to CC BY-NC-SA 3.0, which is incompatible with MIT.
| Beer-Powder cloud lighting, dual-lobe phase | Andrew Schneider, Horizon Zero Dawn clouds (SIGGRAPH 2015) | math |
| Sun limb darkening | Neckel 1996 | constants are facts |
| Cornette-Shanks phase function | Cornette and Shanks 1992 | math |
+| Simplex noise and its analytic gradient | Stefan Gustavson, "Simplex noise demystified" (2005); Gustavson and McEwan, "Tiling simplex noise and flow noise in two and three dimensions", JCGT 11(1), 2022 | papers; math reimplemented, the psrdnoise reference code is not used |
+| Flow noise (rotating gradients) | Perlin and Neyret, "Flow Noise", SIGGRAPH 2001 technical sketch | math |
+| Turbulence | Ken Perlin, "An Image Synthesizer", SIGGRAPH 1985 | math |
+| Sum-of-sines water with sharpened crests, deep-water dispersion | Mark Finch, "Effective Water Simulation from Physical Models", GPU Gems (2004), chapter 1 | math |
+| Filtering vanished normal detail into roughness | Toksvig, "Mipmapping Normal Maps" (2005); Olano and Baker, "LEAN Mapping" (I3D 2010) | math |
+| Four-arc (Moss) egg | classical compass construction | geometry |
diff --git a/README.md b/README.md
index 6c45f6f..5fbac05 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
A skill that teaches coding agents to write procedural GLSL shaders that compile on the first try and look
intentional. It works with Claude Code, Codex, Cursor, Copilot, Gemini and others. It pairs a shader-craft
-workflow with a **verified GLSL building-block library**: 169 functions across 18 modules, each one compiled in
+workflow with a **verified GLSL building-block library**: 179 functions across 18 modules, each one compiled in
WebGL2 and numerically tested on the GPU. A bundler inlines exactly the functions a shader uses, so the result
pastes straight into Shadertoy.
@@ -10,8 +10,8 @@ pastes straight into Shadertoy.
|---|---|---|
| [![Studio still life](gallery/raymarch-sdf.png)](gallery/raymarch-sdf.glsl) | [![Eroded mountains](gallery/terrain.png)](gallery/terrain.glsl) | [![Cumulus clouds](gallery/volumetric-clouds.png)](gallery/volumetric-clouds.glsl) |
| SDF still life: smooth blends with blended materials, PBR, soft shadows, AO, AgX | Eroded terrain under a physically based sky with aerial perspective | Volumetric cumulus: energy-conserving integration, Beer-Powder, dual-lobe phase |
-| [![Dusk poster](gallery/sdf-2d-poster.png)](gallery/sdf-2d-poster.glsl) | [![Pattern swatches](gallery/pattern-swatches.png)](gallery/pattern-swatches.glsl) | |
-| 2D distance-field poster: Oklab gradients, polar leaves, Bézier trunks | Texture-free materials: warped marble, Voronoi cracks, hex tiles, Truchet, filtered checker | |
+| [![Dusk poster](gallery/sdf-2d-poster.png)](gallery/sdf-2d-poster.glsl) | [![Pattern swatches](gallery/pattern-swatches.png)](gallery/pattern-swatches.glsl) | [![Open ocean](gallery/ocean.png)](gallery/ocean.glsl) |
+| 2D distance-field poster: Oklab gradients, polar leaves, Bézier trunks | Texture-free materials: warped marble, Voronoi cracks, hex tiles, Truchet, filtered checker | Ocean: dispersive waves with analytic curvature foam, Fresnel sky, glitter path widening with distance |
Each image links to its paste-ready shader. The sources are in [`skills/shader-art-coding/templates/`](skills/shader-art-coding/templates/).
@@ -111,8 +111,8 @@ The full catalog with signatures, exactness and uses is
|---|---|---|
| Lint + drift | `glsl_tools.py check` | docs and tags on every function, module order, no WebGL1 or sine-hash patterns, reference snippets identical to the library |
| glslang compile | CI (`checks.yml`) | every library module, reference snippet and template compiles as GLSL ES 3.00 |
-| WebGL2 compile | `tests/` harness | all 146 units compile under ANGLE, which also enforces WebGL-only rules |
-| GPU property tests | `tests/properties.py` | 68 tests × 16,384 samples: Lipschitz, exactness, signs, brute-force curve distance, derivatives, divergence, ranges, round trips |
+| WebGL2 compile | `tests/` harness | all 147 units compile under ANGLE, which also enforces WebGL-only rules |
+| GPU property tests | `tests/properties.py` | 84 tests × 16,384 samples: Lipschitz, exactness, signs, brute-force curve distance, derivatives, divergence, ranges, round trips |
| Renders | harness + gallery | every template renders with no NaNs and no black frames; images saved to `gallery/` |
Run it locally: `python3 tests/build_harness.py && python3 tests/serve.py`, then open
diff --git a/gallery/ocean.glsl b/gallery/ocean.glsl
new file mode 100644
index 0000000..786c7f1
--- /dev/null
+++ b/gallery/ocean.glsl
@@ -0,0 +1,660 @@
+// Open ocean at golden hour under a physically based sky.
+// Shows: a sum of dispersive exp-sine waves with analytic slope and curvature (normals and foam with no extra samples),
+// a heightfield tracer clipped to the wave slab, distance filtering that hands the slope of vanished waves to GGX
+// roughness (the glitter path widens with distance), simplex flow-noise ripples, Fresnel sky reflection, a sun glint,
+// light glowing through thin crests, curvature foam broken up by billow noise, aerial perspective, AgX.
+// Units are meters; the atmosphere functions take kilometers.
+// @render time=12.5
+
+#define DEBUG_MODE 0 // 0 final | 1 height | 2 normals | 3 foam mask | 4 trace steps | 5 fresnel | 6 light terms
+
+// Library code below is bundled from shader-skills (MIT): https://github.com/gokayfem/shader-skills
+// ---- shader-skills library: common ----
+const float PI = 3.14159265358979;
+const float TAU = 6.28318530717959;
+// Squared length.
+float dot2(vec2 v) { return dot(v, v); }
+float dot2(vec3 v) { return dot(v, v); }
+// 2D rotation matrix. `rot2(a) * v` rotates v counter-clockwise by a radians. (cos, sin) is renormalized because GLSL ES leaves trig precision undefined: on SwiftShader and some mobile GPUs a raw cos/sin pair is far enough from unit length that rotations stop preserving distances.
+mat2 rot2(float a) {
+ vec2 cs = normalize(vec2(cos(a), sin(a)));
+ return mat2(cs.x, cs.y, -cs.y, cs.x);
+}
+
+// ---- shader-skills library: hash ----
+// PCG-style 1D integer hash.
+uint pcgHash(uint v) {
+ uint state = v * 747796405u + 2891336453u;
+ uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
+ return (word >> 22u) ^ word;
+}
+// 3D integer hash, three decorrelated outputs.
+uvec3 pcg3d(uvec3 v) {
+ v = v * 1664525u + 1013904223u;
+ v.x += v.y * v.z;
+ v.y += v.z * v.x;
+ v.z += v.x * v.y;
+ v ^= v >> 16u;
+ v.x += v.y * v.z;
+ v.y += v.z * v.x;
+ v.z += v.x * v.y;
+ return v;
+}
+// Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.
+float uintToUnit(uint h) { return float(h >> 8u) * (1.0 / 16777216.0); }
+vec2 uintToUnit(uvec2 h) { return vec2(h >> 8u) * (1.0 / 16777216.0); }
+vec3 uintToUnit(uvec3 h) { return vec3(h >> 8u) * (1.0 / 16777216.0); }
+vec4 uintToUnit(uvec4 h) { return vec4(h >> 8u) * (1.0 / 16777216.0); }
+// Random float in [0,1) for an integer-valued 2D input.
+float hash12(vec2 p) {
+ uvec2 q = uvec2(ivec2(floor(p)));
+ return uintToUnit(pcgHash(q.x + pcgHash(q.y)));
+}
+// Random vec2 in [0,1)^2 for an integer-valued 2D input.
+vec2 hash22(vec2 p) {
+ ivec2 q = ivec2(floor(p));
+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x2545u))).xy;
+}
+// Random vec3 in [0,1)^3 for an integer-valued 3D input.
+vec3 hash33(vec3 p) { return uintToUnit(pcg3d(uvec3(ivec3(floor(p))))); }
+// Random vec3 in [0,1)^3 for an integer-valued 2D input.
+vec3 hash32(vec2 p) {
+ ivec2 q = ivec2(floor(p));
+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x9E37u)));
+}
+
+// ---- shader-skills library: noise ----
+// Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise.
+vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
+vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
+// Derivative of quinticFade: 30 t^2 (t - 1)^2.
+vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
+vec3 quinticFadeDeriv(vec3 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
+// Unit gradient for a 2D lattice point.
+vec2 latticeGradient(vec2 cell) {
+ float a = TAU * hash12(cell);
+ return vec2(cos(a), sin(a));
+}
+// 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm.
+vec3 gradientNoiseD(vec2 p) {
+ vec2 i = floor(p), f = fract(p);
+ vec2 u = quinticFade(f), du = quinticFadeDeriv(f);
+ vec2 ga = latticeGradient(i);
+ vec2 gb = latticeGradient(i + vec2(1.0, 0.0));
+ vec2 gc = latticeGradient(i + vec2(0.0, 1.0));
+ vec2 gd = latticeGradient(i + vec2(1.0, 1.0));
+ float va = dot(ga, f);
+ float vb = dot(gb, f - vec2(1.0, 0.0));
+ float vc = dot(gc, f - vec2(0.0, 1.0));
+ float vd = dot(gd, f - vec2(1.0, 1.0));
+ float k = va - vb - vc + vd;
+ float value = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;
+ vec2 deriv = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)
+ + du * (vec2(vb - va, vc - va) + u.yx * k);
+ return vec3(value, deriv);
+}
+// 2D gradient noise.
+float gradientNoise(vec2 p) { return gradientNoiseD(p).x; }
+// 2D simplex noise with analytic gradient. Returns vec3(value, d/dx, d/dy). Sums three radial kernels (0.5 - r^2)^4 on a triangular lattice instead of blending four square-cell corners, so it has fewer axis-aligned artifacts than gradientNoise. rotation (radians) spins every lattice gradient: animating it gives flow noise that churns in place instead of sliding (Perlin and Neyret 2001). Scaled so |value| <= 1 exactly.
+vec3 simplexNoiseD(vec2 p, float rotation) {
+ const float SKEW = 0.36602540378; // (sqrt(3) - 1) / 2: square lattice -> triangle lattice
+ const float UNSKEW = 0.21132486541; // (3 - sqrt(3)) / 6
+ vec2 cell = floor(p + (p.x + p.y) * SKEW);
+ vec2 d0 = p - cell + (cell.x + cell.y) * UNSKEW;
+ vec2 o = (d0.x > d0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); // which of the cell's two triangles holds p
+ vec2 corners[3] = vec2[3](cell, cell + o, cell + 1.0);
+ vec2 offsets[3] = vec2[3](d0, d0 - o + UNSKEW, d0 - 1.0 + 2.0 * UNSKEW);
+ mat2 spin = rot2(rotation);
+ vec3 sum = vec3(0.0);
+ for (int k = 0; k < 3; k++) {
+ vec2 d = offsets[k];
+ float t = max(0.5 - dot(d, d), 0.0);
+ vec2 g = spin * latticeGradient(corners[k]);
+ float gd = dot(g, d);
+ float t3 = t * t * t;
+ // value t^4 (g.d); gradient t^4 g - 8 t^3 (g.d) d
+ sum += vec3(t3 * t * gd, t3 * t * g - 8.0 * t3 * gd * d);
+ }
+ return 99.2 * sum; // 1 / max over the simplex of sum t^4 |d|
+}
+vec3 simplexNoiseD(vec2 p) { return simplexNoiseD(p, 0.0); }
+// Dot product of a hashed 3D gradient with the offset to its lattice corner.
+float latticeGradDot(vec3 cell, vec3 corner, vec3 f) {
+ vec3 g = hash33(cell + corner) * 2.0 - 1.0;
+ return dot(g, f - corner);
+}
+// 3D gradient noise.
+float gradientNoise(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = quinticFade(f);
+ return mix(mix(mix(latticeGradDot(i, vec3(0, 0, 0), f), latticeGradDot(i, vec3(1, 0, 0), f), u.x),
+ mix(latticeGradDot(i, vec3(0, 1, 0), f), latticeGradDot(i, vec3(1, 1, 0), f), u.x), u.y),
+ mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),
+ mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);
+}
+// 3D gradient noise with analytic derivatives. Returns vec4(value, d/dx, d/dy, d/dz); value equals gradientNoise(p). The trilinear blend is expanded as a polynomial in the fade weights, so the gradient is the same blend of the corner gradients plus the chain-rule term of the fade.
+vec4 gradientNoiseD(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = quinticFade(f), du = quinticFadeDeriv(f);
+ vec3 g000 = hash33(i) * 2.0 - 1.0;
+ vec3 g100 = hash33(i + vec3(1, 0, 0)) * 2.0 - 1.0;
+ vec3 g010 = hash33(i + vec3(0, 1, 0)) * 2.0 - 1.0;
+ vec3 g110 = hash33(i + vec3(1, 1, 0)) * 2.0 - 1.0;
+ vec3 g001 = hash33(i + vec3(0, 0, 1)) * 2.0 - 1.0;
+ vec3 g101 = hash33(i + vec3(1, 0, 1)) * 2.0 - 1.0;
+ vec3 g011 = hash33(i + vec3(0, 1, 1)) * 2.0 - 1.0;
+ vec3 g111 = hash33(i + vec3(1, 1, 1)) * 2.0 - 1.0;
+ float v000 = dot(g000, f);
+ float v100 = dot(g100, f - vec3(1, 0, 0));
+ float v010 = dot(g010, f - vec3(0, 1, 0));
+ float v110 = dot(g110, f - vec3(1, 1, 0));
+ float v001 = dot(g001, f - vec3(0, 0, 1));
+ float v101 = dot(g101, f - vec3(1, 0, 1));
+ float v011 = dot(g011, f - vec3(0, 1, 1));
+ float v111 = dot(g111, f - vec3(1, 1, 1));
+ // value = v000 + kx u.x + ky u.y + kz u.z + kxy u.x u.y + kyz u.y u.z + kzx u.z u.x + kxyz u.x u.y u.z
+ float kx = v100 - v000, ky = v010 - v000, kz = v001 - v000;
+ float kxy = v000 - v100 - v010 + v110;
+ float kyz = v000 - v010 - v001 + v011;
+ float kzx = v000 - v100 - v001 + v101;
+ float kxyz = -v000 + v100 + v010 - v110 + v001 - v101 - v011 + v111;
+ float value = v000 + kx * u.x + ky * u.y + kz * u.z
+ + kxy * u.x * u.y + kyz * u.y * u.z + kzx * u.z * u.x + kxyz * u.x * u.y * u.z;
+ vec3 grad = g000 + (g100 - g000) * u.x + (g010 - g000) * u.y + (g001 - g000) * u.z
+ + (g000 - g100 - g010 + g110) * u.x * u.y
+ + (g000 - g010 - g001 + g011) * u.y * u.z
+ + (g000 - g100 - g001 + g101) * u.z * u.x
+ + (-g000 + g100 + g010 - g110 + g001 - g101 - g011 + g111) * u.x * u.y * u.z
+ + du * vec3(kx + kxy * u.y + kzx * u.z + kxyz * u.y * u.z,
+ ky + kxy * u.x + kyz * u.z + kxyz * u.x * u.z,
+ kz + kyz * u.y + kzx * u.x + kxyz * u.x * u.y);
+ return vec4(value, grad);
+}
+const int FBM_MAX_OCTAVES = 12;
+// Billowy multifractal: |noise| per octave makes puffy rounded lobes split by sharp creases (the inverse of ridgedFbm). Each octave is weighted by the previous one, so detail gathers on the lobes while the creases stay clean.
+float billowFbm(vec2 p, int octaves) {
+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);
+ float sum = 0.0, amp = 0.5, weight = 1.0, norm = 0.0;
+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {
+ if (i >= octaves) break;
+ float n = abs(gradientNoise(p) * 1.4);
+ n = n * (2.0 - n); // round the lobe tops, keep the creases sharp
+ sum += amp * n * weight;
+ norm += amp;
+ weight = clamp(n * 1.5, 0.0, 1.0);
+ amp *= 0.5;
+ p = 2.01 * (octaveRotation * p) + vec2(17.13, -3.71);
+ }
+ return sum / norm;
+}
+float billowFbm(vec3 p, int octaves) {
+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,
+ -0.80, 0.36, -0.48,
+ -0.60, -0.48, 0.64);
+ float sum = 0.0, amp = 0.5, weight = 1.0, norm = 0.0;
+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {
+ if (i >= octaves) break;
+ float n = min(abs(gradientNoise(p)) * 1.4, 1.0);
+ n = n * (2.0 - n);
+ sum += amp * n * weight;
+ norm += amp;
+ weight = clamp(n * 1.5, 0.0, 1.0);
+ amp *= 0.5;
+ p = 2.01 * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);
+ }
+ return sum / norm;
+}
+// Exact distance to Voronoi cell borders, found in two passes: nearest point, then nearest bisector. Returns vec3(borderDistance, vectorToNearestPoint). Unlike F2-F1, the border distance is a true distance, so lines have constant width.
+vec3 voronoiBorder(vec2 p, float jitter) {
+ vec2 ip = floor(p), fp = fract(p);
+ vec2 mg = vec2(0.0), mr = vec2(0.0);
+ float md = 8.0;
+ for (int j = -1; j <= 1; j++)
+ for (int i = -1; i <= 1; i++) {
+ vec2 g = vec2(float(i), float(j));
+ vec2 r = g + jitter * hash22(ip + g) - fp;
+ float d = dot(r, r);
+ if (d < md) { md = d; mr = r; mg = g; }
+ }
+ md = 8.0;
+ for (int j = -2; j <= 2; j++)
+ for (int i = -2; i <= 2; i++) {
+ vec2 g = mg + vec2(float(i), float(j));
+ vec2 r = g + jitter * hash22(ip + g) - fp;
+ if (dot2(mr - r) > 1e-5) {
+ md = min(md, dot(0.5 * (mr + r), normalize(r - mr)));
+ }
+ }
+ return vec3(md, mr);
+}
+
+// ---- shader-skills library: raymarch ----
+#define ZERO (min(iFrame, 0))
+
+// ---- shader-skills library: intersect ----
+// Ray vs sphere centered at c with radius r. Returns vec2(tNear, tFar), or vec2(-1) on a miss. Uses the precision-friendly form that measures from the closest point on the ray.
+vec2 iSphere(vec3 ro, vec3 rd, vec3 c, float r) {
+ vec3 oc = ro - c;
+ float b = dot(oc, rd);
+ vec3 qc = oc - b * rd;
+ float h = r * r - dot(qc, qc);
+ if (h < 0.0) return vec2(-1.0);
+ h = sqrt(h);
+ return vec2(-b - h, -b + h);
+}
+
+// ---- shader-skills library: camera ----
+// Camera-to-world matrix looking from ro toward ta, with roll in radians. Columns are (right, up, forward).
+mat3 cameraMatrix(vec3 ro, vec3 ta, float roll) {
+ vec3 w = normalize(ta - ro);
+ vec3 up = vec3(sin(roll), cos(roll), 0.0);
+ vec3 u = normalize(cross(w, up));
+ vec3 v = cross(u, w);
+ return mat3(u, v, w);
+}
+// Primary ray direction for screen point uv. focal is about 1.5-2.5 for natural framing (see fovToFocal).
+vec3 cameraRay(mat3 cam, vec2 uv, float focal) {
+ return normalize(cam * vec3(uv, focal));
+}
+
+// ---- shader-skills library: shading ----
+// Schlick Fresnel. u is VoH for lights and NoV for environment reflections and rims. f0 = 0.04 for dielectrics (plastic, skin, stone, water ~0.02); for metals f0 = base color.
+vec3 fresnelSchlick(float u, vec3 f0) {
+ float m = clamp(1.0 - u, 0.0, 1.0);
+ float m2 = m * m;
+ return f0 + (1.0 - f0) * (m2 * m2 * m);
+}
+// GGX / Trowbridge-Reitz normal distribution. alpha = roughness^2.
+float distributionGGX(float NoH, float alpha) {
+ float a2 = alpha * alpha;
+ float d = NoH * NoH * (a2 - 1.0) + 1.0;
+ return a2 / (PI * d * d);
+}
+// Height-correlated Smith visibility. Already contains the 1 / (4 NoL NoV) term.
+float visibilitySmithGGX(float NoV, float NoL, float alpha) {
+ float a2 = alpha * alpha;
+ float gv = NoL * sqrt(NoV * NoV * (1.0 - a2) + a2);
+ float gl = NoV * sqrt(NoL * NoL * (1.0 - a2) + a2);
+ return 0.5 / max(gv + gl, 1e-6);
+}
+// Microfacet specular for one light: pi * D * V * F * NoL (artist units). roughness is perceptual, in [0,1].
+vec3 specularGGX(vec3 n, vec3 v, vec3 l, float roughness, vec3 f0) {
+ vec3 h = normalize(v + l);
+ float NoL = clamp(dot(n, l), 0.0, 1.0);
+ float NoV = max(dot(n, v), 1e-4);
+ float NoH = clamp(dot(n, h), 0.0, 1.0);
+ float VoH = clamp(dot(v, h), 0.0, 1.0);
+ float alpha = max(roughness, 0.045);
+ alpha *= alpha;
+ return PI * distributionGGX(NoH, alpha) * visibilitySmithGGX(NoV, NoL, alpha) * fresnelSchlick(VoH, f0) * NoL;
+}
+
+// ---- shader-skills library: color ----
+// Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping. pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2).
+vec3 linearToSrgb(vec3 c) {
+ c = max(c, 0.0);
+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
+}
+// Relative luminance of linear Rec.709 / sRGB color.
+float luminance(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
+
+// ---- shader-skills library: tonemap ----
+// AgX with the "punchy" look (more contrast and saturation) for stylized art.
+vec3 tonemapAgXPunchy(vec3 c) {
+ const mat3 inset = mat3(0.842479062253094, 0.0423282422610123, 0.0423756549057051,
+ 0.0784335999999992, 0.878468636469772, 0.0784336,
+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104);
+ const mat3 outset = mat3(1.19687900512017, -0.0528968517574562, -0.0529716355144438,
+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,
+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116);
+ const float minEv = -12.47393, maxEv = 4.026069;
+ c = inset * max(c, 0.0);
+ c = clamp((log2(max(c, 1e-10)) - minEv) / (maxEv - minEv), 0.0, 1.0);
+ vec3 x2 = c * c, x4 = x2 * x2;
+ c = 15.5 * x4 * x2 - 40.14 * x4 * c + 31.96 * x4 - 6.868 * x2 * c + 0.4298 * x2 + 0.1191 * c - 0.00232;
+ c = pow(max(c, 0.0), vec3(1.35));
+ float luma = dot(c, vec3(0.2126, 0.7152, 0.0722));
+ c = luma + 1.4 * (c - luma);
+ c = outset * c;
+ return pow(max(c, 0.0), vec3(2.2));
+}
+
+// ---- shader-skills library: volume ----
+// Rayleigh phase function.
+float phaseRayleigh(float mu) { return 3.0 / (16.0 * PI) * (1.0 + mu * mu); }
+// Cornette-Shanks phase (a better-normalized Mie approximation). g = 0.8 for atmospheric haze.
+float phaseCornetteShanks(float mu, float g) {
+ float g2 = g * g;
+ return 3.0 / (8.0 * PI) * (1.0 - g2) * (1.0 + mu * mu)
+ / ((2.0 + g2) * pow(max(1.0 + g2 - 2.0 * g * mu, 1e-6), 1.5));
+}
+// One energy-conserving step of volume integration. sigmaT is extinction per unit length (RGB for tinted media), inScatter is in-scattered radiance at this point (including sigmaS, phase and light), ds is step length. Accumulates into radiance and transmittance. Stable for dense media, unlike radiance += T * S * ds.
+void volumeStep(inout vec3 radiance, inout vec3 transmittance, vec3 sigmaT, vec3 inScatter, float ds) {
+ vec3 stepT = exp(-sigmaT * ds);
+ vec3 integral = (inScatter - inScatter * stepT) / max(sigmaT, vec3(1e-7));
+ radiance += transmittance * integral;
+ transmittance *= stepT;
+}
+
+// ---- shader-skills library: atmosphere ----
+// Sun disk with antialiased edge and limb darkening (Neckel 1996). angularRadius in radians (the real sun is 0.00476; art often uses 3-10x). pixelAngle is the angular size of a pixel (about 2 / (iResolution.y * focal)). Returns a 0..1 shape tinted by limb darkening; multiply by a bright sun color (10-50).
+vec3 sunDisk(vec3 rd, vec3 sunDir, float angularRadius, float pixelAngle) {
+ float ang = acos(clamp(dot(rd, sunDir), -1.0, 1.0));
+ float edge = 1.0 - smoothstep(angularRadius - pixelAngle, angularRadius + pixelAngle, ang);
+ float r = clamp(ang / angularRadius, 0.0, 1.0);
+ float muLimb = sqrt(max(1.0 - r * r, 0.0));
+ vec3 limb = pow(vec3(muLimb), vec3(0.397, 0.503, 0.652));
+ return edge * limb;
+}
+const float ATMOSPHERE_GROUND_KM = 6360.0;
+const float ATMOSPHERE_TOP_KM = 6460.0;
+// Densities (rayleigh, mie, ozone) at altitude h km above the ground.
+vec3 atmosphereDensity(float h) {
+ return vec3(exp(-h / 8.0), exp(-h / 1.2), max(0.0, 1.0 - abs(h - 25.0) / 15.0));
+}
+// Extinction per km for the given densities.
+vec3 atmosphereExtinction(vec3 density) {
+ const vec3 rayleigh = vec3(5.802, 13.558, 33.1) * 1e-3;
+ const float mie = (3.996 + 4.40) * 1e-3;
+ const vec3 ozone = vec3(0.650, 1.881, 0.085) * 1e-3;
+ return rayleigh * density.x + mie * density.y + ozone * density.z;
+}
+// Physically based sky radiance along rd for a viewer viewHeightKm above the ground, with single scattering (16 view steps x 8 light steps). sunIntensity about 20. Sunsets come out somewhat dark because multiple scattering is ignored; add a small ambient term if needed.
+vec3 atmosphereSky(vec3 rd, vec3 sunDir, float viewHeightKm, float sunIntensity) {
+ const vec3 rayleighScatter = vec3(5.802, 13.558, 33.1) * 1e-3;
+ const float mieScatter = 3.996e-3;
+ vec3 ro = vec3(0.0, ATMOSPHERE_GROUND_KM + max(viewHeightKm, 0.001), 0.0);
+ vec2 top = iSphere(ro, rd, vec3(0.0), ATMOSPHERE_TOP_KM);
+ if (top.y <= 0.0) return vec3(0.0);
+ vec2 ground = iSphere(ro, rd, vec3(0.0), ATMOSPHERE_GROUND_KM);
+ float tStart = max(top.x, 0.0);
+ float tEnd = (ground.x > 0.0) ? ground.x : top.y;
+ float mu = dot(rd, sunDir);
+ float pR = phaseRayleigh(mu);
+ float pM = phaseCornetteShanks(mu, 0.8);
+ const int VIEW_STEPS = 16;
+ const int LIGHT_STEPS = 8;
+ float dt = (tEnd - tStart) / float(VIEW_STEPS);
+ vec3 radiance = vec3(0.0), transmittance = vec3(1.0);
+ for (int i = 0; i < VIEW_STEPS; i++) {
+ vec3 p = ro + rd * (tStart + (float(i) + 0.5) * dt);
+ vec3 dens = atmosphereDensity(length(p) - ATMOSPHERE_GROUND_KM);
+ vec3 sunT = vec3(0.0);
+ if (iSphere(p, sunDir, vec3(0.0), ATMOSPHERE_GROUND_KM).x < 0.0) {
+ float tl = iSphere(p, sunDir, vec3(0.0), ATMOSPHERE_TOP_KM).y;
+ float dl = tl / float(LIGHT_STEPS);
+ vec3 depth = vec3(0.0);
+ for (int j = 0; j < LIGHT_STEPS; j++) {
+ vec3 q = p + sunDir * ((float(j) + 0.5) * dl);
+ depth += atmosphereExtinction(atmosphereDensity(length(q) - ATMOSPHERE_GROUND_KM)) * dl;
+ }
+ sunT = exp(-depth);
+ }
+ vec3 scatter = sunT * (rayleighScatter * dens.x * pR + mieScatter * dens.y * pM) * sunIntensity;
+ volumeStep(radiance, transmittance, atmosphereExtinction(dens), scatter, dt);
+ }
+ return radiance;
+}
+
+// ---- shader-skills library: post ----
+// Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor.
+vec3 ditherTPDF(vec2 fragCoord, int frame) {
+ vec2 r = hash22(vec2(floor(fragCoord) + 7919.0 * float(frame % 1024)));
+ return vec3((r.x + r.y - 1.0) / 255.0);
+}
+
+// ---- shader-skills library: debug ----
+// Normal as RGB.
+vec3 debugNormal(vec3 n) { return 0.5 + 0.5 * n; }
+// Heat ramp for a value in [0,1]: black, blue, magenta, orange, yellow, white.
+vec3 debugHeat(float t) {
+ t = clamp(t, 0.0, 1.0);
+ return clamp(vec3(1.5 * t, 1.6 * t * t * t - 0.1, 0.9 * sin(PI * t) + 0.2 * t * t), 0.0, 1.0);
+}
+
+// ---- shader ----
+// ---- art controls ----
+const vec3 SUN_DIR = normalize(vec3(0.2, 0.14, -1.0)); // low sun ahead of the camera, a little to the right
+const float SUN_INTENSITY = 20.0;
+const float WIND_ANGLE = 1.9; // direction the waves travel, radians from +X toward +Z (camera looks down -Z)
+const float SWELL_LENGTH = 34.0; // longest wavelength, meters
+const float SWELL_HEIGHT = 0.8; // amplitude of the longest wave, meters
+const float CHOP = 0.7; // amplitude ratio between successive waves: higher = choppier
+const float CREST_SHARPNESS = 2.4; // 1 rolling swell .. 3 peaky crests
+const float RIPPLE = 0.008; // capillary ripple amplitude, meters
+const float FOAM_AMOUNT = 1.0;
+const vec3 WATER_DEEP = vec3(0.004, 0.02, 0.04); // linear albedo of the deep body
+const vec3 WATER_GLOW = vec3(0.05, 0.26, 0.25); // color of sunlight scattered through thin crests
+const float HAZE = 6.0; // aerial perspective strength (multiplies sea-level air extinction)
+const float CAMERA_HEIGHT = 3.0; // meters above mean sea level
+const float EXPOSURE = 0.9;
+const float FOCAL = 2.0;
+
+const float GRAVITY = 9.81;
+const float WAVELENGTH_RATIO = 0.8; // wavelength ratio between successive waves
+const int TRACE_WAVES = 12; // waves in the traced surface
+const int SHADE_WAVES = 28; // waves in the shading normal (adds fine chop)
+const int FOAM_WAVES = 6; // waves whose crests make foam
+const float TRACE_FAR = 400.0; // beyond this, intersect the mean plane and rely on filtering
+
+// Wave i of the sum: unit direction, wavenumber, amplitude and phase. Wavelengths fall geometrically from the swell;
+// long waves run with the wind, short chop spreads wider around it.
+void wave(int i, out vec2 dir, out float k, out float amp, out float phase) {
+ float fi = float(i);
+ vec3 h = hash32(vec2(fi, 17.0));
+ float a = WIND_ANGLE + mix(0.35, 1.3, min(fi / 12.0, 1.0)) * (2.0 * h.x - 1.0);
+ dir = vec2(cos(a), sin(a));
+ k = TAU / (SWELL_LENGTH * pow(WAVELENGTH_RATIO, fi) * mix(0.85, 1.15, h.y));
+ amp = SWELL_HEIGHT * pow(CHOP, fi);
+ phase = TAU * h.z;
+}
+
+// Deep-water dispersion: a wave of wavenumber k moves at angular frequency sqrt(g k), so long swell outruns chop.
+float wavePhase(vec2 dir, float k, float phase, vec2 xz) {
+ return k * dot(dir, xz) - sqrt(GRAVITY * k) * iTime + phase;
+}
+
+// How much of a wave survives filtering: 1 while its wavelength spans 6+ pixel footprints, 0 below 2.
+// A pixel covers an ellipse on the water: fp.zw = its size across and along the view, fp.xy = the unit view
+// direction projected on the water. At grazing angles it is far longer along the view, which is where waves alias.
+float waveKeep(vec2 dir, float k, vec4 fp) {
+ float footprint = length(vec2(dot(dir, vec2(-fp.y, fp.x)) * fp.z, dot(dir, fp.xy) * fp.w));
+ return smoothstep(2.0, 6.0, TAU / (k * footprint));
+}
+
+// Exp-sine profile: sharp crests, broad troughs. exp(s (sin - 1)) - 0.3 keeps the mean level near 0.
+// Waves too small for the footprint are faded out, so distant geometry does not alias into streaks.
+float oceanHeight(vec2 xz, int count, vec4 fp) {
+ float h = 0.0;
+ for (int i = ZERO; i < SHADE_WAVES; i++) {
+ if (i >= count) break;
+ vec2 dir; float k, amp, phase;
+ wave(i, dir, k, amp, phase);
+ h += waveKeep(dir, k, fp) * amp * (exp(CREST_SHARPNESS * (sin(wavePhase(dir, k, phase, xz)) - 1.0)) - 0.3);
+ }
+ return h;
+}
+
+// Steepest slope one wave of amplitude a and wavenumber k can reach: a k max|s cos(t) e^(s (sin(t) - 1))|.
+float profileMaxSlope() {
+ float s = CREST_SHARPNESS;
+ float sn = (sqrt(1.0 + 4.0 * s * s) - 1.0) / (2.0 * s);
+ return s * sqrt(1.0 - sn * sn) * exp(s * (sn - 1.0));
+}
+
+// Bounds of the traced surface: vec3(lowest height, highest height, steepest slope).
+vec3 oceanBounds() {
+ float ampSum = 0.0, slopeSum = 0.0;
+ for (int i = ZERO; i < TRACE_WAVES; i++) {
+ vec2 dir; float k, amp, phase;
+ wave(i, dir, k, amp, phase);
+ ampSum += amp;
+ slopeSum += amp * k;
+ }
+ return vec3(-0.3 * ampSum, 0.7 * ampSum, slopeSum * profileMaxSlope());
+}
+
+// Ray vs the traced wave surface. The surface lies inside the slab bounds.x <= y <= bounds.y, so clip the ray to it,
+// then step by the height gap over the fastest rate the gap can close (the ray's descent plus the steepest slope times
+// its horizontal speed). The slope bound is relaxed by 0.6 for speed; a secant step refines the crossing.
+// Returns vec2(t, steps); t < 0 when the ray reaches TRACE_FAR first.
+vec2 traceOcean(vec3 ro, vec3 rd, vec3 bounds, vec4 pixelSpread) {
+ if (rd.y >= 0.0) return vec2(-1.0, 0.0);
+ float t = max((ro.y - bounds.y) / -rd.y, 0.0);
+ float tEnd = min((ro.y - bounds.x) / -rd.y, TRACE_FAR);
+ float closing = -rd.y + 0.6 * bounds.z * length(rd.xz);
+ float tPrev = t, gapPrev = 1e10;
+ for (int i = ZERO; i < 200; i++) {
+ vec3 p = ro + rd * t;
+ float gap = p.y - oceanHeight(p.xz, TRACE_WAVES, pixelSpread * vec4(1.0, 1.0, t, t));
+ if (gap < 0.0) return vec2(mix(tPrev, t, gapPrev / (gapPrev - gap)), float(i));
+ if (t >= tEnd) break;
+ tPrev = t;
+ gapPrev = gap;
+ t = min(t + max(gap / closing, 0.004 * t), tEnd);
+ }
+ return vec2(-1.0, 200.0);
+}
+
+// Shading detail at xz: height, slope and Laplacian of all SHADE_WAVES, each wave faded out as its wavelength nears
+// the pixel footprint. Returns vec4(height, dh/dx, dh/dz, laplacian). lostSlope2 collects the slope variance of the
+// faded waves (it becomes roughness); crest is the convexity of the big waves, 1 where all their crests meet (foam).
+vec4 oceanDetail(vec2 xz, vec4 fp, out float lostSlope2, out float crest) {
+ const float slopeRms = 0.3 + 0.06 * CREST_SHARPNESS; // RMS of the profile's slope per unit a k
+ vec4 s = vec4(0.0);
+ lostSlope2 = 0.0;
+ crest = 0.0;
+ float crestMax = 0.0;
+ for (int i = ZERO; i < SHADE_WAVES; i++) {
+ vec2 dir; float k, amp, phase;
+ wave(i, dir, k, amp, phase);
+ float keep = waveKeep(dir, k, fp);
+ float theta = wavePhase(dir, k, phase, xz);
+ float sn = sin(theta), cs = cos(theta);
+ float e = exp(CREST_SHARPNESS * (sn - 1.0));
+ float d1 = CREST_SHARPNESS * cs * e; // dW/dtheta
+ float d2 = CREST_SHARPNESS * (CREST_SHARPNESS * cs * cs - sn) * e; // d2W/dtheta2
+ s += keep * amp * vec4(e - 0.3, k * d1 * dir, k * k * d2);
+ lostSlope2 += (1.0 - keep) * (amp * k * slopeRms) * (amp * k * slopeRms);
+ if (i < FOAM_WAVES) {
+ crest -= keep * amp * k * k * d2;
+ crestMax += amp * k * k * CREST_SHARPNESS; // a crest's curvature: -W'' = s at the top
+ }
+ }
+ crest /= crestMax;
+ return s;
+}
+
+// Transmittance from a point at heightKm toward dir, through the atmosphere (colors the sunlight).
+vec3 sunTransmittance(float heightKm, vec3 dir) {
+ vec3 ro = vec3(0.0, ATMOSPHERE_GROUND_KM + heightKm, 0.0);
+ if (iSphere(ro, dir, vec3(0.0), ATMOSPHERE_GROUND_KM).x > 0.0) return vec3(0.0);
+ float tl = iSphere(ro, dir, vec3(0.0), ATMOSPHERE_TOP_KM).y;
+ vec3 depth = vec3(0.0);
+ for (int i = 0; i < 12; i++) {
+ vec3 q = ro + dir * ((float(i) + 0.5) * tl / 12.0);
+ depth += atmosphereExtinction(atmosphereDensity(length(q) - ATMOSPHERE_GROUND_KM)) * tl / 12.0;
+ }
+ return exp(-depth);
+}
+
+vec3 render(vec2 fragCoord) {
+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
+ float pixelAngle = 2.0 / (iResolution.y * FOCAL);
+ float viewKm = CAMERA_HEIGHT * 0.001;
+
+#if DEBUG_MODE == 1
+ return vec3(0.5 + 0.5 * oceanHeight(uv * 30.0, SHADE_WAVES, vec4(1.0, 0.0, 1e-4, 1e-4)) / SWELL_HEIGHT);
+#endif
+
+ vec3 ro = vec3(0.0, CAMERA_HEIGHT, 0.0);
+ mat3 cam = cameraMatrix(ro, ro + vec3(0.0, -0.06, -1.0), 0.0);
+ vec3 rd = cameraRay(cam, uv, FOCAL);
+
+ vec3 sunColor = SUN_INTENSITY * 0.12 * sunTransmittance(viewKm, SUN_DIR);
+ if (rd.y >= 0.0) {
+ vec3 sky = atmosphereSky(rd, SUN_DIR, viewKm, SUN_INTENSITY);
+ return sky + sunColor * 40.0 * sunDisk(rd, SUN_DIR, 0.012, pixelAngle);
+ }
+
+ // pixel footprint on the water per meter of distance: pixelAngle across the view, stretched by 1/sin(grazing
+ // angle) along it
+ vec4 pixelSpread = vec4(normalize(rd.xz), pixelAngle, pixelAngle / max(-rd.y, 0.01));
+ vec3 bounds = oceanBounds();
+ vec2 hit = traceOcean(ro, rd, bounds, pixelSpread);
+#if DEBUG_MODE == 4
+ return debugHeat(hit.y / 200.0);
+#endif
+ // past TRACE_FAR the waves are below pixel size anyway: use the mean plane and let filtering do the rest
+ float t = (hit.x > 0.0) ? hit.x : ro.y / -rd.y;
+ vec3 p = ro + rd * t;
+
+ vec4 fp = pixelSpread * vec4(1.0, 1.0, t, t);
+ float lostSlope2, crest;
+ vec4 wv = oceanDetail(p.xz, fp, lostSlope2, crest);
+ vec2 slope = wv.yz;
+
+ // capillary ripples: two octaves of simplex flow noise whose gradients spin, so they churn instead of sliding
+ float footprint = sqrt(fp.z * fp.w); // ripples are isotropic: use the ellipse's mean size
+ float keepRipple = smoothstep(2.0, 6.0, 0.8 / footprint);
+ vec3 r1 = simplexNoiseD(p.xz * 1.3 + vec2(0.3, 0.9) * iTime, 1.3 * iTime);
+ vec3 r2 = simplexNoiseD(p.xz * 3.7 - vec2(0.6, 0.2) * iTime, -2.1 * iTime);
+ slope += RIPPLE * keepRipple * (1.3 * r1.yz + 0.5 * 3.7 * r2.yz * smoothstep(2.0, 6.0, 0.3 / footprint));
+ lostSlope2 += RIPPLE * RIPPLE * 4.0 * (1.0 - keepRipple);
+ vec3 n = normalize(vec3(-slope.x, 1.0, -slope.y));
+
+ // foam: the convexity of the big waves' crests sets how much of a billow-noise lace is covered, so patches
+ // grow from crisp filaments on mild crests to solid caps on the sharpest ones
+ float lace = billowFbm(p.xz * vec2(1.2, 2.4) + vec2(0.0, 0.5 * iTime), 6);
+ float coverage = 0.7 * smoothstep(0.08, 0.3, crest); // below 1, so even the sharpest caps stay broken
+ float foam = FOAM_AMOUNT * coverage * smoothstep(1.0 - coverage, 1.15 - coverage, lace);
+ // inside a patch, foam is a network of bubbles: dense along Voronoi borders, thin inside the cells
+ float bubbles = smoothstep(0.22, 0.0, voronoiBorder(p.xz * vec2(2.5, 4.0), 1.0).x);
+ foam *= mix(0.75, mix(0.4, 1.0, bubbles), smoothstep(2.0, 6.0, 0.3 / footprint));
+
+ vec3 v = -rd;
+ float NoV = max(dot(n, v), 1e-3);
+ vec3 F = fresnelSchlick(NoV, vec3(0.02));
+ vec3 refl = reflect(rd, n);
+ refl.y = abs(refl.y); // a reflection into the water would hit the next wave: fold it back to the sky
+ vec3 skyRefl = atmosphereSky(refl, SUN_DIR, viewKm, SUN_INTENSITY);
+ vec3 skyAmbient = atmosphereSky(vec3(0.0, 1.0, 0.0), SUN_DIR, viewKm, SUN_INTENSITY);
+
+ // sun glint: GGX whose roughness absorbs the slope variance of the waves filtered away at this distance
+ float alpha = sqrt(0.02 * 0.02 + 2.0 * lostSlope2);
+ vec3 glint = specularGGX(n, v, SUN_DIR, sqrt(alpha), vec3(0.02)) * sunColor;
+ vec3 reflection = F * skyRefl;
+
+ // body: refracted light scattered back out, plus sunlight glowing through thin crests seen against the sun
+ float backlit = pow(clamp(dot(rd, SUN_DIR), 0.0, 1.0), 4.0);
+ float thin = smoothstep(0.45, 0.9, (wv.x - bounds.x) / (bounds.y - bounds.x)); // crest tops only
+ vec3 body = (1.0 - F) * (WATER_DEEP * (skyAmbient + sunColor * max(dot(n, SUN_DIR), 0.0))
+ + WATER_GLOW * sunColor * backlit * thin);
+
+ // foam is a thin white scatterer: diffuse sun and sky light, plus sunlight shining through it from behind
+ vec3 foamColor = vec3(0.9) * (sunColor * (max(dot(n, SUN_DIR), 0.0) + 0.5 * backlit) + 3.0 * skyAmbient);
+
+#if DEBUG_MODE == 2
+ return debugNormal(n);
+#elif DEBUG_MODE == 3
+ return vec3(foam, clamp(crest, 0.0, 1.0), lace);
+#elif DEBUG_MODE == 5
+ return sqrt(F);
+#elif DEBUG_MODE == 6
+ return vec3(luminance(reflection), luminance(glint) * 0.1, luminance(body) * 10.0);
+#endif
+
+ vec3 col = mix(reflection + glint + body, foamColor, foam);
+ // aerial perspective, with the haze color taken from the sky just above the horizon so the two meet without a seam
+ vec3 fogColor = atmosphereSky(normalize(vec3(rd.x, 0.0, rd.z)), SUN_DIR, viewKm, SUN_INTENSITY);
+ vec3 airT = exp(-t * 0.001 * HAZE * atmosphereExtinction(atmosphereDensity(0.0)));
+ return col * airT + fogColor * (1.0 - airT);
+}
+
+void mainImage(out vec4 fragColor, in vec2 fragCoord) {
+ vec3 col = render(fragCoord);
+#if DEBUG_MODE == 0
+ col = linearToSrgb(tonemapAgXPunchy(col * EXPOSURE)) + ditherTPDF(fragCoord, iFrame);
+#endif
+ fragColor = vec4(col, 1.0);
+}
diff --git a/gallery/ocean.png b/gallery/ocean.png
new file mode 100644
index 0000000..b925037
Binary files /dev/null and b/gallery/ocean.png differ
diff --git a/gallery/pattern-swatches.glsl b/gallery/pattern-swatches.glsl
index 3120b39..7d726db 100644
--- a/gallery/pattern-swatches.glsl
+++ b/gallery/pattern-swatches.glsl
@@ -59,6 +59,7 @@ vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
// Derivative of quinticFade: 30 t^2 (t - 1)^2.
vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
+vec3 quinticFadeDeriv(vec3 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
// Unit gradient for a 2D lattice point.
vec2 latticeGradient(vec2 cell) {
float a = TAU * hash12(cell);
@@ -98,6 +99,44 @@ float gradientNoise(vec3 p) {
mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),
mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);
}
+// 3D gradient noise with analytic derivatives. Returns vec4(value, d/dx, d/dy, d/dz); value equals gradientNoise(p). The trilinear blend is expanded as a polynomial in the fade weights, so the gradient is the same blend of the corner gradients plus the chain-rule term of the fade.
+vec4 gradientNoiseD(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = quinticFade(f), du = quinticFadeDeriv(f);
+ vec3 g000 = hash33(i) * 2.0 - 1.0;
+ vec3 g100 = hash33(i + vec3(1, 0, 0)) * 2.0 - 1.0;
+ vec3 g010 = hash33(i + vec3(0, 1, 0)) * 2.0 - 1.0;
+ vec3 g110 = hash33(i + vec3(1, 1, 0)) * 2.0 - 1.0;
+ vec3 g001 = hash33(i + vec3(0, 0, 1)) * 2.0 - 1.0;
+ vec3 g101 = hash33(i + vec3(1, 0, 1)) * 2.0 - 1.0;
+ vec3 g011 = hash33(i + vec3(0, 1, 1)) * 2.0 - 1.0;
+ vec3 g111 = hash33(i + vec3(1, 1, 1)) * 2.0 - 1.0;
+ float v000 = dot(g000, f);
+ float v100 = dot(g100, f - vec3(1, 0, 0));
+ float v010 = dot(g010, f - vec3(0, 1, 0));
+ float v110 = dot(g110, f - vec3(1, 1, 0));
+ float v001 = dot(g001, f - vec3(0, 0, 1));
+ float v101 = dot(g101, f - vec3(1, 0, 1));
+ float v011 = dot(g011, f - vec3(0, 1, 1));
+ float v111 = dot(g111, f - vec3(1, 1, 1));
+ // value = v000 + kx u.x + ky u.y + kz u.z + kxy u.x u.y + kyz u.y u.z + kzx u.z u.x + kxyz u.x u.y u.z
+ float kx = v100 - v000, ky = v010 - v000, kz = v001 - v000;
+ float kxy = v000 - v100 - v010 + v110;
+ float kyz = v000 - v010 - v001 + v011;
+ float kzx = v000 - v100 - v001 + v101;
+ float kxyz = -v000 + v100 + v010 - v110 + v001 - v101 - v011 + v111;
+ float value = v000 + kx * u.x + ky * u.y + kz * u.z
+ + kxy * u.x * u.y + kyz * u.y * u.z + kzx * u.z * u.x + kxyz * u.x * u.y * u.z;
+ vec3 grad = g000 + (g100 - g000) * u.x + (g010 - g000) * u.y + (g001 - g000) * u.z
+ + (g000 - g100 - g010 + g110) * u.x * u.y
+ + (g000 - g010 - g001 + g011) * u.y * u.z
+ + (g000 - g100 - g001 + g101) * u.z * u.x
+ + (-g000 + g100 + g010 - g110 + g001 - g101 - g011 + g111) * u.x * u.y * u.z
+ + du * vec3(kx + kxy * u.y + kzx * u.z + kxyz * u.y * u.z,
+ ky + kxy * u.x + kyz * u.z + kxyz * u.x * u.z,
+ kz + kyz * u.y + kzx * u.x + kxyz * u.x * u.y);
+ return vec4(value, grad);
+}
const int FBM_MAX_OCTAVES = 12;
// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.
float fbm(vec2 p, int octaves, float lacunarity, float persistence) {
diff --git a/gallery/sdf-2d-poster.glsl b/gallery/sdf-2d-poster.glsl
index 9e1c27f..9088c9f 100644
--- a/gallery/sdf-2d-poster.glsl
+++ b/gallery/sdf-2d-poster.glsl
@@ -70,6 +70,7 @@ vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
// Derivative of quinticFade: 30 t^2 (t - 1)^2.
vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
+vec3 quinticFadeDeriv(vec3 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
// Unit gradient for a 2D lattice point.
vec2 latticeGradient(vec2 cell) {
float a = TAU * hash12(cell);
@@ -109,6 +110,44 @@ float gradientNoise(vec3 p) {
mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),
mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);
}
+// 3D gradient noise with analytic derivatives. Returns vec4(value, d/dx, d/dy, d/dz); value equals gradientNoise(p). The trilinear blend is expanded as a polynomial in the fade weights, so the gradient is the same blend of the corner gradients plus the chain-rule term of the fade.
+vec4 gradientNoiseD(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = quinticFade(f), du = quinticFadeDeriv(f);
+ vec3 g000 = hash33(i) * 2.0 - 1.0;
+ vec3 g100 = hash33(i + vec3(1, 0, 0)) * 2.0 - 1.0;
+ vec3 g010 = hash33(i + vec3(0, 1, 0)) * 2.0 - 1.0;
+ vec3 g110 = hash33(i + vec3(1, 1, 0)) * 2.0 - 1.0;
+ vec3 g001 = hash33(i + vec3(0, 0, 1)) * 2.0 - 1.0;
+ vec3 g101 = hash33(i + vec3(1, 0, 1)) * 2.0 - 1.0;
+ vec3 g011 = hash33(i + vec3(0, 1, 1)) * 2.0 - 1.0;
+ vec3 g111 = hash33(i + vec3(1, 1, 1)) * 2.0 - 1.0;
+ float v000 = dot(g000, f);
+ float v100 = dot(g100, f - vec3(1, 0, 0));
+ float v010 = dot(g010, f - vec3(0, 1, 0));
+ float v110 = dot(g110, f - vec3(1, 1, 0));
+ float v001 = dot(g001, f - vec3(0, 0, 1));
+ float v101 = dot(g101, f - vec3(1, 0, 1));
+ float v011 = dot(g011, f - vec3(0, 1, 1));
+ float v111 = dot(g111, f - vec3(1, 1, 1));
+ // value = v000 + kx u.x + ky u.y + kz u.z + kxy u.x u.y + kyz u.y u.z + kzx u.z u.x + kxyz u.x u.y u.z
+ float kx = v100 - v000, ky = v010 - v000, kz = v001 - v000;
+ float kxy = v000 - v100 - v010 + v110;
+ float kyz = v000 - v010 - v001 + v011;
+ float kzx = v000 - v100 - v001 + v101;
+ float kxyz = -v000 + v100 + v010 - v110 + v001 - v101 - v011 + v111;
+ float value = v000 + kx * u.x + ky * u.y + kz * u.z
+ + kxy * u.x * u.y + kyz * u.y * u.z + kzx * u.z * u.x + kxyz * u.x * u.y * u.z;
+ vec3 grad = g000 + (g100 - g000) * u.x + (g010 - g000) * u.y + (g001 - g000) * u.z
+ + (g000 - g100 - g010 + g110) * u.x * u.y
+ + (g000 - g010 - g001 + g011) * u.y * u.z
+ + (g000 - g100 - g001 + g101) * u.z * u.x
+ + (-g000 + g100 + g010 - g110 + g001 - g101 - g011 + g111) * u.x * u.y * u.z
+ + du * vec3(kx + kxy * u.y + kzx * u.z + kxyz * u.y * u.z,
+ ky + kxy * u.x + kyz * u.z + kxyz * u.x * u.z,
+ kz + kyz * u.y + kzx * u.x + kxyz * u.x * u.y);
+ return vec4(value, grad);
+}
const int FBM_MAX_OCTAVES = 12;
// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.
float fbm(vec2 p, int octaves, float lacunarity, float persistence) {
diff --git a/gallery/sdf-2d-poster.png b/gallery/sdf-2d-poster.png
index c90650a..568e360 100644
Binary files a/gallery/sdf-2d-poster.png and b/gallery/sdf-2d-poster.png differ
diff --git a/gallery/terrain.glsl b/gallery/terrain.glsl
index 2e55b9d..94d8929 100644
--- a/gallery/terrain.glsl
+++ b/gallery/terrain.glsl
@@ -54,6 +54,7 @@ vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
// Derivative of quinticFade: 30 t^2 (t - 1)^2.
vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
+vec3 quinticFadeDeriv(vec3 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
// Unit gradient for a 2D lattice point.
vec2 latticeGradient(vec2 cell) {
float a = TAU * hash12(cell);
@@ -93,6 +94,44 @@ float gradientNoise(vec3 p) {
mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),
mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);
}
+// 3D gradient noise with analytic derivatives. Returns vec4(value, d/dx, d/dy, d/dz); value equals gradientNoise(p). The trilinear blend is expanded as a polynomial in the fade weights, so the gradient is the same blend of the corner gradients plus the chain-rule term of the fade.
+vec4 gradientNoiseD(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = quinticFade(f), du = quinticFadeDeriv(f);
+ vec3 g000 = hash33(i) * 2.0 - 1.0;
+ vec3 g100 = hash33(i + vec3(1, 0, 0)) * 2.0 - 1.0;
+ vec3 g010 = hash33(i + vec3(0, 1, 0)) * 2.0 - 1.0;
+ vec3 g110 = hash33(i + vec3(1, 1, 0)) * 2.0 - 1.0;
+ vec3 g001 = hash33(i + vec3(0, 0, 1)) * 2.0 - 1.0;
+ vec3 g101 = hash33(i + vec3(1, 0, 1)) * 2.0 - 1.0;
+ vec3 g011 = hash33(i + vec3(0, 1, 1)) * 2.0 - 1.0;
+ vec3 g111 = hash33(i + vec3(1, 1, 1)) * 2.0 - 1.0;
+ float v000 = dot(g000, f);
+ float v100 = dot(g100, f - vec3(1, 0, 0));
+ float v010 = dot(g010, f - vec3(0, 1, 0));
+ float v110 = dot(g110, f - vec3(1, 1, 0));
+ float v001 = dot(g001, f - vec3(0, 0, 1));
+ float v101 = dot(g101, f - vec3(1, 0, 1));
+ float v011 = dot(g011, f - vec3(0, 1, 1));
+ float v111 = dot(g111, f - vec3(1, 1, 1));
+ // value = v000 + kx u.x + ky u.y + kz u.z + kxy u.x u.y + kyz u.y u.z + kzx u.z u.x + kxyz u.x u.y u.z
+ float kx = v100 - v000, ky = v010 - v000, kz = v001 - v000;
+ float kxy = v000 - v100 - v010 + v110;
+ float kyz = v000 - v010 - v001 + v011;
+ float kzx = v000 - v100 - v001 + v101;
+ float kxyz = -v000 + v100 + v010 - v110 + v001 - v101 - v011 + v111;
+ float value = v000 + kx * u.x + ky * u.y + kz * u.z
+ + kxy * u.x * u.y + kyz * u.y * u.z + kzx * u.z * u.x + kxyz * u.x * u.y * u.z;
+ vec3 grad = g000 + (g100 - g000) * u.x + (g010 - g000) * u.y + (g001 - g000) * u.z
+ + (g000 - g100 - g010 + g110) * u.x * u.y
+ + (g000 - g010 - g001 + g011) * u.y * u.z
+ + (g000 - g100 - g001 + g101) * u.z * u.x
+ + (-g000 + g100 + g010 - g110 + g001 - g101 - g011 + g111) * u.x * u.y * u.z
+ + du * vec3(kx + kxy * u.y + kzx * u.z + kxyz * u.y * u.z,
+ ky + kxy * u.x + kyz * u.z + kxyz * u.x * u.z,
+ kz + kyz * u.y + kzx * u.x + kxyz * u.x * u.y);
+ return vec4(value, grad);
+}
const int FBM_MAX_OCTAVES = 12;
// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.
float fbm(vec2 p, int octaves, float lacunarity, float persistence) {
diff --git a/gallery/volumetric-clouds.glsl b/gallery/volumetric-clouds.glsl
index 8eb9148..67cdcf4 100644
--- a/gallery/volumetric-clouds.glsl
+++ b/gallery/volumetric-clouds.glsl
@@ -57,6 +57,7 @@ vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
// Derivative of quinticFade: 30 t^2 (t - 1)^2.
vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
+vec3 quinticFadeDeriv(vec3 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
// Unit gradient for a 2D lattice point.
vec2 latticeGradient(vec2 cell) {
float a = TAU * hash12(cell);
@@ -96,6 +97,44 @@ float gradientNoise(vec3 p) {
mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),
mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);
}
+// 3D gradient noise with analytic derivatives. Returns vec4(value, d/dx, d/dy, d/dz); value equals gradientNoise(p). The trilinear blend is expanded as a polynomial in the fade weights, so the gradient is the same blend of the corner gradients plus the chain-rule term of the fade.
+vec4 gradientNoiseD(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = quinticFade(f), du = quinticFadeDeriv(f);
+ vec3 g000 = hash33(i) * 2.0 - 1.0;
+ vec3 g100 = hash33(i + vec3(1, 0, 0)) * 2.0 - 1.0;
+ vec3 g010 = hash33(i + vec3(0, 1, 0)) * 2.0 - 1.0;
+ vec3 g110 = hash33(i + vec3(1, 1, 0)) * 2.0 - 1.0;
+ vec3 g001 = hash33(i + vec3(0, 0, 1)) * 2.0 - 1.0;
+ vec3 g101 = hash33(i + vec3(1, 0, 1)) * 2.0 - 1.0;
+ vec3 g011 = hash33(i + vec3(0, 1, 1)) * 2.0 - 1.0;
+ vec3 g111 = hash33(i + vec3(1, 1, 1)) * 2.0 - 1.0;
+ float v000 = dot(g000, f);
+ float v100 = dot(g100, f - vec3(1, 0, 0));
+ float v010 = dot(g010, f - vec3(0, 1, 0));
+ float v110 = dot(g110, f - vec3(1, 1, 0));
+ float v001 = dot(g001, f - vec3(0, 0, 1));
+ float v101 = dot(g101, f - vec3(1, 0, 1));
+ float v011 = dot(g011, f - vec3(0, 1, 1));
+ float v111 = dot(g111, f - vec3(1, 1, 1));
+ // value = v000 + kx u.x + ky u.y + kz u.z + kxy u.x u.y + kyz u.y u.z + kzx u.z u.x + kxyz u.x u.y u.z
+ float kx = v100 - v000, ky = v010 - v000, kz = v001 - v000;
+ float kxy = v000 - v100 - v010 + v110;
+ float kyz = v000 - v010 - v001 + v011;
+ float kzx = v000 - v100 - v001 + v101;
+ float kxyz = -v000 + v100 + v010 - v110 + v001 - v101 - v011 + v111;
+ float value = v000 + kx * u.x + ky * u.y + kz * u.z
+ + kxy * u.x * u.y + kyz * u.y * u.z + kzx * u.z * u.x + kxyz * u.x * u.y * u.z;
+ vec3 grad = g000 + (g100 - g000) * u.x + (g010 - g000) * u.y + (g001 - g000) * u.z
+ + (g000 - g100 - g010 + g110) * u.x * u.y
+ + (g000 - g010 - g001 + g011) * u.y * u.z
+ + (g000 - g100 - g001 + g101) * u.z * u.x
+ + (-g000 + g100 + g010 - g110 + g001 - g101 - g011 + g111) * u.x * u.y * u.z
+ + du * vec3(kx + kxy * u.y + kzx * u.z + kxyz * u.y * u.z,
+ ky + kxy * u.x + kyz * u.z + kxyz * u.x * u.z,
+ kz + kyz * u.y + kzx * u.x + kxyz * u.x * u.y);
+ return vec4(value, grad);
+}
const int FBM_MAX_OCTAVES = 12;
// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.
float fbm(vec2 p, int octaves, float lacunarity, float persistence) {
diff --git a/skills/shader-art-coding/SKILL.md b/skills/shader-art-coding/SKILL.md
index a94eb5a..2079a3a 100644
--- a/skills/shader-art-coding/SKILL.md
+++ b/skills/shader-art-coding/SKILL.md
@@ -83,7 +83,8 @@ Read only what the task needs:
| `references/formula-code-couples-materials.md` | masks, palettes, lighting terms, polish, motion |
Templates in `templates/` are complete, render-verified starting points (gallery in the repository README):
-`raymarch-sdf.glsl`, `terrain.glsl`, `volumetric-clouds.glsl`, `sdf-2d-poster.glsl`, `pattern-swatches.glsl`.
+`raymarch-sdf.glsl`, `terrain.glsl`, `ocean.glsl`, `volumetric-clouds.glsl`, `sdf-2d-poster.glsl`,
+`pattern-swatches.glsl`.
## Output expectations
diff --git a/skills/shader-art-coding/glsl/domain.glsl b/skills/shader-art-coding/glsl/domain.glsl
index 9074357..c459870 100644
--- a/skills/shader-art-coding/glsl/domain.glsl
+++ b/skills/shader-art-coding/glsl/domain.glsl
@@ -49,6 +49,24 @@ float domPolarId(vec2 p, float n) {
return mod(floor(atan(p.y, p.x) / sector + 0.5), n);
}
+/// Neighbor-checked polar repetition: ids (in [0, n)) of the sector holding p and of the adjacent sector p leans
+/// toward. Evaluate the shape in both with domPolarSector and take the min. Use it when sectors vary (per-id length,
+/// tilt, color) or are asymmetric. It covers shapes of similar size that stay inside their own sector; a shape that
+/// reaches across its neighbor needs a wider search.
+/// @use varied petals, tilted fan blades, gear teeth of mixed sizes, uneven clock marks, radial crowds
+vec2 domPolarPair(vec2 p, float n) {
+ if (dot(p, p) < 1e-20) return vec2(0.0, 1.0);
+ float sector = TAU / n;
+ float a = atan(p.y, p.x) / sector;
+ float id = floor(a + 0.5);
+ return mod(vec2(id, id + ((a >= id) ? 1.0 : -1.0)), n);
+}
+
+/// Rotate p into the frame of polar sector id (its center line on +X). domPolarSector(p, domPolarId(p, n), n)
+/// equals domPolar(p, n).
+/// @use the second half of domPolarPair: evaluate a sector's shape by id
+vec2 domPolarSector(vec2 p, float id, float n) { return rot2(-id * TAU / n) * p; }
+
/// Fold space across the plane through the origin with unit normal n. Points behind the plane are reflected.
/// @use kaleidoscopes, symmetric creatures, KIFS fractals, mirrored architecture
vec3 domFold(vec3 p, vec3 n) { return p - 2.0 * min(dot(p, n), 0.0) * n; }
diff --git a/skills/shader-art-coding/glsl/noise.glsl b/skills/shader-art-coding/glsl/noise.glsl
index 7e7b424..da9b2a2 100644
--- a/skills/shader-art-coding/glsl/noise.glsl
+++ b/skills/shader-art-coding/glsl/noise.glsl
@@ -1,4 +1,5 @@
-//! noise: value and gradient noise (2D/3D, analytic derivatives), fBm, domain warping, Voronoi, tilings, dithering.
+//! noise: value, gradient and simplex noise (2D/3D, analytic derivatives), fBm, turbulence and billow, domain warping,
+//! curl flow, Voronoi, dithering.
//! Every function here is texture-free and original. The math follows the cited articles.
//! Ranges are approximate unless stated. Noise built on integer hashes stays stable at large coordinates
//! until float precision runs out (|p| around 1e5). Re-center long animations with mod/fract on time.
@@ -11,6 +12,7 @@ vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }
/// Derivative of quinticFade: 30 t^2 (t - 1)^2.
/// @use analytic noise derivatives
vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
+vec3 quinticFadeDeriv(vec3 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }
/// 2D value noise with analytic derivatives. Returns vec3(value, d/dx, d/dy).
/// @use terrain base layers, cheap clouds, anything needing normals without finite differences
@@ -79,6 +81,41 @@ vec3 gradientNoiseD(vec2 p) {
/// @range about [-0.7,0.7]
float gradientNoise(vec2 p) { return gradientNoiseD(p).x; }
+/// 2D simplex noise with analytic gradient. Returns vec3(value, d/dx, d/dy).
+/// Sums three radial kernels (0.5 - r^2)^4 on a triangular lattice instead of blending four square-cell corners, so it
+/// has fewer axis-aligned artifacts than gradientNoise. rotation (radians) spins every lattice gradient: animating it
+/// gives flow noise that churns in place instead of sliding (Perlin and Neyret 2001). Scaled so |value| <= 1 exactly.
+/// @use flowing water and lava (animate rotation), ripples with analytic normals, isotropic fBm, swirling fields
+/// @range value in [-1,1]
+/// @see Gustavson, "Simplex noise demystified" (2005); Gustavson and McEwan, JCGT 11(1), 2022 (psrdnoise)
+vec3 simplexNoiseD(vec2 p, float rotation) {
+ const float SKEW = 0.36602540378; // (sqrt(3) - 1) / 2: square lattice -> triangle lattice
+ const float UNSKEW = 0.21132486541; // (3 - sqrt(3)) / 6
+ vec2 cell = floor(p + (p.x + p.y) * SKEW);
+ vec2 d0 = p - cell + (cell.x + cell.y) * UNSKEW;
+ vec2 o = (d0.x > d0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); // which of the cell's two triangles holds p
+ vec2 corners[3] = vec2[3](cell, cell + o, cell + 1.0);
+ vec2 offsets[3] = vec2[3](d0, d0 - o + UNSKEW, d0 - 1.0 + 2.0 * UNSKEW);
+ mat2 spin = rot2(rotation);
+ vec3 sum = vec3(0.0);
+ for (int k = 0; k < 3; k++) {
+ vec2 d = offsets[k];
+ float t = max(0.5 - dot(d, d), 0.0);
+ vec2 g = spin * latticeGradient(corners[k]);
+ float gd = dot(g, d);
+ float t3 = t * t * t;
+ // value t^4 (g.d); gradient t^4 g - 8 t^3 (g.d) d
+ sum += vec3(t3 * t * gd, t3 * t * g - 8.0 * t3 * gd * d);
+ }
+ return 99.2 * sum; // 1 / max over the simplex of sum t^4 |d|
+}
+vec3 simplexNoiseD(vec2 p) { return simplexNoiseD(p, 0.0); }
+
+/// 2D simplex noise.
+/// @use isotropic smooth noise, fBm layers without grid alignment
+/// @range [-1,1]
+float simplexNoise(vec2 p) { return simplexNoiseD(p, 0.0).x; }
+
/// Dot product of a hashed 3D gradient with the offset to its lattice corner.
float latticeGradDot(vec3 cell, vec3 corner, vec3 f) {
vec3 g = hash33(cell + corner) * 2.0 - 1.0;
@@ -98,6 +135,50 @@ float gradientNoise(vec3 p) {
mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);
}
+/// 3D gradient noise with analytic derivatives. Returns vec4(value, d/dx, d/dy, d/dz); value equals gradientNoise(p).
+/// The trilinear blend is expanded as a polynomial in the fade weights, so the gradient is the same blend of the corner
+/// gradients plus the chain-rule term of the fade.
+/// @use normals of noise-displaced surfaces without extra samples, 3D curl flow, slope-aware 3D fBm, lit nebulae
+/// @range value in about [-1,1]
+/// @see https://iquilezles.org/articles/gradientnoise/
+vec4 gradientNoiseD(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ vec3 u = quinticFade(f), du = quinticFadeDeriv(f);
+ vec3 g000 = hash33(i) * 2.0 - 1.0;
+ vec3 g100 = hash33(i + vec3(1, 0, 0)) * 2.0 - 1.0;
+ vec3 g010 = hash33(i + vec3(0, 1, 0)) * 2.0 - 1.0;
+ vec3 g110 = hash33(i + vec3(1, 1, 0)) * 2.0 - 1.0;
+ vec3 g001 = hash33(i + vec3(0, 0, 1)) * 2.0 - 1.0;
+ vec3 g101 = hash33(i + vec3(1, 0, 1)) * 2.0 - 1.0;
+ vec3 g011 = hash33(i + vec3(0, 1, 1)) * 2.0 - 1.0;
+ vec3 g111 = hash33(i + vec3(1, 1, 1)) * 2.0 - 1.0;
+ float v000 = dot(g000, f);
+ float v100 = dot(g100, f - vec3(1, 0, 0));
+ float v010 = dot(g010, f - vec3(0, 1, 0));
+ float v110 = dot(g110, f - vec3(1, 1, 0));
+ float v001 = dot(g001, f - vec3(0, 0, 1));
+ float v101 = dot(g101, f - vec3(1, 0, 1));
+ float v011 = dot(g011, f - vec3(0, 1, 1));
+ float v111 = dot(g111, f - vec3(1, 1, 1));
+ // value = v000 + kx u.x + ky u.y + kz u.z + kxy u.x u.y + kyz u.y u.z + kzx u.z u.x + kxyz u.x u.y u.z
+ float kx = v100 - v000, ky = v010 - v000, kz = v001 - v000;
+ float kxy = v000 - v100 - v010 + v110;
+ float kyz = v000 - v010 - v001 + v011;
+ float kzx = v000 - v100 - v001 + v101;
+ float kxyz = -v000 + v100 + v010 - v110 + v001 - v101 - v011 + v111;
+ float value = v000 + kx * u.x + ky * u.y + kz * u.z
+ + kxy * u.x * u.y + kyz * u.y * u.z + kzx * u.z * u.x + kxyz * u.x * u.y * u.z;
+ vec3 grad = g000 + (g100 - g000) * u.x + (g010 - g000) * u.y + (g001 - g000) * u.z
+ + (g000 - g100 - g010 + g110) * u.x * u.y
+ + (g000 - g010 - g001 + g011) * u.y * u.z
+ + (g000 - g100 - g001 + g101) * u.z * u.x
+ + (-g000 + g100 + g010 - g110 + g001 - g101 - g011 + g111) * u.x * u.y * u.z
+ + du * vec3(kx + kxy * u.y + kzx * u.z + kxyz * u.y * u.z,
+ ky + kxy * u.x + kyz * u.z + kxyz * u.x * u.z,
+ kz + kyz * u.y + kzx * u.x + kxyz * u.x * u.y);
+ return vec4(value, grad);
+}
+
const int FBM_MAX_OCTAVES = 12;
/// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment.
@@ -181,6 +262,74 @@ float ridgedFbm(vec2 p, int octaves) {
return sum / norm;
}
+/// Perlin's turbulence: fBm of |noise|. The absolute value folds every zero crossing into a sharp crease, at every scale.
+/// @use fire, marble veins (sin(x + k * turbulence)), smoke wisps, electric glow, lava cracks, wind-torn clouds
+/// @range [0,1]
+/// @see Perlin, "An Image Synthesizer", SIGGRAPH 1985
+float turbulence(vec2 p, int octaves) {
+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);
+ float sum = 0.0, amp = 1.0, norm = 0.0;
+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {
+ if (i >= octaves) break;
+ sum += amp * abs(gradientNoise(p));
+ norm += amp;
+ amp *= 0.5;
+ p = 2.01 * (octaveRotation * p) + vec2(17.13, -3.71);
+ }
+ return 1.4 * sum / norm; // |2D gradient noise| <= sqrt(2)/2
+}
+float turbulence(vec3 p, int octaves) {
+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,
+ -0.80, 0.36, -0.48,
+ -0.60, -0.48, 0.64);
+ float sum = 0.0, amp = 1.0, norm = 0.0;
+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {
+ if (i >= octaves) break;
+ sum += amp * min(abs(gradientNoise(p)), 1.0);
+ norm += amp;
+ amp *= 0.5;
+ p = 2.01 * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);
+ }
+ return sum / norm;
+}
+
+/// Billowy multifractal: |noise| per octave makes puffy rounded lobes split by sharp creases (the inverse of ridgedFbm).
+/// Each octave is weighted by the previous one, so detail gathers on the lobes while the creases stay clean.
+/// @use cumulus and cauliflower tops, puffy smoke, foam clumps, rock piles, cotton, popcorn-like bumps
+/// @range [0,1]
+float billowFbm(vec2 p, int octaves) {
+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);
+ float sum = 0.0, amp = 0.5, weight = 1.0, norm = 0.0;
+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {
+ if (i >= octaves) break;
+ float n = abs(gradientNoise(p) * 1.4);
+ n = n * (2.0 - n); // round the lobe tops, keep the creases sharp
+ sum += amp * n * weight;
+ norm += amp;
+ weight = clamp(n * 1.5, 0.0, 1.0);
+ amp *= 0.5;
+ p = 2.01 * (octaveRotation * p) + vec2(17.13, -3.71);
+ }
+ return sum / norm;
+}
+float billowFbm(vec3 p, int octaves) {
+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,
+ -0.80, 0.36, -0.48,
+ -0.60, -0.48, 0.64);
+ float sum = 0.0, amp = 0.5, weight = 1.0, norm = 0.0;
+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {
+ if (i >= octaves) break;
+ float n = min(abs(gradientNoise(p)) * 1.4, 1.0);
+ n = n * (2.0 - n);
+ sum += amp * n * weight;
+ norm += amp;
+ weight = clamp(n * 1.5, 0.0, 1.0);
+ amp *= 0.5;
+ p = 2.01 * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);
+ }
+ return sum / norm;
+}
+
/// Two-level domain warp f(p + s*r), r = fbm(p + s*q), q = fbm(p). Writes the intermediate warp
/// vectors so they can drive color. Cost is 5 fBm calls.
/// @use marble, smoke, agate, alien skies, painterly backgrounds
@@ -201,6 +350,17 @@ vec2 curlNoise(vec2 p) {
return vec2(n.z, -n.y);
}
+/// Divergence-free 3D flow field: the curl of a vector potential whose components are three decorrelated
+/// gradientNoiseD fields. Analytic, so it costs three noise evaluations and no finite differences.
+/// @use smoke and fire advection, swirling particles and sparks, wisps, 3D flow-aligned strokes, magic trails
+/// @see Bridson, Hourihan and Nordenstam, "Curl-Noise for Procedural Fluid Flow", SIGGRAPH 2007
+vec3 curlNoise(vec3 p) {
+ vec3 a = gradientNoiseD(p).yzw; // grad of potential.x
+ vec3 b = gradientNoiseD(p + vec3(31.416, -47.853, 12.793)).yzw; // grad of potential.y
+ vec3 c = gradientNoiseD(p + vec3(-23.719, 18.274, -56.183)).yzw; // grad of potential.z
+ return vec3(c.y - b.z, a.z - c.x, b.x - a.y);
+}
+
/// Cellular (Worley/Voronoi) noise. Returns vec4(F1, F2, nearestCell.xy).
/// F1 = distance to nearest feature point, F2 = second nearest. nearestCell is integer-valued, so hash it for
/// per-cell randomness. jitter in [0,1] (0 = regular grid). Searches 3x3 cells. F2 can be slightly off at jitter 1.
diff --git a/skills/shader-art-coding/glsl/sdf2d.glsl b/skills/shader-art-coding/glsl/sdf2d.glsl
index 5714dba..66ae8b1 100644
--- a/skills/shader-art-coding/glsl/sdf2d.glsl
+++ b/skills/shader-art-coding/glsl/sdf2d.glsl
@@ -204,3 +204,67 @@ float sdQuadraticBezier(vec2 pos, vec2 A, vec2 B, vec2 C) {
}
return sqrt(res);
}
+
+/// Pie slice (circular sector) of radius r, symmetric about +Y. sc = vec2(sin, cos) of the half-aperture, which may
+/// go up to pi (a full disk); past pi/2 the slice is concave.
+/// @exact
+/// @use pie charts, pac-man, fans, radar sweeps, pizza slices, clock wedges, 2D spotlight cones
+float sdPie(vec2 p, vec2 sc, float r) {
+ p.x = abs(p.x);
+ float toArc = length(p) - r;
+ float toEdge = length(p - sc * clamp(dot(p, sc), 0.0, r)); // straight edge from the center along sc
+ float side = sign(sc.y * p.x - sc.x * p.y); // +1 beyond the aperture, -1 within it
+ return max(toArc, toEdge * side);
+}
+
+/// Horseshoe: an arc of radius r over the top (half-aperture given by sc = vec2(sin, cos), as in sdArc) whose ends run on
+/// as straight legs of length legLength along the arc's tangent, stroked with half-width w and round ends.
+/// The legs must not cross the Y axis (keep legLength * |cos(aperture)| below r * sin(aperture)).
+/// @exact
+/// @use horseshoes, magnets, U-bends, arches with posts, croquet hoops, handles, headphones (2D)
+float sdHorseshoe(vec2 p, vec2 sc, float r, float legLength, float w) {
+ p.x = abs(p.x);
+ vec2 end = r * sc;
+ float leg = sdSegment(p, end, end + legLength * vec2(sc.y, -sc.x));
+ return min(sdArc(p, sc, r, 0.0), leg) - w;
+}
+
+/// Parabolic arch: the region under y = h (1 - x^2 / w^2) and above y = 0, so half-width w at the base and height h.
+/// The closest point on the curve is the largest root of a depressed cubic, solved in closed form.
+/// @exact
+/// @use arches, bridges, tunnels, domes, bullets, gothic windows, tents, fountain jets, bell curves
+float sdParabolaSegment(vec2 p, float w, float h) {
+ p.x = abs(p.x);
+ float k = h / (w * w); // curve y = h - k x^2
+ // d/dx |p - (x, h - k x^2)|^2 = 0 <=> x^3 + P x + Q = 0
+ float P = (1.0 - 2.0 * k * (h - p.y)) / (2.0 * k * k);
+ float Q = -p.x / (2.0 * k * k);
+ float disc = 0.25 * Q * Q + P * P * P / 27.0;
+ float x;
+ if (disc >= 0.0) {
+ float u = pow(-0.5 * Q + sqrt(disc), 1.0 / 3.0); // Q <= 0, so no cancellation here
+ float v = -P / (3.0 * max(u, 1e-20));
+ x = -Q / max(u * u - u * v + v * v, 1e-30); // = u + v, without cancelling u against v
+ } else {
+ float m = sqrt(-P / 3.0);
+ x = 2.0 * m * cos(acos(clamp(-Q / (2.0 * m * m * m), -1.0, 1.0)) / 3.0); // largest of three roots
+ }
+ // Q <= 0 means the squared distance falls from x = 0 up to the root, so clamping the root to the arc is exact
+ x = clamp(x, 0.0, w);
+ float d = min(length(p - vec2(x, h - k * x * x)), length(p - vec2(min(p.x, w), 0.0)));
+ return (p.y > 0.0 && p.y < h - k * p.x * p.x) ? -d : d;
+}
+
+/// Egg built from four tangent arcs (Moss-style): a bottom half-disk of radius ra centered at the origin, a top cap of
+/// radius rb, and two side arcs of radius 2 ra joining them. rb = ra is a disk; smaller rb makes a pointier egg.
+/// Spans y from -ra to sqrt((2 ra - rb)^2 - ra^2) + rb. Needs 0 < rb <= ra.
+/// @exact
+/// @use eggs, droplets, pebbles, seeds, cartoon heads and bodies, onion domes (flip y), Easter eggs
+float sdEgg(vec2 p, float ra, float rb) {
+ p.x = abs(p.x);
+ float c = sqrt((2.0 * ra - rb) * (2.0 * ra - rb) - ra * ra); // height of the cap center
+ if (p.y < 0.0) return length(p) - ra;
+ // past the line from the right arc's center (-ra, 0) through the cap center, the cap is nearest
+ if (ra * p.y > c * (p.x + ra)) return length(p - vec2(0.0, c)) - rb;
+ return length(p + vec2(ra, 0.0)) - 2.0 * ra;
+}
diff --git a/skills/shader-art-coding/references/library-index.md b/skills/shader-art-coding/references/library-index.md
index a2dbb61..25b3462 100644
--- a/skills/shader-art-coding/references/library-index.md
+++ b/skills/shader-art-coding/references/library-index.md
@@ -14,7 +14,7 @@ Tags: **exact** is a true Euclidean distance, safe for blending, AO, shadows and
- [common](#common) - constants, rotation, remapping and shaping functions
- [hash](#hash) - integer hashes and float wrappers for lattice ids
-- [noise](#noise) - value and gradient noise (2D/3D, analytic derivatives), fBm, domain warping, Voronoi, tilings, dithering
+- [noise](#noise) - value, gradient and simplex noise (2D/3D, analytic derivatives), fBm, turbulence and billow, domain warping, curl flow, Voronoi, dithering
- [pattern](#pattern) - tilings and antialiased procedural patterns
- [sdf3d](#sdf3d) - 3D signed distance primitives
- [sdf2d](#sdf2d) - 2D signed distance primitives for posters, icons, UI, motion graphics, and as profiles for opExtrude / opRevolve
@@ -66,22 +66,26 @@ hash: integer hashes and float wrappers for lattice ids. Naming: hashNM returns
## noise
-noise: value and gradient noise (2D/3D, analytic derivatives), fBm, domain warping, Voronoi, tilings, dithering. Every function here is texture-free and original. The math follows the cited articles. Ranges are approximate unless stated. Noise built on integer hashes stays stable at large coordinates until float precision runs out (|p| around 1e5). Re-center long animations with mod/fract on time.
+noise: value, gradient and simplex noise (2D/3D, analytic derivatives), fBm, turbulence and billow, domain warping, curl flow, Voronoi, dithering. Every function here is texture-free and original. The math follows the cited articles. Ranges are approximate unless stated. Noise built on integer hashes stays stable at large coordinates until float precision runs out (|p| around 1e5). Re-center long animations with mod/fract on time.
- `vec2 quinticFade(vec2 f)` / `vec3 quinticFade(vec3 f)` - Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise. *Use: custom lattice noises, smooth cell interpolation.*
-- `vec2 quinticFadeDeriv(vec2 f)` - Derivative of quinticFade: 30 t^2 (t - 1)^2. *Use: analytic noise derivatives.*
+- `vec2 quinticFadeDeriv(vec2 f)` / `vec3 quinticFadeDeriv(vec3 f)` - Derivative of quinticFade: 30 t^2 (t - 1)^2. *Use: analytic noise derivatives.*
- `vec3 valueNoiseD(vec2 p)` - 2D value noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). *Use: terrain base layers, cheap clouds, anything needing normals without finite differences.* Range value in [0,1].
- `float valueNoise(vec2 p)` / `float valueNoise(vec3 p)` - 2D value noise. *Use: soft blotches, low-frequency color variation.* Range [0,1].
- `vec2 latticeGradient(vec2 cell)` - Unit gradient for a 2D lattice point.
-- `vec3 gradientNoiseD(vec2 p)` - 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm. *Use: fBm, terrain with analytic normals, curl flow, marble and wood distortions.* Range value in about [-0.7,0.7].
+- `vec3 gradientNoiseD(vec2 p)` / `vec4 gradientNoiseD(vec3 p)` - 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm. *Use: fBm, terrain with analytic normals, curl flow, marble and wood distortions.* Range value in about [-0.7,0.7].
- `float gradientNoise(vec2 p)` / `float gradientNoise(vec3 p)` - 2D gradient noise. *Use: general-purpose smooth noise.* Range about [-0.7,0.7].
+- `vec3 simplexNoiseD(vec2 p, float rotation)` / `vec3 simplexNoiseD(vec2 p)` - 2D simplex noise with analytic gradient. Returns vec3(value, d/dx, d/dy). Sums three radial kernels (0.5 - r^2)^4 on a triangular lattice instead of blending four square-cell corners, so it has fewer axis-aligned artifacts than gradientNoise. rotation (radians) spins every lattice gradient: animating it gives flow noise that churns in place instead of sliding (Perlin and Neyret 2001). Scaled so |value| <= 1 exactly. *Use: flowing water and lava (animate rotation), ripples with analytic normals, isotropic fBm, swirling fields.* Range value in [-1,1].
+- `float simplexNoise(vec2 p)` - 2D simplex noise. *Use: isotropic smooth noise, fBm layers without grid alignment.* Range [-1,1].
- `float latticeGradDot(vec3 cell, vec3 corner, vec3 f)` - Dot product of a hashed 3D gradient with the offset to its lattice corner.
- `const int FBM_MAX_OCTAVES = 12;`
- `float fbm(vec2 p, int octaves, float lacunarity, float persistence)` / `float fbm(vec2 p, int octaves)` / `float fbm(vec3 p, int octaves, float lacunarity, float persistence)` - Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher. *Use: clouds, terrain, dirt, roughness breakup, warping input.* Range about [-1,1].
- `float erodedFbm(vec2 p, int octaves)` - Terrain fBm where each octave is damped by the accumulated slope, so detail settles in valleys and steep slopes stay smooth. This gives an eroded look without simulation. *Use: mountains, dunes, rocky ground.* Range about [-0.5,1].
- `float ridgedFbm(vec2 p, int octaves)` - Ridged multifractal: inverted |noise| creates sharp crests; each octave is weighted by the previous one, so detail gathers along ridges. *Use: mountain ridges, lightning-like veins, canyons, eroded rock, alien landscapes.* Range about [0,1].
+- `float turbulence(vec2 p, int octaves)` / `float turbulence(vec3 p, int octaves)` - Perlin's turbulence: fBm of |noise|. The absolute value folds every zero crossing into a sharp crease, at every scale. *Use: fire, marble veins (sin(x + k * turbulence)), smoke wisps, electric glow, lava cracks, wind-torn clouds.* Range [0,1].
+- `float billowFbm(vec2 p, int octaves)` / `float billowFbm(vec3 p, int octaves)` - Billowy multifractal: |noise| per octave makes puffy rounded lobes split by sharp creases (the inverse of ridgedFbm). Each octave is weighted by the previous one, so detail gathers on the lobes while the creases stay clean. *Use: cumulus and cauliflower tops, puffy smoke, foam clumps, rock piles, cotton, popcorn-like bumps.* Range [0,1].
- `float warpedFbm(vec2 p, float strength, int octaves, out vec2 q, out vec2 r)` - Two-level domain warp f(p + s*r), r = fbm(p + s*q), q = fbm(p). Writes the intermediate warp vectors so they can drive color. Cost is 5 fBm calls. *Use: marble, smoke, agate, alien skies, painterly backgrounds.* Range about [-1,1].
-- `vec2 curlNoise(vec2 p)` - Divergence-free 2D flow field: the curl of scalar gradient noise. Particles advected by it swirl without bunching up. *Use: smoke advection, flowing paint, hair/fur flow direction, wind.*
+- `vec2 curlNoise(vec2 p)` / `vec3 curlNoise(vec3 p)` - Divergence-free 2D flow field: the curl of scalar gradient noise. Particles advected by it swirl without bunching up. *Use: smoke advection, flowing paint, hair/fur flow direction, wind.*
- `vec4 voronoi(vec2 p, float jitter)` - Cellular (Worley/Voronoi) noise. Returns vec4(F1, F2, nearestCell.xy). F1 = distance to nearest feature point, F2 = second nearest. nearestCell is integer-valued, so hash it for per-cell randomness. jitter in [0,1] (0 = regular grid). Searches 3x3 cells. F2 can be slightly off at jitter 1. *Use: cells, scales, stones, cracked mud (F2-F1), caustics, foam, sparkles.* Range F1 in [0, ~1.2].
- `vec3 voronoiBorder(vec2 p, float jitter)` - Exact distance to Voronoi cell borders, found in two passes: nearest point, then nearest bisector. Returns vec3(borderDistance, vectorToNearestPoint). Unlike F2-F1, the border distance is a true distance, so lines have constant width. *Use: cell walls, stained glass leading, cracked earth, giraffe and leaf-vein patterns, crackle glaze.*
- `float smoothVoronoi(vec2 p, float k)` - Smooth Voronoi: a soft-min of distances to feature points. Cells become blobs with no creases. k controls smoothness (large = sharper; around 8-32). Searches 5x5 cells so low k has no seams. *Use: organic cell clusters, bubbles, lumpy surfaces, skin pores.*
@@ -147,6 +151,10 @@ sdf2d: 2D signed distance primitives for posters, icons, UI, motion graphics, an
- `float sdRhombus(vec2 p, vec2 b)` **exact** - Rhombus with half-diagonals b. *Use: diamonds, kites, card suits, argyle, harlequin patterns.*
- `float sdEllipse(vec2 p, vec2 r)` **approx** - Ellipse with semi-axes r. A fast approximation: exact zero set, a bound outside up to about 2:1 aspect, gradient above 1 inside and for flatter ellipses. Fine for fills and strokes; avoid for exact offsets. *Use: eyes, pupils, ovals, shadows under objects, planet rings (with opOnion).*
- `float sdQuadraticBezier(vec2 pos, vec2 A, vec2 B, vec2 C)` **exact** - Unsigned distance to a quadratic Bezier curve A-B-C. Solves the closest-point cubic analytically. Falls back to a segment when the curve degenerates to a line. Float error in the cubic solve is about 1e-4. *Use: brush strokes, hair, calligraphy, tendrils, eyelashes, smooth paths, font-like curves.*
+- `float sdPie(vec2 p, vec2 sc, float r)` **exact** - Pie slice (circular sector) of radius r, symmetric about +Y. sc = vec2(sin, cos) of the half-aperture, which may go up to pi (a full disk); past pi/2 the slice is concave. *Use: pie charts, pac-man, fans, radar sweeps, pizza slices, clock wedges, 2D spotlight cones.*
+- `float sdHorseshoe(vec2 p, vec2 sc, float r, float legLength, float w)` **exact** - Horseshoe: an arc of radius r over the top (half-aperture given by sc = vec2(sin, cos), as in sdArc) whose ends run on as straight legs of length legLength along the arc's tangent, stroked with half-width w and round ends. The legs must not cross the Y axis (keep legLength * |cos(aperture)| below r * sin(aperture)). *Use: horseshoes, magnets, U-bends, arches with posts, croquet hoops, handles, headphones (2D).*
+- `float sdParabolaSegment(vec2 p, float w, float h)` **exact** - Parabolic arch: the region under y = h (1 - x^2 / w^2) and above y = 0, so half-width w at the base and height h. The closest point on the curve is the largest root of a depressed cubic, solved in closed form. *Use: arches, bridges, tunnels, domes, bullets, gothic windows, tents, fountain jets, bell curves.*
+- `float sdEgg(vec2 p, float ra, float rb)` **exact** - Egg built from four tangent arcs (Moss-style): a bottom half-disk of radius ra centered at the origin, a top cap of radius rb, and two side arcs of radius 2 ra joining them. rb = ra is a disk; smaller rb makes a pointier egg. Spans y from -ra to sqrt((2 ra - rb)^2 - ra^2) + rb. Needs 0 < rb <= ra. *Use: eggs, droplets, pebbles, seeds, cartoon heads and bodies, onion domes (flip y), Easter eggs.*
## operators
@@ -179,6 +187,8 @@ domain: transform the point BEFORE evaluating a distance (repetition, mirroring,
- `vec2 domRepeatMirror(vec2 p, vec2 s)` - Mirrored repetition: every other cell is flipped, so shapes touching the cell border join seamlessly. *Use: tiled ornaments, symmetric wallpaper, seamless pipes and rails.*
- `vec2 domPolar(vec2 p, float n)` - Polar repetition into n sectors around the origin. Returns the point rotated into the sector centered on +X. Single evaluation: exact for shapes symmetric about their sector's center line. For asymmetric or per-sector-varying shapes, evaluate this sector and its neighbor and take the min (see references/sdf-library-guide.md). *Use: petals, spokes, gears, clock marks, radial ornaments, columns around a tower.*
- `float domPolarId(vec2 p, float n)` - Sector index in [0, n) for domPolar. *Use: varying each petal, spoke or column.*
+- `vec2 domPolarPair(vec2 p, float n)` - Neighbor-checked polar repetition: ids (in [0, n)) of the sector holding p and of the adjacent sector p leans toward. Evaluate the shape in both with domPolarSector and take the min. Use it when sectors vary (per-id length, tilt, color) or are asymmetric. It covers shapes of similar size that stay inside their own sector; a shape that reaches across its neighbor needs a wider search. *Use: varied petals, tilted fan blades, gear teeth of mixed sizes, uneven clock marks, radial crowds.*
+- `vec2 domPolarSector(vec2 p, float id, float n)` - Rotate p into the frame of polar sector id (its center line on +X). domPolarSector(p, domPolarId(p, n), n) equals domPolar(p, n). *Use: the second half of domPolarPair: evaluate a sector's shape by id.*
- `vec3 domFold(vec3 p, vec3 n)` - Fold space across the plane through the origin with unit normal n. Points behind the plane are reflected. *Use: kaleidoscopes, symmetric creatures, KIFS fractals, mirrored architecture.*
- `vec3 domTwist(vec3 p, float k)` - Twist around Y: rotate XZ by k * y. Divide the resulting distance by L = a/2 + sqrt(1 + a*a/4), a = k * R, where R is the shape's max distance from the Y axis. Without that, the march overshoots. *Use: twisted columns, drills, licorice, DNA-like spirals, towels.*
- `vec3 domBend(vec3 p, float k)` - Bend in XY: rotate XY by k * x. Divide the resulting distance by about 1 + k * R (R = max |p.xy| of the shape). *Use: bent beams, arches from boxes, bananas, curved horns.*
diff --git a/skills/shader-art-coding/references/sdf-library-guide.md b/skills/shader-art-coding/references/sdf-library-guide.md
index 1fd24f9..4550d3f 100644
--- a/skills/shader-art-coding/references/sdf-library-guide.md
+++ b/skills/shader-art-coding/references/sdf-library-guide.md
@@ -100,18 +100,17 @@ float sdPillarField(vec3 p, float spacing) {
```
Polar repetition has the same rule. `domPolar` is exact for shapes symmetric about their sector's center line. For
-asymmetric or varying petals, evaluate the sector and its nearer neighbor:
+asymmetric or varying petals, evaluate the sector and the neighbor p leans toward. `domPolarPair` returns both ids
+and `domPolarSector` rotates into either one:
```glsl
float sdPetalRing(vec2 p, float n) {
- float sector = TAU / n;
- float a = atan(p.y, p.x);
- float id = floor(a / sector - 0.5); // the two petals around angle a are id and id + 1
+ vec2 ids = domPolarPair(p, n);
float d = 1e10;
for (int i = 0; i < 2; i++) {
- float k = id + float(i);
- vec2 q = rot2(-(k + 0.5) * sector) * p; // rotate this sector's center onto +X
- float len = 0.5 + 0.2 * hash11(mod(k, n)); // per-petal length
+ float k = (i == 0) ? ids.x : ids.y;
+ vec2 q = domPolarSector(p, k, n); // this sector's center line on +X
+ float len = 0.5 + 0.2 * hash11(k); // per-petal length
d = min(d, sdUnevenCapsule(vec2(q.y, q.x - 0.15), 0.08, 0.02, len));
}
return d;
@@ -147,10 +146,12 @@ Get as close as possible with exact operations first, then add the smallest disp
between machines and degrades at large coordinates.
- Use noise in tiers: low frequency for silhouette and mass, mid for material breakup, high for grain. Do not use
the same noise for shape, color and roughness. Offset or rotate the inputs so the controls stay independent.
-- Picking a noise: `gradientNoise` / `fbm` for general use, `valueNoiseD` / `gradientNoiseD` when you need analytic
- normals, `erodedFbm` for mountains, `ridgedFbm` for crests and veins, `warpedFbm` for marble and smoke, `voronoi`
- for cells and stones, `voronoiBorder` for constant-width cracks and leading, `smoothVoronoi` for soft organic cells,
- `curlNoise` for swirling flow.
+- Picking a noise: `gradientNoise` / `fbm` for general use, `simplexNoiseD` for isotropic noise with a gradient (animate
+ its rotation for flow noise that churns in place), `valueNoiseD` / `gradientNoiseD` (2D and 3D) when you need
+ analytic normals, `erodedFbm` for mountains, `ridgedFbm` for crests and veins, `turbulence` for creased fire and
+ marble veins, `billowFbm` for puffy lobes, `warpedFbm` for marble and smoke, `voronoi` for cells and stones,
+ `voronoiBorder` for constant-width cracks and leading, `smoothVoronoi` for soft organic cells, `curlNoise` (2D or
+ 3D) for divergence-free swirling flow.
- Keep coordinates bounded: float precision is about 0.001 at 1e4 and 0.008 at 1e5. Wrap long animations with `mod`.
## Shaping functions
diff --git a/skills/shader-art-coding/references/subject-routing.md b/skills/shader-art-coding/references/subject-routing.md
index 45eac3a..d15965e 100644
--- a/skills/shader-art-coding/references/subject-routing.md
+++ b/skills/shader-art-coding/references/subject-routing.md
@@ -21,7 +21,8 @@ section with the formulas. The formula files use geometry-first names; this tabl
|---|---|---|
| flat graphic, poster, icon, logo, UI, pattern | 2D distance fields + `fillAA` | `sdf-2d-poster.glsl`, `pattern-swatches.glsl` |
| sculpted 3D objects, characters, still lifes | SDF raymarching | `raymarch-sdf.glsl` |
-| landscape, terrain, ocean surface | heightfield march (scaled bound) | `terrain.glsl` |
+| landscape, terrain | heightfield march (scaled bound) | `terrain.glsl` |
+| sea, ocean, lake surface | heightfield trace in a wave slab + Fresnel reflection | `ocean.glsl` |
| clouds, smoke, fog volumes, nebulae, fire | volume integration | `volumetric-clouds.glsl` |
| texture, material swatch, wallpaper | 2D procedural pattern | `pattern-swatches.glsl` |
@@ -59,12 +60,12 @@ section with the formulas. The formula files use geometry-first names; this tabl
| mountains | `erodedFbm` height, `ridgedFbm` crests, slope/altitude masks | couples-terrain 1-12, `terrain.glsl` |
| snow | upward-facing accumulation mask (`n.y`) + altitude + noise breakup | couples-terrain 22 |
| desert dunes | `ridgedFbm` along one axis + `warpedFbm`, low sun | couples-terrain 23 (layered ridge) |
-| ocean, lakes | `iPlane` water + `fresnelSchlick` + sky reflection, `gradientNoiseD` normals | rendering-pipeline "Lighting" |
+| ocean, lakes | `ocean.glsl`: dispersive exp-sine waves with analytic slope and curvature, `fresnelSchlick` sky reflection, GGX glint with distance roughness, curvature foam; calm lakes: `iPlane` + `simplexNoiseD` ripples | rendering-pipeline "Lighting" |
| sky, sunset | `atmosphereSky` (physical) or `simpleSky`; `sunDisk` | rendering-pipeline "Sky, fog and aerial perspective" |
| clouds | `volumetric-clouds.glsl`: coverage fBm, `beerPowder`, `phaseDualHG`, `volumeStep` | rendering-pipeline "Volumes" |
| fog, mist, haze | `distanceFog`, `heightFog`, aerial perspective with horizon-clamped sky | couples-terrain 13-14 |
| night sky, stars | per-cell `hash32` stars, `blackbody` colors, twinkle with `sin(iTime)` | `sdf-2d-poster.glsl` |
-| fire, lava, embers | `warpedFbm` / `curlNoise`, `blackbody(1200-1800 K)`, additive glow, AgX | rendering-pipeline "Volumes" |
+| fire, lava, embers | `turbulence`, `warpedFbm` / `curlNoise` (2D or 3D), `simplexNoiseD` with animated rotation for churning flow, `blackbody(1200-1800 K)`, additive glow, AgX | rendering-pipeline "Volumes" |
| rain, snowfall | repeated streaks with `domRepeat` + per-cell `hash12` phase | sdf-library-guide "Repetition" |
## Built and manufactured things
@@ -101,6 +102,7 @@ section with the formulas. The formula files use geometry-first names; this tabl
| poster, landscape silhouette | ridges from `fbm` lines, layered back to front, `mixOklab` sky | `sdf-2d-poster.glsl` |
| icons, UI shapes | `sdRoundedBox` (per-corner), `sdCircle`, `strokeAA` | couples-materials 3-4 |
| loaders, gauges, rings | `sdArc`, `opOnion`, time-driven aperture | couples-materials 25-26 |
+| charts, badges, signage | `sdPie` (pie charts, radar sweeps), `sdHorseshoe` (magnets, U-bends), `sdParabolaSegment` (arches, domes), `sdEgg` (eggs, drops, cartoon heads) | library-index (sdf2d) |
| kaleidoscopes, mandalas | `domPolar`, `domFold`, `cosinePalette` | sdf-library-guide "Repetition" |
| retro sunsets, synthwave | `filteredStripes`, `filteredGrid` in perspective, `tonemapNeutral` | `sdf-2d-poster.glsl` |
| looping animation | integer-frequency `cos(TAU * t)`, `cosinePalette` with integer c | couples-materials 25 |
diff --git a/skills/shader-art-coding/templates/ocean.glsl b/skills/shader-art-coding/templates/ocean.glsl
new file mode 100644
index 0000000..e0bd154
--- /dev/null
+++ b/skills/shader-art-coding/templates/ocean.glsl
@@ -0,0 +1,255 @@
+// Open ocean at golden hour under a physically based sky.
+// Shows: a sum of dispersive exp-sine waves with analytic slope and curvature (normals and foam with no extra samples),
+// a heightfield tracer clipped to the wave slab, distance filtering that hands the slope of vanished waves to GGX
+// roughness (the glitter path widens with distance), simplex flow-noise ripples, Fresnel sky reflection, a sun glint,
+// light glowing through thin crests, curvature foam broken up by billow noise, aerial perspective, AgX.
+// Units are meters; the atmosphere functions take kilometers.
+// @render time=12.5
+
+#define DEBUG_MODE 0 // 0 final | 1 height | 2 normals | 3 foam mask | 4 trace steps | 5 fresnel | 6 light terms
+
+// ---- art controls ----
+const vec3 SUN_DIR = normalize(vec3(0.2, 0.14, -1.0)); // low sun ahead of the camera, a little to the right
+const float SUN_INTENSITY = 20.0;
+const float WIND_ANGLE = 1.9; // direction the waves travel, radians from +X toward +Z (camera looks down -Z)
+const float SWELL_LENGTH = 34.0; // longest wavelength, meters
+const float SWELL_HEIGHT = 0.8; // amplitude of the longest wave, meters
+const float CHOP = 0.7; // amplitude ratio between successive waves: higher = choppier
+const float CREST_SHARPNESS = 2.4; // 1 rolling swell .. 3 peaky crests
+const float RIPPLE = 0.008; // capillary ripple amplitude, meters
+const float FOAM_AMOUNT = 1.0;
+const vec3 WATER_DEEP = vec3(0.004, 0.02, 0.04); // linear albedo of the deep body
+const vec3 WATER_GLOW = vec3(0.05, 0.26, 0.25); // color of sunlight scattered through thin crests
+const float HAZE = 6.0; // aerial perspective strength (multiplies sea-level air extinction)
+const float CAMERA_HEIGHT = 3.0; // meters above mean sea level
+const float EXPOSURE = 0.9;
+const float FOCAL = 2.0;
+
+const float GRAVITY = 9.81;
+const float WAVELENGTH_RATIO = 0.8; // wavelength ratio between successive waves
+const int TRACE_WAVES = 12; // waves in the traced surface
+const int SHADE_WAVES = 28; // waves in the shading normal (adds fine chop)
+const int FOAM_WAVES = 6; // waves whose crests make foam
+const float TRACE_FAR = 400.0; // beyond this, intersect the mean plane and rely on filtering
+
+// Wave i of the sum: unit direction, wavenumber, amplitude and phase. Wavelengths fall geometrically from the swell;
+// long waves run with the wind, short chop spreads wider around it.
+void wave(int i, out vec2 dir, out float k, out float amp, out float phase) {
+ float fi = float(i);
+ vec3 h = hash32(vec2(fi, 17.0));
+ float a = WIND_ANGLE + mix(0.35, 1.3, min(fi / 12.0, 1.0)) * (2.0 * h.x - 1.0);
+ dir = vec2(cos(a), sin(a));
+ k = TAU / (SWELL_LENGTH * pow(WAVELENGTH_RATIO, fi) * mix(0.85, 1.15, h.y));
+ amp = SWELL_HEIGHT * pow(CHOP, fi);
+ phase = TAU * h.z;
+}
+
+// Deep-water dispersion: a wave of wavenumber k moves at angular frequency sqrt(g k), so long swell outruns chop.
+float wavePhase(vec2 dir, float k, float phase, vec2 xz) {
+ return k * dot(dir, xz) - sqrt(GRAVITY * k) * iTime + phase;
+}
+
+// How much of a wave survives filtering: 1 while its wavelength spans 6+ pixel footprints, 0 below 2.
+// A pixel covers an ellipse on the water: fp.zw = its size across and along the view, fp.xy = the unit view
+// direction projected on the water. At grazing angles it is far longer along the view, which is where waves alias.
+float waveKeep(vec2 dir, float k, vec4 fp) {
+ float footprint = length(vec2(dot(dir, vec2(-fp.y, fp.x)) * fp.z, dot(dir, fp.xy) * fp.w));
+ return smoothstep(2.0, 6.0, TAU / (k * footprint));
+}
+
+// Exp-sine profile: sharp crests, broad troughs. exp(s (sin - 1)) - 0.3 keeps the mean level near 0.
+// Waves too small for the footprint are faded out, so distant geometry does not alias into streaks.
+float oceanHeight(vec2 xz, int count, vec4 fp) {
+ float h = 0.0;
+ for (int i = ZERO; i < SHADE_WAVES; i++) {
+ if (i >= count) break;
+ vec2 dir; float k, amp, phase;
+ wave(i, dir, k, amp, phase);
+ h += waveKeep(dir, k, fp) * amp * (exp(CREST_SHARPNESS * (sin(wavePhase(dir, k, phase, xz)) - 1.0)) - 0.3);
+ }
+ return h;
+}
+
+// Steepest slope one wave of amplitude a and wavenumber k can reach: a k max|s cos(t) e^(s (sin(t) - 1))|.
+float profileMaxSlope() {
+ float s = CREST_SHARPNESS;
+ float sn = (sqrt(1.0 + 4.0 * s * s) - 1.0) / (2.0 * s);
+ return s * sqrt(1.0 - sn * sn) * exp(s * (sn - 1.0));
+}
+
+// Bounds of the traced surface: vec3(lowest height, highest height, steepest slope).
+vec3 oceanBounds() {
+ float ampSum = 0.0, slopeSum = 0.0;
+ for (int i = ZERO; i < TRACE_WAVES; i++) {
+ vec2 dir; float k, amp, phase;
+ wave(i, dir, k, amp, phase);
+ ampSum += amp;
+ slopeSum += amp * k;
+ }
+ return vec3(-0.3 * ampSum, 0.7 * ampSum, slopeSum * profileMaxSlope());
+}
+
+// Ray vs the traced wave surface. The surface lies inside the slab bounds.x <= y <= bounds.y, so clip the ray to it,
+// then step by the height gap over the fastest rate the gap can close (the ray's descent plus the steepest slope times
+// its horizontal speed). The slope bound is relaxed by 0.6 for speed; a secant step refines the crossing.
+// Returns vec2(t, steps); t < 0 when the ray reaches TRACE_FAR first.
+vec2 traceOcean(vec3 ro, vec3 rd, vec3 bounds, vec4 pixelSpread) {
+ if (rd.y >= 0.0) return vec2(-1.0, 0.0);
+ float t = max((ro.y - bounds.y) / -rd.y, 0.0);
+ float tEnd = min((ro.y - bounds.x) / -rd.y, TRACE_FAR);
+ float closing = -rd.y + 0.6 * bounds.z * length(rd.xz);
+ float tPrev = t, gapPrev = 1e10;
+ for (int i = ZERO; i < 200; i++) {
+ vec3 p = ro + rd * t;
+ float gap = p.y - oceanHeight(p.xz, TRACE_WAVES, pixelSpread * vec4(1.0, 1.0, t, t));
+ if (gap < 0.0) return vec2(mix(tPrev, t, gapPrev / (gapPrev - gap)), float(i));
+ if (t >= tEnd) break;
+ tPrev = t;
+ gapPrev = gap;
+ t = min(t + max(gap / closing, 0.004 * t), tEnd);
+ }
+ return vec2(-1.0, 200.0);
+}
+
+// Shading detail at xz: height, slope and Laplacian of all SHADE_WAVES, each wave faded out as its wavelength nears
+// the pixel footprint. Returns vec4(height, dh/dx, dh/dz, laplacian). lostSlope2 collects the slope variance of the
+// faded waves (it becomes roughness); crest is the convexity of the big waves, 1 where all their crests meet (foam).
+vec4 oceanDetail(vec2 xz, vec4 fp, out float lostSlope2, out float crest) {
+ const float slopeRms = 0.3 + 0.06 * CREST_SHARPNESS; // RMS of the profile's slope per unit a k
+ vec4 s = vec4(0.0);
+ lostSlope2 = 0.0;
+ crest = 0.0;
+ float crestMax = 0.0;
+ for (int i = ZERO; i < SHADE_WAVES; i++) {
+ vec2 dir; float k, amp, phase;
+ wave(i, dir, k, amp, phase);
+ float keep = waveKeep(dir, k, fp);
+ float theta = wavePhase(dir, k, phase, xz);
+ float sn = sin(theta), cs = cos(theta);
+ float e = exp(CREST_SHARPNESS * (sn - 1.0));
+ float d1 = CREST_SHARPNESS * cs * e; // dW/dtheta
+ float d2 = CREST_SHARPNESS * (CREST_SHARPNESS * cs * cs - sn) * e; // d2W/dtheta2
+ s += keep * amp * vec4(e - 0.3, k * d1 * dir, k * k * d2);
+ lostSlope2 += (1.0 - keep) * (amp * k * slopeRms) * (amp * k * slopeRms);
+ if (i < FOAM_WAVES) {
+ crest -= keep * amp * k * k * d2;
+ crestMax += amp * k * k * CREST_SHARPNESS; // a crest's curvature: -W'' = s at the top
+ }
+ }
+ crest /= crestMax;
+ return s;
+}
+
+// Transmittance from a point at heightKm toward dir, through the atmosphere (colors the sunlight).
+vec3 sunTransmittance(float heightKm, vec3 dir) {
+ vec3 ro = vec3(0.0, ATMOSPHERE_GROUND_KM + heightKm, 0.0);
+ if (iSphere(ro, dir, vec3(0.0), ATMOSPHERE_GROUND_KM).x > 0.0) return vec3(0.0);
+ float tl = iSphere(ro, dir, vec3(0.0), ATMOSPHERE_TOP_KM).y;
+ vec3 depth = vec3(0.0);
+ for (int i = 0; i < 12; i++) {
+ vec3 q = ro + dir * ((float(i) + 0.5) * tl / 12.0);
+ depth += atmosphereExtinction(atmosphereDensity(length(q) - ATMOSPHERE_GROUND_KM)) * tl / 12.0;
+ }
+ return exp(-depth);
+}
+
+vec3 render(vec2 fragCoord) {
+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
+ float pixelAngle = 2.0 / (iResolution.y * FOCAL);
+ float viewKm = CAMERA_HEIGHT * 0.001;
+
+#if DEBUG_MODE == 1
+ return vec3(0.5 + 0.5 * oceanHeight(uv * 30.0, SHADE_WAVES, vec4(1.0, 0.0, 1e-4, 1e-4)) / SWELL_HEIGHT);
+#endif
+
+ vec3 ro = vec3(0.0, CAMERA_HEIGHT, 0.0);
+ mat3 cam = cameraMatrix(ro, ro + vec3(0.0, -0.06, -1.0), 0.0);
+ vec3 rd = cameraRay(cam, uv, FOCAL);
+
+ vec3 sunColor = SUN_INTENSITY * 0.12 * sunTransmittance(viewKm, SUN_DIR);
+ if (rd.y >= 0.0) {
+ vec3 sky = atmosphereSky(rd, SUN_DIR, viewKm, SUN_INTENSITY);
+ return sky + sunColor * 40.0 * sunDisk(rd, SUN_DIR, 0.012, pixelAngle);
+ }
+
+ // pixel footprint on the water per meter of distance: pixelAngle across the view, stretched by 1/sin(grazing
+ // angle) along it
+ vec4 pixelSpread = vec4(normalize(rd.xz), pixelAngle, pixelAngle / max(-rd.y, 0.01));
+ vec3 bounds = oceanBounds();
+ vec2 hit = traceOcean(ro, rd, bounds, pixelSpread);
+#if DEBUG_MODE == 4
+ return debugHeat(hit.y / 200.0);
+#endif
+ // past TRACE_FAR the waves are below pixel size anyway: use the mean plane and let filtering do the rest
+ float t = (hit.x > 0.0) ? hit.x : ro.y / -rd.y;
+ vec3 p = ro + rd * t;
+
+ vec4 fp = pixelSpread * vec4(1.0, 1.0, t, t);
+ float lostSlope2, crest;
+ vec4 wv = oceanDetail(p.xz, fp, lostSlope2, crest);
+ vec2 slope = wv.yz;
+
+ // capillary ripples: two octaves of simplex flow noise whose gradients spin, so they churn instead of sliding
+ float footprint = sqrt(fp.z * fp.w); // ripples are isotropic: use the ellipse's mean size
+ float keepRipple = smoothstep(2.0, 6.0, 0.8 / footprint);
+ vec3 r1 = simplexNoiseD(p.xz * 1.3 + vec2(0.3, 0.9) * iTime, 1.3 * iTime);
+ vec3 r2 = simplexNoiseD(p.xz * 3.7 - vec2(0.6, 0.2) * iTime, -2.1 * iTime);
+ slope += RIPPLE * keepRipple * (1.3 * r1.yz + 0.5 * 3.7 * r2.yz * smoothstep(2.0, 6.0, 0.3 / footprint));
+ lostSlope2 += RIPPLE * RIPPLE * 4.0 * (1.0 - keepRipple);
+ vec3 n = normalize(vec3(-slope.x, 1.0, -slope.y));
+
+ // foam: the convexity of the big waves' crests sets how much of a billow-noise lace is covered, so patches
+ // grow from crisp filaments on mild crests to solid caps on the sharpest ones
+ float lace = billowFbm(p.xz * vec2(1.2, 2.4) + vec2(0.0, 0.5 * iTime), 6);
+ float coverage = 0.7 * smoothstep(0.08, 0.3, crest); // below 1, so even the sharpest caps stay broken
+ float foam = FOAM_AMOUNT * coverage * smoothstep(1.0 - coverage, 1.15 - coverage, lace);
+ // inside a patch, foam is a network of bubbles: dense along Voronoi borders, thin inside the cells
+ float bubbles = smoothstep(0.22, 0.0, voronoiBorder(p.xz * vec2(2.5, 4.0), 1.0).x);
+ foam *= mix(0.75, mix(0.4, 1.0, bubbles), smoothstep(2.0, 6.0, 0.3 / footprint));
+
+ vec3 v = -rd;
+ float NoV = max(dot(n, v), 1e-3);
+ vec3 F = fresnelSchlick(NoV, vec3(0.02));
+ vec3 refl = reflect(rd, n);
+ refl.y = abs(refl.y); // a reflection into the water would hit the next wave: fold it back to the sky
+ vec3 skyRefl = atmosphereSky(refl, SUN_DIR, viewKm, SUN_INTENSITY);
+ vec3 skyAmbient = atmosphereSky(vec3(0.0, 1.0, 0.0), SUN_DIR, viewKm, SUN_INTENSITY);
+
+ // sun glint: GGX whose roughness absorbs the slope variance of the waves filtered away at this distance
+ float alpha = sqrt(0.02 * 0.02 + 2.0 * lostSlope2);
+ vec3 glint = specularGGX(n, v, SUN_DIR, sqrt(alpha), vec3(0.02)) * sunColor;
+ vec3 reflection = F * skyRefl;
+
+ // body: refracted light scattered back out, plus sunlight glowing through thin crests seen against the sun
+ float backlit = pow(clamp(dot(rd, SUN_DIR), 0.0, 1.0), 4.0);
+ float thin = smoothstep(0.45, 0.9, (wv.x - bounds.x) / (bounds.y - bounds.x)); // crest tops only
+ vec3 body = (1.0 - F) * (WATER_DEEP * (skyAmbient + sunColor * max(dot(n, SUN_DIR), 0.0))
+ + WATER_GLOW * sunColor * backlit * thin);
+
+ // foam is a thin white scatterer: diffuse sun and sky light, plus sunlight shining through it from behind
+ vec3 foamColor = vec3(0.9) * (sunColor * (max(dot(n, SUN_DIR), 0.0) + 0.5 * backlit) + 3.0 * skyAmbient);
+
+#if DEBUG_MODE == 2
+ return debugNormal(n);
+#elif DEBUG_MODE == 3
+ return vec3(foam, clamp(crest, 0.0, 1.0), lace);
+#elif DEBUG_MODE == 5
+ return sqrt(F);
+#elif DEBUG_MODE == 6
+ return vec3(luminance(reflection), luminance(glint) * 0.1, luminance(body) * 10.0);
+#endif
+
+ vec3 col = mix(reflection + glint + body, foamColor, foam);
+ // aerial perspective, with the haze color taken from the sky just above the horizon so the two meet without a seam
+ vec3 fogColor = atmosphereSky(normalize(vec3(rd.x, 0.0, rd.z)), SUN_DIR, viewKm, SUN_INTENSITY);
+ vec3 airT = exp(-t * 0.001 * HAZE * atmosphereExtinction(atmosphereDensity(0.0)));
+ return col * airT + fogColor * (1.0 - airT);
+}
+
+void mainImage(out vec4 fragColor, in vec2 fragCoord) {
+ vec3 col = render(fragCoord);
+#if DEBUG_MODE == 0
+ col = linearToSrgb(tonemapAgXPunchy(col * EXPOSURE)) + ditherTPDF(fragCoord, iFrame);
+#endif
+ fragColor = vec4(col, 1.0);
+}
diff --git a/tests/properties.py b/tests/properties.py
index 00c55d3..eca75d6 100644
--- a/tests/properties.py
+++ b/tests/properties.py
@@ -76,13 +76,52 @@ SDF2 = [
("sdQuadraticBezier 2D straight", "sdQuadraticBezier(p, vec2(-0.6, -0.3), vec2(0.0, 0.0), vec2(0.6, 0.3)) - 0.05", 1.2, ["0,0"], ["0,0.3"]),
("hexEdgeDistance", "-hexEdgeDistance(hexGrid(p * 3.0).xy) / 3.0", 1.2, [], []),
("truchetArcs", "truchetArcs(p * 3.0, 0.1) / 3.0", 1.2, [], []),
+ ("sdPie", "sdPie(p, vec2(sin(0.9), cos(0.9)), 0.7)", 1.2, ["0,0.3", "0.3,0.4"], ["0,-0.1", "0,0.75", "0.6,0"]),
+ ("sdPie concave", "sdPie(p, vec2(sin(2.4), cos(2.4)), 0.7)", 1.2, ["0,0.3", "0.5,0", "0.3,-0.2"], ["0,-0.3", "0,0.75"]),
+ ("sdHorseshoe", "sdHorseshoe(p, vec2(sin(2.0), cos(2.0)), 0.5, 0.3, 0.08)", 1.2, ["0,0.5", "0.39,-0.345"],
+ ["0,0", "0,-0.5", "0,0.65"]),
+ ("sdParabolaSegment", "sdParabolaSegment(p, 0.7, 0.9)", 1.2, ["0,0.1", "0,0.85", "0.5,0.2"], ["0,-0.05", "0,0.95", "0.65,0.3"]),
+ ("sdParabolaSegment flat", "sdParabolaSegment(p, 0.9, 0.25)", 1.2, ["0,0.1", "0.6,0.1"], ["0,0.3", "0,-0.1", "0.85,0.05"]),
+ ("sdParabolaSegment tall", "sdParabolaSegment(p, 0.3, 1.0)", 1.2, ["0,0.5", "0.1,0.8"], ["0.25,0.5", "0,1.05"]),
+ ("sdParabolaSegment boundary", "abs(sdParabolaSegment(p, 0.7, 0.9))", 1.2, [], []),
+ ("sdParabolaSegment tall boundary", "abs(sdParabolaSegment(p, 0.3, 1.0))", 1.2, [], []),
+ ("sdEgg", "sdEgg(p, 0.5, 0.2)", 1.2, ["0,0", "0,0.75", "0.45,0"], ["0,-0.55", "0,0.85", "0.52,0", "0.45,0.5"]),
+ ("sdEgg pointed", "sdEgg(p, 0.5, 0.02)", 1.2, ["0,0.8", "0,-0.45"], ["0,0.9", "0.2,0.8"]),
+ ("sdEgg boundary", "abs(sdEgg(p, 0.5, 0.2))", 1.2, [], []),
]
+
+def _parabola_boundary(w: float, h: float) -> str:
+ """Closed boundary of sdParabolaSegment(p, w, h): the arc for t < 0.8 (denser, it is longer), then the base."""
+ x = f"mix({-w}, {w}, t / 0.8)"
+ return (f"t < 0.8 ? vec2({x}, {h} - {h / (w * w):.6f} * {x} * {x}) "
+ f": vec2(mix({-w}, {w}, (t - 0.8) / 0.2), 0.0)")
+
+
+def _egg_boundary(ra: float, rb: float) -> str:
+ """Closed boundary of sdEgg(p, ra, rb): bottom arc, side arc, cap on the right half (split by arc length),
+ mirrored for t >= 0.5."""
+ import math
+ c = math.sqrt((2 * ra - rb) ** 2 - ra * ra)
+ th = math.atan2(c, ra)
+ lens = [ra * math.pi / 2, 2 * ra * th, rb * (math.pi / 2 - th)]
+ s1, s2 = lens[0] / sum(lens), (lens[0] + lens[1]) / sum(lens)
+ s = "fract(2.0 * t)"
+ arc = lambda cx, cy, r, a0, a1, lo, hi: (
+ f"vec2({cx}, {cy:.7f}) + {r} * vec2(cos({a0:.7f} + {a1 - a0:.7f} * ({s} - {lo:.6f}) / {hi - lo:.6f}), "
+ f"sin({a0:.7f} + {a1 - a0:.7f} * ({s} - {lo:.6f}) / {hi - lo:.6f}))")
+ return (f"vec2(t < 0.5 ? 1.0 : -1.0, 1.0) * ({s} < {s1:.6f} ? {arc(0.0, 0.0, ra, -math.pi / 2, 0.0, 0.0, s1)} "
+ f": {s} < {s2:.6f} ? {arc(-ra, 0.0, 2 * ra, 0.0, th, s1, s2)} "
+ f": {arc(0.0, c, rb, th, math.pi / 2, s2, 1.0)})")
+
# Curves checked against brute-force sampling (bit 8): name -> (expr of p, point on curve at parameter t).
BRUTE = {
"sdQuadraticBezier 2D": ("vec2", "mix(mix(vec2(-0.7, -0.3), vec2(0.0, 0.9), t), mix(vec2(0.0, 0.9), vec2(0.6, -0.4), t), t)", 0.05),
"sdQuadraticBezier 2D straight": ("vec2", "mix(vec2(-0.6, -0.3), vec2(0.6, 0.3), t)", 0.05),
"sdQuadraticBezier 3D": ("vec3", "mix(mix(vec3(-0.6, -0.3, 0.1), vec3(0.0, 0.9, -0.3), t), mix(vec3(0.0, 0.9, -0.3), vec3(0.6, -0.2, 0.2), t), t)", 0.1),
+ "sdParabolaSegment boundary": ("vec2", _parabola_boundary(0.7, 0.9), 0.0),
+ "sdParabolaSegment tall boundary": ("vec2", _parabola_boundary(0.3, 1.0), 0.0),
+ "sdEgg boundary": ("vec2", _egg_boundary(0.5, 0.2), 0.0),
}
# Allowed failure rates for the exactness bit (medial-axis noise). Everything else must be 0.
@@ -127,6 +166,53 @@ PROPERTIES = [
float div = (curlNoise(p + vec2(e, 0.0)).x - curlNoise(p - vec2(e, 0.0)).x
+ curlNoise(p + vec2(0.0, e)).y - curlNoise(p - vec2(0.0, e)).y) / (2.0 * e);
return abs(div) > 0.05 ? 1 : 0;""", {}),
+ ("simplexNoiseD derivative matches finite difference, |value| <= 1", """
+ vec2 p = (a.xy - 0.5) * 40.0;
+ float rot = TAU * b.x;
+ vec3 n = simplexNoiseD(p, rot);
+ float e = 1e-3;
+ vec2 fd = vec2(simplexNoiseD(p + vec2(e, 0.0), rot).x - simplexNoiseD(p - vec2(e, 0.0), rot).x,
+ simplexNoiseD(p + vec2(0.0, e), rot).x - simplexNoiseD(p - vec2(0.0, e), rot).x) / (2.0 * e);
+ int f = 0;
+ if (length(n.yz - fd) > 0.02 * (1.0 + length(fd))) f |= 1;
+ if (isnan(n.x) || abs(n.x) > 1.0) f |= 2;
+ if (simplexNoise(p) != simplexNoiseD(p, 0.0).x) f |= 4;
+ return f;""", {}),
+ ("gradientNoiseD 3D matches gradientNoise and finite differences", """
+ vec3 p = (a.xyz - 0.5) * 30.0;
+ vec4 n = gradientNoiseD(p);
+ float e = 1e-3;
+ vec3 fd = vec3(gradientNoise(p + vec3(e, 0.0, 0.0)) - gradientNoise(p - vec3(e, 0.0, 0.0)),
+ gradientNoise(p + vec3(0.0, e, 0.0)) - gradientNoise(p - vec3(0.0, e, 0.0)),
+ gradientNoise(p + vec3(0.0, 0.0, e)) - gradientNoise(p - vec3(0.0, 0.0, e))) / (2.0 * e);
+ int f = 0;
+ if (abs(n.x - gradientNoise(p)) > 1e-5) f |= 1;
+ if (length(n.yzw - fd) > 0.02 * (1.0 + length(fd))) f |= 2;
+ return f;""", {}),
+ ("curlNoise 3D is divergence-free", """
+ vec3 p = (a.xyz - 0.5) * 20.0;
+ float e = 2e-3;
+ vec3 dx = curlNoise(p + vec3(e, 0.0, 0.0)) - curlNoise(p - vec3(e, 0.0, 0.0));
+ vec3 dy = curlNoise(p + vec3(0.0, e, 0.0)) - curlNoise(p - vec3(0.0, e, 0.0));
+ vec3 dz = curlNoise(p + vec3(0.0, 0.0, e)) - curlNoise(p - vec3(0.0, 0.0, e));
+ float div = (dx.x + dy.y + dz.z) / (2.0 * e);
+ float scale = (abs(dx.x) + abs(dy.y) + abs(dz.z)) / (2.0 * e); // what a non-solenoidal field would show
+ vec3 c = curlNoise(p);
+ int f = 0;
+ if (abs(div) > 0.01 * scale + 0.02) f |= 1;
+ if (isnan(c.x + c.y + c.z) || length(c) > 20.0) f |= 2;
+ return f;""", {}),
+ ("turbulence and billowFbm stay in [0,1]", """
+ vec2 p = (a.xy - 0.5) * 100.0;
+ vec3 q = (b.xyz - 0.5) * 40.0;
+ float t2 = turbulence(p, 6), t3 = turbulence(q, 5);
+ float b2 = billowFbm(p, 6), b3 = billowFbm(q, 5);
+ int f = 0;
+ if (isnan(t2) || t2 < 0.0 || t2 > 1.0) f |= 1;
+ if (isnan(t3) || t3 < 0.0 || t3 > 1.0) f |= 2;
+ if (isnan(b2) || b2 < 0.0 || b2 > 1.0) f |= 4;
+ if (isnan(b3) || b3 < 0.0 || b3 > 1.0) f |= 8;
+ return f;""", {}),
("noise and fbm ranges", """
vec2 p = (a.xy - 0.5) * 200.0;
vec3 q = (a.xyz - 0.5) * 50.0;
@@ -174,6 +260,28 @@ PROPERTIES = [
vec2 r = domRepeat(p, vec2(0.7));
if (any(greaterThan(abs(r), vec2(0.35 + 1e-4)))) f |= 8;
return f;""", {}),
+ ("domPolarPair matches a search over every sector", """
+ vec2 p = (a.xy - 0.5) * 2.4;
+ const float n = 7.0;
+ float best = 1e10; // tilted petals of varying length, one per sector
+ for (int k = 0; k < 7; k++) {
+ vec2 q = rot2(-0.35) * (domPolarSector(p, float(k), n) - vec2(0.2, 0.0));
+ best = min(best, sdUnevenCapsule(q.yx, 0.06, 0.02, 0.3 + 0.35 * hash11(float(k))));
+ }
+ vec2 ids = domPolarPair(p, n);
+ float pair = 1e10;
+ for (int i = 0; i < 2; i++) {
+ float k = (i == 0) ? ids.x : ids.y;
+ vec2 q = rot2(-0.35) * (domPolarSector(p, k, n) - vec2(0.2, 0.0));
+ pair = min(pair, sdUnevenCapsule(q.yx, 0.06, 0.02, 0.3 + 0.35 * hash11(k)));
+ }
+ float gap = mod(ids.y - ids.x + n, n);
+ int f = 0;
+ if (abs(pair - best) > 1e-6) f |= 1;
+ if (ids.x != domPolarId(p, n)) f |= 2;
+ if (length(domPolarSector(p, ids.x, n) - domPolar(p, n)) > 1e-4) f |= 4;
+ if (gap != 1.0 && gap != n - 1.0) f |= 8;
+ return f;""", {}),
("intersectors agree with SDFs", """
vec3 ro = (a.xyz - 0.5) * 6.0;
vec3 rd = normalize(b.xyz - 0.5 + 1e-4);