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.
Python agent-skillsclaude-codecodexcomputer-graphicscursorgemini-cligenerative-artgithub-copilotglslnoiseprocedural-artprocedural-generationraymarchingshadersshadertoysigned-distance-functionsterrain-generationwebglwebgl2
Add procedural buildings, alpine terrain, and high-quality water workflows (#2)
Gökay Aydoğanb19dcf95591f
diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.ymlindex b8176a0..71412e1 100644--- a/.github/workflows/checks.yml+++ b/.github/workflows/checks.yml@@ -24,6 +24,8 @@ jobs:run: python3 skills/shader-art-coding/scripts/glsl_tools.py check- name: Eval suite matches the plugin-eval formatrun: python3 tests/check_evals.py+ - name: Bundler regressions+ run: python3 -m unittest discover -s tests -p 'test_*.py'webgl:name: WebGL2 compile, GPU property tests, rendersdiff --git a/CREDITS.md b/CREDITS.mdindex c8d8750..d317ee0 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -38,3 +38,9 @@ default to CC BY-NC-SA 3.0, which is incompatible with MIT.| 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 |+| Procedural building massing hierarchy | [Müller et al., Procedural Modeling of Buildings, SIGGRAPH 2006](https://doi.org/10.1145/1141911.1141931); [SIGGRAPH 2011 urban modeling course](https://www.cs.purdue.edu/cgvlab/urban/sg_2011_course/contents.html) | concepts reimplemented; not a CGA engine or copied grammar/code |+| Filtered facade window coverage | Quilez, filterable procedurals / analytic footprint integration | original periodic rectangle integral; no source copied |+| Terrain representation and density/meshing distinction | [Geiss, GPU Gems 3 chapter 1](https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-1-generating-complex-procedural-terrains-using-gpu) | explanatory source; local heightfield shaders do not implement the chapter's meshing pipeline |+| Finite-depth gravity-wave dispersion | [MIT Marine Hydrodynamics lecture 20](https://ocw.mit.edu/courses/2-20-marine-hydrodynamics-13-021-spring-2005/5d48a5937971d973fd8ca90c051a83f8_lecture20.pdf) | mathematical relation, original implementation |+| Exact dielectric Fresnel and Beer-Lambert attenuation | [PBRT reflection/transmission](https://www.pbr-book.org/4ed/Reflection_Models/Specular_Reflection_and_Transmission), [transmittance](https://www.pbr-book.org/4ed/Volume_Scattering/Transmittance) | equations reimplemented; no PBRT source copied |+| Coastal refraction pipeline comparison | [GPU Gems 2 chapter 19, Generic Refraction Simulation](https://developer.nvidia.com/gpugems/gpugems2/part-ii-shading-lighting-and-shadows/chapter-19-generic-refraction-simulation) | reference for scene-buffer alternatives; local coastal shader traces a procedural heightfield instead |diff --git a/README.md b/README.mdindex 3205913..575029d 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 lookintentional. It works with Claude Code, Codex, Cursor, Copilot, Gemini and others. It pairs a shader-craft-workflow with a **verified GLSL building-block library**: 180 functions across 18 modules, each one compiled in+workflow with a **verified GLSL building-block library**: 186 functions across 20 modules, each one compiled inWebGL2 and numerically tested on the GPU. A bundler inlines exactly the functions a shader uses, so the resultpastes straight into Shadertoy.@@ -96,8 +96,10 @@ What the commands do:| `sdf2d` | 16 primitives including vesica, moon, heart, star, regular polygon, rounded box with per-corner radii, quadratic Bézier || `operators` | smooth min/max/subtract (quadratic and C2 cubic), smooth union with material blend weight, chamfer, stairs, engrave, round, onion, extrude, revolve, exact elongate || `domain` | repetition (infinite, limited, mirrored), polar sectors, folds, twist and bend with their Lipschitz corrections |+| `architecture` | stable parcel-based building dimensions/roof IDs, box-filtered facade windows that converge to opening area || `raymarch` | sphere tracing with distance-relative hit threshold, tetrahedral normals, improved soft shadows, AO, thickness; WebGL-safe loops || `shading` | GGX + height-correlated Smith + Schlick, metallic-roughness `shadePBR`, environment BRDF approximation, wrap diffuse, translucency, rim |+| `water` | finite-depth dispersion, analytic wave height/slope/curvature, exact dielectric Fresnel including TIR, RGB Beer-Lambert attenuation || `color` / `tonemap` | exact sRGB curves, Oklab / OkLCh mixing, blackbody colors; AgX (default), AgX punchy, Khronos PBR Neutral, ACES fitted, Reinhard || `volume` / `atmosphere` | HG, dual-lobe, Rayleigh and Cornette-Shanks phase, energy-conserving `volumeStep`, Beer-Powder, analytic height fog; physically based single-scattering sky, sun disk with limb darkening || `camera` / `intersect` / `post` / `debug` | look-at, thin-lens DOF, ortho; analytic sphere/box/plane hits; AA helpers, R2 supersampling offsets, cos⁴ vignette, grain, TPDF dither; distance, normal, id and heat debug views |@@ -137,15 +139,41 @@ Click a preview for the standalone Shadertoy shader. Editable sources:[`noise-progression.glsl`](skills/shader-art-coding/templates/noise-progression.glsl) and[`noise-terrain-map.glsl`](skills/shader-art-coding/templates/noise-terrain-map.glsl).+## Procedural buildings, terrain and water++Three complete, texture-free starting points cover construction, landscape and shallow-water optics. Each has+art controls, inspectable debug modes, a standalone Shadertoy bundle and a rendered preview.++| [](gallery/procedural-city.glsl) | [](gallery/alpine-valley.glsl) | [](gallery/coastal-water.glsl) |+|---|---|---|+| Parcel-based masses, podiums/setbacks, varied roofs, filtered occupied windows, AO, shadows and height fog. | Designed valley, eroded/ridged terrain, snow by slope/altitude, rock strata, grass and atmospheric depth. | Analytic waves, refracted seabed, reflected land, exact Fresnel, RGB depth absorption, shore foam and three quality presets. |++- **[Procedural buildings](skills/shader-art-coding/references/procedural-buildings.md):** massing hierarchy,+ deterministic parcels, neighbor-safe repetition, facade filtering, geometry versus material detail, and mesh/engine integration.+- **[Terrain production](skills/shader-art-coding/references/terrain-production.md):** heightfields versus density,+ silhouette/detail separation, primary-trace refinement, biome masks, chunk coordinates, seams and LOD.+- **[Water quality](skills/shader-art-coding/references/water-quality.md):** shallow coast versus open ocean,+ reflection/refraction paths, finite-depth waves, filtering, quality presets, and the extra renderer/simulation+ systems needed for film or production water. The existing [open-ocean shader](gallery/ocean.glsl) remains available.++The coastal example uses `QUALITY` 1/2/3 for sky reflection, reflected-land rays, and a four-sample still preset+with more waves/steps. It is a single-pass visual study: foam, in-scattering and caustics include artistic+approximations; it does not simulate breaking surf or FFT ocean spectra. The guides identify implemented features+and limits rather than promising a universal “highest quality” or frame rate.++Sources are in [`templates/`](skills/shader-art-coding/templates/). Bundle with `glsl_tools.py bundle` as above.+All three water presets and every annotated diagnostic view are compiled and rendered by the harness.+## Verification| Check | Where | What it proves ||---|---|---|| 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 160 units compile under ANGLE, which also enforces WebGL-only rules |-| GPU property tests | `tests/properties.py` | 85 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/` |+| WebGL2 compile | `tests/` harness | all library/reference/template units and annotated quality/debug variants compile under ANGLE, which also enforces WebGL-only rules |+| GPU property tests | `tests/properties.py` | 90 tests × 16,384 samples: Lipschitz, exactness, signs, brute-force curve distance, derivatives, divergence, ranges, round trips, facade filtering, water dispersion/Fresnel/attenuation |+| Renders | harness + gallery | 11 beauty templates plus 16 quality/debug variants; no NaNs or black frames; beauty PNGs saved to `gallery/` |+| Bundler regressions | `tests/test_bundler.py` | conditional quality macros cannot hide dependencies; annotated variants replace the intended define and reject missing defines || Skill effect | `evals/` (`claude plugin eval`, paid, manual) | output-rule adherence with the skill vs without it on 6 shader tasks, plus no false triggers on 3 near-miss tasks; see [evals/README.md](evals/README.md) |Run it locally: `python3 tests/build_harness.py && python3 tests/serve.py`, then opendiff --git a/gallery/alpine-valley.glsl b/gallery/alpine-valley.glslnew file mode 100644index 0000000..8365c15--- /dev/null+++ b/gallery/alpine-valley.glsl@@ -0,0 +1,440 @@+// Alpine valley: designed lowland corridor, multiscale ridges, snow accumulation, strata and aerial depth.+// A heightfield cannot make overhangs. The controlled valley is not a drainage/erosion simulation.+// @render time=0.0+// @variant DEBUG_MODE=1+// @variant DEBUG_MODE=2+// @variant DEBUG_MODE=3+// @variant DEBUG_MODE=4+#define DEBUG_MODE 0 // 0 beauty | 1 elevation | 2 normal | 3 grass/rock/snow | 4 steps++// 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;++// ---- 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))))); }++// ---- 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; }+// 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;+// 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) {+ 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 * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return 1.4 * sum / norm;+}+// 2D fBm with the usual defaults (lacunarity 2.01 so octave peaks never re-align, persistence 0.5).+float fbm(vec2 p, int octaves) { return fbm(p, octaves, 2.01, 0.5); }+// fBm over 3D gradient noise.+float fbm(vec3 p, int octaves, float lacunarity, float persistence) {+ 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 * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);+ }+ return sum / norm;+}+// 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.+float erodedFbm(vec2 p, int octaves) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float h = 0.0, amp = 0.5;+ vec2 slope = vec2(0.0);+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ vec3 n = gradientNoiseD(p);+ slope += n.yz;+ h += amp * n.x / (1.0 + dot(slope, slope));+ amp *= 0.5;+ p = 2.0 * (octaveRotation * p);+ }+ return 2.0 * h;+}+// Ridged multifractal: inverted |noise| creates sharp crests; each octave is weighted by the previous one, so detail gathers along ridges.+float ridgedFbm(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 = 1.0 - abs(gradientNoise(p) * 1.4);+ n *= n;+ sum += amp * n * weight;+ norm += amp;+ weight = clamp(n * 2.0, 0.0, 1.0);+ amp *= 0.5;+ p = 2.01 * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return sum / norm;+}++// ---- shader-skills library: raymarch ----+#define ZERO (min(iFrame, 0))+vec2 map(vec3 p);+// Surface normal from 4 tetrahedral samples (cheaper than 6 central differences, and still centered). eps should scale with distance, e.g. 0.0005 * t: that filters distant detail and avoids sparkling.+vec3 calcNormal(vec3 p, float eps) {+ vec3 n = vec3(0.0);+ for (int i = ZERO; i < 4; i++) {+ vec3 e = 0.5773 * (2.0 * vec3((((i + 3) >> 1) & 1), ((i >> 1) & 1), (i & 1)) - 1.0);+ n += e * map(p + e * eps).x;+ }+ return normalize(n);+}+// Soft shadow toward a light along unit rd. k controls sharpness (k is about 1 / light angular size: 8 soft, 32 hard). Uses the "closest approach between samples" estimate, which removes banding from sharp-cornered occluders. Returns 0 (full shadow) .. 1 (lit).+float softShadow(vec3 ro, vec3 rd, float tmin, float tmax, float k) {+ float res = 1.0;+ float t = tmin;+ float ph = 1e10;+ for (int i = ZERO; i < 64; i++) {+ float h = map(ro + rd * t).x;+ if (h < 0.0001) return 0.0;+ float y = h * h / (2.0 * ph);+ float d = sqrt(max(h * h - y * y, 0.0));+ res = min(res, k * d / max(t - y, 1e-4));+ ph = h;+ t += clamp(h, 0.005, 0.5);+ if (res < 0.001 || t > tmax) break;+ }+ res = clamp(res, 0.0, 1.0);+ return res * res * (3.0 - 2.0 * res);+}++// ---- 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;+}+// Complete metallic-roughness shading for one light (diffuse + specular, NoL included, artist units). Multiply by light color and shadow. Keep albedo around 0.05-0.7 (linear); brighten lights, not albedo.+vec3 shadePBR(vec3 n, vec3 v, vec3 l, vec3 albedo, float roughness, float metallic) {+ vec3 f0 = mix(vec3(0.04), albedo, metallic);+ float NoL = clamp(dot(n, l), 0.0, 1.0);+ vec3 F = fresnelSchlick(max(dot(n, v), 0.0), f0);+ vec3 diffuse = albedo * (1.0 - metallic) * (1.0 - F) * NoL;+ return diffuse + specularGGX(n, v, l, roughness, f0);+}+// Hemisphere light: sky color from above blended to ground color from below.+vec3 hemisphereLight(vec3 n, vec3 skyColor, vec3 groundColor) {+ return mix(groundColor, skyColor, 0.5 + 0.5 * n.y);+}++// ---- 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));+}++// ---- shader-skills library: tonemap ----+// AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display. Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT).+vec3 tonemapAgX(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 = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++// ---- shader-skills library: volume ----+// Analytic height fog for density a * exp(-b * y) along the ray segment [0, t]. Thick near the ground, thin above. Returns the fog amount in [0,1].+float heightFog(vec3 ro, vec3 rd, float t, float a, float b) {+ float base = a * exp(-ro.y * b);+ float amount = (abs(rd.y) < 1e-4) ? base * t+ : base * (1.0 - exp(-t * rd.y * b)) / (rd.y * b);+ return 1.0 - exp(-max(amount, 0.0));+}++// ---- shader-skills library: atmosphere ----+// Cheap analytic sky: horizon-to-zenith gradient, darker ground below the horizon, sun glow lobes. Returns linear radiance (roughly 0-2; the glow can exceed 1 near the sun).+vec3 simpleSky(vec3 rd, vec3 sunDir) {+ float y = max(rd.y, 0.0);+ vec3 zenith = vec3(0.12, 0.28, 0.62);+ vec3 horizon = vec3(0.62, 0.74, 0.88);+ vec3 col = mix(horizon, zenith, pow(y, 0.5));+ col = mix(col, vec3(0.28, 0.26, 0.24), smoothstep(0.0, -0.08, rd.y));+ float mu = max(dot(rd, sunDir), 0.0);+ col += vec3(1.0, 0.75, 0.45) * (0.25 * pow(mu, 8.0) + 0.6 * pow(mu, 64.0) + 2.0 * pow(mu, 512.0));+ return col;+}++// ---- 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 ----+// 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 ----+const vec3 ALPINE_SUN=normalize(vec3(-0.65,0.42,-0.25));+const float SNOW_ALTITUDE=1.9;+const float FAR_DISTANCE=70.0;+const int ALPINE_TRACE_STEPS=320;++float alpineHeight(vec2 p) {+ float valley=1.0-exp(-0.085*p.x*p.x);+ float peaks=0.65+1.8*erodedFbm(p*vec2(0.30,0.25)+vec2(2.0,7.0),6)+ +0.35*ridgedFbm(p*0.2,4);+ float broad=0.5+0.5*fbm(p*0.12,4);+ float detail=0.06*fbm(p*1.8,3);+ return 0.18+(1.3+3.1*peaks+1.0*broad)*valley+detail;+}++vec2 map(vec3 p) {return vec2((p.y-alpineHeight(p.xz))*0.12,1.0);}++// Coarse-to-fine heightfield intersection. Distance-proportional sampling avoids the asymptotic+// slowdown of a small globally scaled gap near the horizon; crossings are refined by bisection.+vec3 traceAlpine(vec3 ro,vec3 rd) {+ float t=0.02,previous=0.0;+ for(int i=0;i<ALPINE_TRACE_STEPS;i++) {+ vec3 p=ro+rd*t;+ float gap=p.y-alpineHeight(p.xz);+ if(gap<0.0) {+ float lo=previous,hi=t;+ for(int j=0;j<10;j++) {+ float mid=0.5*(lo+hi);+ vec3 q=ro+rd*mid;+ if(q.y>alpineHeight(q.xz))lo=mid;else hi=mid;+ }+ return vec3(0.5*(lo+hi),1.0,float(i));+ }+ previous=t;+ t+=0.04+0.015*t;+ if(t>FAR_DISTANCE)break;+ }+ return vec3(-1.0,0.0,float(ALPINE_TRACE_STEPS));+}++vec3 alpineSky(vec3 rd) {+ vec3 c=simpleSky(rd,ALPINE_SUN);+ // A broad cloud mask in sky-direction space; it is not a cloud volume.+ float cloud=smoothstep(0.1,0.5,fbm(rd.xz/max(rd.y+0.45,0.15)*1.2,4));+ return mix(c,vec3(0.86,0.88,0.91),cloud*0.45*smoothstep(0.05,0.4,rd.y));+}++vec3 alpineRender(vec2 coord) {+ vec2 uv=(2.0*coord-iResolution.xy)/iResolution.y;+ vec3 ro=vec3(0.15,2.1,10.0-0.25*iTime);+ ro.y=max(ro.y,alpineHeight(ro.xz)+0.7);+ vec3 rd=cameraRay(cameraMatrix(ro,vec3(0.0,1.9,-15.0),0.0),uv,1.8);+ vec3 sky=alpineSky(rd);+ vec3 hit=traceAlpine(ro,rd);+#if DEBUG_MODE == 4+ return debugHeat(hit.z/float(ALPINE_TRACE_STEPS));+#endif+ if(hit.x<0.0)return sky;+ vec3 p=ro+rd*hit.x;+ float footprint=hit.x*2.0/(iResolution.y*1.8);+ vec3 n=calcNormal(p,max(0.002,footprint*0.5));+ float snow=smoothstep(SNOW_ALTITUDE-0.3,SNOW_ALTITUDE+0.4,p.y+0.22*fbm(p.xz*2.0,3))+ *smoothstep(0.35,0.75,n.y);+ float grass=smoothstep(0.6,0.9,n.y)*(1.0-smoothstep(1.4,2.5,p.y));+ float detailKeep=1.0-smoothstep(0.02,0.2,footprint);+ float grain=0.5+0.5*fbm(p.xz*18.0,3)*detailKeep;+ float strata=0.5+0.5*sin(p.y*35.0+fbm(p.xz*3.0,3)*2.0);+ vec3 rock=mix(vec3(0.16,0.15,0.14),vec3(0.32,0.29,0.25),grain)*(0.85+0.15*strata*detailKeep);+ vec3 albedo=mix(rock,mix(vec3(0.075,0.12,0.035),vec3(0.16,0.20,0.065),grain),grass);+ albedo=mix(albedo,vec3(0.78,0.84,0.9),snow);+ float shadow=softShadow(p+n*0.03,ALPINE_SUN,0.03,15.0,12.0);+ vec3 col=shadePBR(n,-rd,ALPINE_SUN,albedo,0.8,0.0)*vec3(3.4,3.0,2.5)*shadow;+ col+=albedo*hemisphereLight(n,vec3(0.4,0.58,0.85),vec3(0.16,0.13,0.095));+#if DEBUG_MODE == 1+ return vec3(p.y/6.0);+#elif DEBUG_MODE == 2+ return n*0.5+0.5;+#elif DEBUG_MODE == 3+ return vec3(grass,1.0-grass,snow);+#endif+ vec3 haze=alpineSky(normalize(vec3(rd.x,0.04,rd.z)));+ float fog=heightFog(ro,rd,hit.x,0.011,0.18);+ return mix(col,haze,fog);+}++void mainImage(out vec4 fragColor,in vec2 fragCoord) {+ vec3 col=alpineRender(fragCoord);+#if DEBUG_MODE == 0+ col=linearToSrgb(tonemapAgX(col*1.15))+ditherTPDF(fragCoord,iFrame);+#endif+ fragColor=vec4(col,1.0);+}diff --git a/gallery/alpine-valley.png b/gallery/alpine-valley.pngnew file mode 100644index 0000000..b2af4b4Binary files /dev/null and b/gallery/alpine-valley.png differdiff --git a/gallery/coastal-water.glsl b/gallery/coastal-water.glslnew file mode 100644index 0000000..b2a5eee--- /dev/null+++ b/gallery/coastal-water.glsl@@ -0,0 +1,480 @@+// Coastal water: analytic finite-depth waves, refracted seabed, reflected land, exact interface Fresnel,+// RGB Beer-Lambert attenuation, scattered-light approximation, shore/crest foam, GGX glints and filtered ripples.+// Single-pass visual study, not fluid simulation: caustics are artistic; reflected waves/multiple scattering are omitted.+// @render time=5.0+// @variant QUALITY=1+// @variant QUALITY=3+// @variant DEBUG_MODE=1+// @variant DEBUG_MODE=2+// @variant DEBUG_MODE=3+// @variant DEBUG_MODE=4+// @variant DEBUG_MODE=5+// @variant DEBUG_MODE=6+#define QUALITY 2 // 1 interactive: sky reflection | 2 high: land reflection | 3 still: 4x AA, more waves/steps+#define DEBUG_MODE 0 // 0 beauty | 1 optical path | 2 normals | 3 foam | 4 primary steps | 5 Fresnel | 6 transmission++// 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;++// ---- 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))))); }++// ---- 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; }+// 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;+// 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) {+ 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 * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return 1.4 * sum / norm;+}+// 2D fBm with the usual defaults (lacunarity 2.01 so octave peaks never re-align, persistence 0.5).+float fbm(vec2 p, int octaves) { return fbm(p, octaves, 2.01, 0.5); }+// fBm over 3D gradient noise.+float fbm(vec3 p, int octaves, float lacunarity, float persistence) {+ 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 * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);+ }+ return sum / norm;+}++// ---- 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;+}+// Hemisphere light: sky color from above blended to ground color from below.+vec3 hemisphereLight(vec3 n, vec3 skyColor, vec3 groundColor) {+ return mix(groundColor, skyColor, 0.5 + 0.5 * n.y);+}++// ---- shader-skills library: water ----+// Angular frequency sqrt(g*k*tanh(k*depth)) for finite-depth gravity waves. Nonpositive inputs are clamped.+float waterDispersion(float k, float depth, float gravity) {+ k = max(k,0.0);+ float e = exp(-2.0*k*max(depth,0.0));+ return sqrt(max(gravity,0.0)*k*(1.0-e)/(1.0+e));+}+// One sinusoidal wave: vec4(height, dh/dx, dh/dz, Laplacian). Direction is normalized internally; zero uses +X. wavelength > 0, amplitude in meters. footprint filters waves below 2-6 pixels; derivatives hold it constant.+vec4 waterWaveD(vec2 xz, float time, vec2 direction, float wavelength, float amplitude, float depth, float footprint) {+ float dl = length(direction);+ vec2 dir = dl>0.000001 ? direction/dl : vec2(1.0,0.0);+ float lengthM = max(wavelength,0.0001);+ float k = TAU/lengthM;+ float keep = smoothstep(2.0,6.0,lengthM/max(footprint,0.000001));+ float phase = k*dot(dir,xz)-waterDispersion(k,depth,9.81)*time;+ float h = amplitude*keep*sin(phase);+ return vec4(h, amplitude*keep*k*cos(phase)*dir, -k*k*h);+}+// Exact unpolarized dielectric Fresnel for a positive incident cosine and positive refractive indices. Returns 1 for total internal reflection. Caller chooses etaIncident/etaTransmitted for the ray's side.+float fresnelDielectric(float cosIncident, float etaIncident, float etaTransmitted) {+ float ci = clamp(abs(cosIncident),0.0,1.0);+ float ei = max(etaIncident,0.000001), et = max(etaTransmitted,0.000001);+ if (abs(ei-et)<0.0000001) return 0.0;+ float sinT2 = (ei*ei)/(et*et)*max(0.0,1.0-ci*ci);+ if (sinT2>=1.0) return 1.0;+ float ct = sqrt(max(0.0,1.0-sinT2));+ float rs = (ei*ci-et*ct)/max(ei*ci+et*ct,0.000001);+ float rp = (et*ci-ei*ct)/max(et*ci+ei*ct,0.000001);+ return clamp(0.5*(rs*rs+rp*rp),0.0,1.0);+}+// Beer-Lambert RGB transmittance exp(-extinction*pathLength). Negative extinction/path is clamped to zero. Use the refracted optical path, not vertical water depth. Attenuation alone does not add scattered light.+vec3 beerTransmittance(vec3 extinction, float pathLength) {+ return exp(-max(extinction,vec3(0.0))*max(pathLength,0.0));+}++// ---- 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));+}++// ---- shader-skills library: tonemap ----+// AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display. Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT).+vec3 tonemapAgX(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 = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++// ---- 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;+}++// ---- shader-skills library: post ----+// Subpixel offset in [-0.5, 0.5)^2 for sample i of a supersampling loop (R2 low-discrepancy sequence). Better coverage than a regular grid for any sample count.+vec2 aaOffset(int i) {+ return fract(0.5 + float(i) * vec2(0.7548776662, 0.5698402910)) - 0.5;+}+// 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 ----+// 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 ----+const int WATER_AA=QUALITY==3?4:1;+const int WATER_WAVES=QUALITY==3?12:8;+const int WATER_STEPS=QUALITY==3?240:180;+const vec3 COAST_SUN=normalize(vec3(-0.35,0.62,-0.55));+const vec3 EXTINCTION=vec3(0.42,0.085,0.045); // illustrative clear turquoise water, 1/m+const float WATER_IOR=1.333;+const float WATER_FAR=95.0;++float coastBed(vec2 p) {+ vec2 a=p-vec2(-7.0,-8.0),b=p-vec2(7.0,-19.0),c=p-vec2(-5.0,-1.0);+ float islands=5.7*exp(-0.055*dot(a,a))+5.0*exp(-0.07*dot(b,b))+1.1*exp(-0.15*dot(c,c));+ return -2.4+islands*(1.0+0.18*gradientNoise(p*0.75))+0.12*sin(p.x*1.7)*sin(p.y*1.2);+}++vec3 coastBedNormal(vec2 p,float eps) {+ vec2 d=vec2(coastBed(p+vec2(eps,0.0))-coastBed(p-vec2(eps,0.0)),+ coastBed(p+vec2(0.0,eps))-coastBed(p-vec2(0.0,eps)))/(2.0*eps);+ return normalize(vec3(-d.x,1.0,-d.y));+}++vec4 coastWaves(vec2 p,float footprint) {+ vec4 sum=vec4(0.0);+ for(int i=0;i<WATER_WAVES;i++) {+ float fi=float(i);+ float angle=0.7+fi*2.39996;+ float wavelength=4.5*pow(0.69,fi);+ float amp=0.075*pow(0.58,fi);+ // Fixed reference depth in phase avoids spatially varying frequency drifting out of phase along the shore.+ sum+=waterWaveD(p+vec2(fi*1.37,fi*0.79),iTime,vec2(cos(angle),sin(angle)),wavelength,amp,3.0,footprint);+ }+ return sum;+}++vec2 traceCoast(vec3 ro,vec3 rd,bool includeWater,int maxSteps) {+ float t=0.01,previous=0.0;+ float closing=max(0.05,abs(rd.y)+4.0*length(rd.xz));+ for(int i=0;i<WATER_STEPS;i++) {+ if(i>=maxSteps)break;+ vec3 p=ro+rd*t;+ float h=coastBed(p.xz);+ if(includeWater) {+ float geometryFootprint=2.0*t/(iResolution.y*1.75*max(abs(rd.y),0.1));+ h=max(h,coastWaves(p.xz,geometryFootprint).x);+ }+ float gap=p.y-h;+ if(gap<0.0) {+ float lo=previous,hi=t;+ for(int j=0;j<10;j++) {+ float mid=0.5*(lo+hi);+ vec3 q=ro+rd*mid;+ float surface=coastBed(q.xz);+ if(includeWater) {+ float fp=2.0*mid/(iResolution.y*1.75*max(abs(rd.y),0.1));+ surface=max(surface,coastWaves(q.xz,fp).x);+ }+ if(q.y>surface)lo=mid;else hi=mid;+ }+ return vec2(0.5*(lo+hi),float(i));+ }+ previous=t;+ t+=max(gap/closing,0.012+0.008*t);+ if(t>WATER_FAR)break;+ }+ if(includeWater && rd.y < -0.0001) return vec2(max(0.01,-ro.y/rd.y),float(maxSteps));+ return vec2(-1.0,float(maxSteps));+}++vec3 coastSky(vec3 rd) {+ vec3 c=mix(vec3(0.22,0.40,0.60),vec3(0.025,0.13,0.36),sqrt(max(rd.y,0.0)));+ float clouds=smoothstep(0.1,0.55,fbm(rd.xz/max(rd.y+0.4,0.15)*1.3,4));+ c=mix(c,vec3(0.95,0.97,1.0),clouds*0.18*smoothstep(0.03,0.3,rd.y));+ return c+vec3(9.0,8.0,6.0)*sunDisk(rd,COAST_SUN,0.012,0.002);+}++vec3 shadeCoastBed(vec3 p,vec3 n,bool submerged,float footprint) {+ float grain=0.5+0.5*fbm(p.xz*2.5,4)*(1.0-smoothstep(0.03,0.25,footprint));+ float rock=smoothstep(0.45,1.0,p.y)*(1.0-smoothstep(0.65,0.9,n.y));+ vec3 sand=mix(vec3(0.38,0.29,0.15),vec3(0.7,0.59,0.37),grain);+ vec3 albedo=mix(sand,vec3(0.17,0.15,0.12),rock);+ float vegetation=smoothstep(1.2,2.0,p.y)*smoothstep(0.5,0.82,n.y);+ albedo=mix(albedo,vec3(0.07,0.12,0.025),vegetation);+ vec3 direct=vec3(2.5,2.3,1.9)*max(dot(n,COAST_SUN),0.0);+ if(submerged) {+ direct*=beerTransmittance(EXTINCTION,max(-p.y,0.0)/COAST_SUN.y);+ float caustic=pow(max(0.0,sin(p.x*7.0+sin(p.z*4.0+iTime)*1.3)*sin(p.z*6.0+cos(p.x*4.0-iTime)*1.2)),9.0);+ float keep=1.0-smoothstep(0.02,0.12,footprint);+ direct*=1.0+caustic*keep*1.2; // projected artistic caustic pattern, not photon transport+ }+ return albedo*(direct+hemisphereLight(n,vec3(0.35,0.43,0.5),vec3(0.12,0.10,0.07)));+}++vec3 renderCoast(vec2 coord) {+ vec2 uv=(2.0*coord-iResolution.xy)/iResolution.y;+ vec3 ro=vec3(0.0,3.5,7.5);+ vec3 rd=cameraRay(cameraMatrix(ro,vec3(-0.8,-0.1,-6.0),0.0),uv,1.75);+ vec3 sky=coastSky(rd);+ vec2 hit=traceCoast(ro,rd,true,WATER_STEPS);+#if DEBUG_MODE == 4+ return debugHeat(hit.y/float(WATER_STEPS));+#endif+ if(hit.x<0.0)return sky;+ vec3 p=ro+rd*hit.x;+ float footprint=2.0*hit.x/(iResolution.y*1.75);+ float bed=coastBed(p.xz);+ vec3 col;+ if(bed>p.y-0.015) {+ vec3 n=coastBedNormal(p.xz,max(footprint,0.003));+ col=shadeCoastBed(p,n,false,footprint);+ } else {+ vec4 waves=coastWaves(p.xz,footprint/max(abs(rd.y),0.1));+ vec3 n=normalize(vec3(-waves.y,1.0,-waves.z));+ vec3 v=-rd;+ float F=fresnelDielectric(max(dot(n,v),0.0),1.0,WATER_IOR);+ vec3 refracted=refract(rd,n,1.0/WATER_IOR);+ vec2 bottomHit=traceCoast(p-n*0.006,refracted,false,WATER_STEPS);+ float path=bottomHit.x>0.0?bottomHit.x:30.0;+ vec3 bottomPoint=p-n*0.006+refracted*path;+ vec3 bottomColor=shadeCoastBed(bottomPoint,coastBedNormal(bottomPoint.xz,0.01),true,footprint);+ vec3 T=beerTransmittance(EXTINCTION,path);+ vec3 body=bottomColor*T+vec3(0.012,0.19,0.24)*(1.0-T); // approximate in-scattered body light+ vec3 reflected=reflect(rd,n);+ vec3 reflection=coastSky(normalize(vec3(reflected.x,max(reflected.y,0.01),reflected.z)));+#if QUALITY >= 2+ vec2 reflectedHit=traceCoast(p+n*0.015,reflected,false,WATER_STEPS);+ if(reflectedHit.x>0.0) {+ vec3 rp=p+n*0.015+reflected*reflectedHit.x;+ if(rp.y>0.02)reflection=shadeCoastBed(rp,coastBedNormal(rp.xz,0.015),false,footprint);+ }+#endif+ float unresolved=smoothstep(0.02,0.18,footprint);+ float rough=mix(0.075,0.20,unresolved);+ vec3 glint=specularGGX(n,v,COAST_SUN,rough,vec3(0.02037))*vec3(3.5,3.2,2.7);+ float shallow=1.0-smoothstep(0.08,0.5,max(p.y-bed,0.0));+ float shorePulse=0.5+0.5*sin((p.y-bed)*19.0-iTime*1.5+fbm(p.xz*2.0,3)*3.0);+ float foam=shallow*smoothstep(0.25,0.7,shorePulse)*0.8;+ foam+=0.12*smoothstep(0.18,0.6,-waves.w)*(1.0-unresolved);+ foam=clamp(foam,0.0,1.0);+ col=mix(body*(1.0-F)+reflection*F+glint,vec3(0.8,0.84,0.82),foam);+#if DEBUG_MODE == 1+ return vec3(path/12.0);+#elif DEBUG_MODE == 2+ return n*0.5+0.5;+#elif DEBUG_MODE == 3+ return vec3(foam);+#elif DEBUG_MODE == 5+ return vec3(F);+#elif DEBUG_MODE == 6+ return T;+#endif+ }+ return mix(col,coastSky(normalize(vec3(rd.x,0.025,rd.z))),1.0-exp(-hit.x*0.003));+}++void mainImage(out vec4 fragColor,in vec2 fragCoord) {+ vec3 col=vec3(0.0);+ for(int i=0;i<WATER_AA;i++) {+ vec3 c=renderCoast(fragCoord+(WATER_AA>1?aaOffset(i):vec2(0.0)));+#if DEBUG_MODE == 0+ c=tonemapAgX(c*1.05);+#endif+ col+=c/float(WATER_AA);+ }+#if DEBUG_MODE == 0+ col=linearToSrgb(col)+ditherTPDF(fragCoord,iFrame);+#endif+ fragColor=vec4(col,1.0);+}diff --git a/gallery/coastal-water.png b/gallery/coastal-water.pngnew file mode 100644index 0000000..7e01c36Binary files /dev/null and b/gallery/coastal-water.png differdiff --git a/gallery/procedural-city.glsl b/gallery/procedural-city.glslnew file mode 100644index 0000000..4912728--- /dev/null+++ b/gallery/procedural-city.glsl@@ -0,0 +1,399 @@+// Parcel -> mass -> setback -> roof -> facade. Original texture-free city at blue hour.+// 3x3 neighbor checks plus an unvisited-cell distance cap prevent taller remote blocks being skipped.+// Windows are filtered material fields; their emission is illustrative, not global illumination.+// @render time=4.0+// @variant DEBUG_MODE=2+// @variant DEBUG_MODE=3+// @variant DEBUG_MODE=4+// @variant DEBUG_MODE=5+#define DEBUG_MODE 0 // 0 beauty | 2 normals | 3 parcel IDs | 4 steps | 5 window mask++// Library code below is bundled from shader-skills (MIT): https://github.com/gokayfem/shader-skills+// ---- shader-skills library: common ----+const float PI = 3.14159265358979;++// ---- 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 float in [0,1) for an integer-valued 3D input.+float hash13(vec3 p) {+ uvec3 q = uvec3(ivec3(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y + pcgHash(q.z))));+}+// 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: pattern ----+// Box-filtered stripes along x with period 1 and duty cycle 0.5. Returns 0..1.+float filteredStripes(float x, float w) {+ w = max(w, 1e-4);+ float a = x + 0.5 * w, b = x - 0.5 * w;+ float ia = floor(a) * 0.5 + max(fract(a) - 0.5, 0.0);+ float ib = floor(b) * 0.5 + max(fract(b) - 0.5, 0.0);+ return (ia - ib) / w;+}++// ---- shader-skills library: sdf3d ----+// Axis-aligned box with half-extents b.+float sdBox(vec3 p, vec3 b) {+ vec3 q = abs(p) - b;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);+}+// Box with rounded edges. The outer size stays b; r is the edge radius (r <= min(b)).+float sdRoundBox(vec3 p, vec3 b, float r) {+ vec3 q = abs(p) - b + r;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;+}+// Capsule: segment a-b swept by radius r.+float sdCapsule(vec3 p, vec3 a, vec3 b, float r) {+ vec3 pa = p - a, ba = b - a;+ float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);+ return length(pa - ba * h) - r;+}++// ---- shader-skills library: sdf2d ----+// Axis-aligned rectangle with half-extents b.+float sdBox(vec2 p, vec2 b) {+ vec2 d = abs(p) - b;+ return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);+}++// ---- shader-skills library: domain ----+// Cell index for repetition with period s (integer-valued; use with hash functions).+float domRepeatId(float p, float s) { return floor(p / s + 0.5); }+vec2 domRepeatId(vec2 p, vec2 s) { return floor(p / s + 0.5); }+vec3 domRepeatId(vec3 p, vec3 s) { return floor(p / s + 0.5); }+// Infinite repetition with period s. Returns the local coordinate centered in its cell. Exact only while each instance stays inside its own cell. For instances that vary per cell or overhang, evaluate the 2 or 3 neighboring cells too (see references/sdf-library-guide.md).+float domRepeat(float p, float s) { return p - s * floor(p / s + 0.5); }+vec2 domRepeat(vec2 p, vec2 s) { return p - s * floor(p / s + 0.5); }+vec3 domRepeat(vec3 p, vec3 s) { return p - s * floor(p / s + 0.5); }++// ---- shader-skills library: architecture ----+// Stable building profile: vec4(height, half-width, half-depth, roof style 0/1/2) from an integer parcel ID. Height and half-width ranges are ordered, positive world-space values. The same ID always gives the same profile.+vec4 buildingProfile(vec2 parcel, vec2 heightRange, vec2 halfWidthRange) {+ vec3 h = hash32(parcel);+ return vec4(mix(heightRange.x,heightRange.y,h.x*h.x),+ mix(halfWidthRange.x,halfWidthRange.y,h.y),+ mix(halfWidthRange.x,halfWidthRange.y,h.z),+ floor(3.0*hash12(parcel+vec2(83.0,19.0))));+}+// Box-filtered rectangular windows centered on integer facade coordinates. fill is the opening fraction per cell in [0,1]; footprint is the pixel's width/height in cell units. At large footprints it converges to fill.x*fill.y.+float facadeWindowMask(vec2 uv, vec2 fill, vec2 footprint) {+ fill = clamp(fill,0.0,1.0);+ vec2 w = max(footprint,vec2(0.0001));+ vec2 a = uv + 0.5*fill + 0.5*w;+ vec2 b = uv + 0.5*fill - 0.5*w;+ vec2 ia = floor(a)*fill + min(fract(a),fill);+ vec2 ib = floor(b)*fill + min(fract(b),fill);+ vec2 coverage = clamp((ia-ib)/w,0.0,1.0);+ return coverage.x*coverage.y;+}++// ---- shader-skills library: raymarch ----+#define ZERO (min(iFrame, 0))+vec2 map(vec3 p);+const int RAYMARCH_MAX_STEPS = 256;+// Sphere-trace from ro along unit rd between tmin and tmax. Returns vec3(t, materialId, stepCount). t is -1 on a miss. The hit threshold grows with t (about one pixel's footprint), so distant surfaces don't burn steps. stepScale is 1 for exact or bound fields. Use < 1 (e.g. 0.6) when map() has Lipschitz > 1 (displacement, warps, twist).+vec3 raymarch(vec3 ro, vec3 rd, float tmin, float tmax, float stepScale) {+ float t = tmin;+ for (int i = ZERO; i < RAYMARCH_MAX_STEPS; i++) {+ vec2 h = map(ro + rd * t);+ if (abs(h.x) < max(0.0002 * t, 1e-5)) return vec3(t, h.y, float(i));+ t += h.x * stepScale;+ if (t > tmax) break;+ }+ return vec3(-1.0, -1.0, float(RAYMARCH_MAX_STEPS));+}+// Surface normal from 4 tetrahedral samples (cheaper than 6 central differences, and still centered). eps should scale with distance, e.g. 0.0005 * t: that filters distant detail and avoids sparkling.+vec3 calcNormal(vec3 p, float eps) {+ vec3 n = vec3(0.0);+ for (int i = ZERO; i < 4; i++) {+ vec3 e = 0.5773 * (2.0 * vec3((((i + 3) >> 1) & 1), ((i >> 1) & 1), (i & 1)) - 1.0);+ n += e * map(p + e * eps).x;+ }+ return normalize(n);+}+// Soft shadow toward a light along unit rd. k controls sharpness (k is about 1 / light angular size: 8 soft, 32 hard). Uses the "closest approach between samples" estimate, which removes banding from sharp-cornered occluders. Returns 0 (full shadow) .. 1 (lit).+float softShadow(vec3 ro, vec3 rd, float tmin, float tmax, float k) {+ float res = 1.0;+ float t = tmin;+ float ph = 1e10;+ for (int i = ZERO; i < 64; i++) {+ float h = map(ro + rd * t).x;+ if (h < 0.0001) return 0.0;+ float y = h * h / (2.0 * ph);+ float d = sqrt(max(h * h - y * y, 0.0));+ res = min(res, k * d / max(t - y, 1e-4));+ ph = h;+ t += clamp(h, 0.005, 0.5);+ if (res < 0.001 || t > tmax) break;+ }+ res = clamp(res, 0.0, 1.0);+ return res * res * (3.0 - 2.0 * res);+}+// Ambient occlusion from 5 distance samples along the normal. Compares the expected distance with the actual one. scale is the sampling reach in scene units (about 0.12 for a unit-sized object). Returns 0 (occluded) .. 1 (open).+float calcAO(vec3 p, vec3 n, float scale) {+ float occ = 0.0;+ float weight = 1.0;+ for (int i = ZERO; i < 5; i++) {+ float h = 0.01 + scale * float(i) / 4.0;+ float d = map(p + h * n).x;+ occ += (h - d) * weight;+ weight *= 0.95;+ }+ return clamp(1.0 - 3.0 * occ / max(scale / 0.12, 1e-3), 0.0, 1.0);+}++// ---- 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;+}+// Complete metallic-roughness shading for one light (diffuse + specular, NoL included, artist units). Multiply by light color and shadow. Keep albedo around 0.05-0.7 (linear); brighten lights, not albedo.+vec3 shadePBR(vec3 n, vec3 v, vec3 l, vec3 albedo, float roughness, float metallic) {+ vec3 f0 = mix(vec3(0.04), albedo, metallic);+ float NoL = clamp(dot(n, l), 0.0, 1.0);+ vec3 F = fresnelSchlick(max(dot(n, v), 0.0), f0);+ vec3 diffuse = albedo * (1.0 - metallic) * (1.0 - F) * NoL;+ return diffuse + specularGGX(n, v, l, roughness, f0);+}+// Hemisphere light: sky color from above blended to ground color from below.+vec3 hemisphereLight(vec3 n, vec3 skyColor, vec3 groundColor) {+ return mix(groundColor, skyColor, 0.5 + 0.5 * n.y);+}++// ---- 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));+}++// ---- shader-skills library: tonemap ----+// AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display. Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT).+vec3 tonemapAgX(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 = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++// ---- shader-skills library: volume ----+// Analytic height fog for density a * exp(-b * y) along the ray segment [0, t]. Thick near the ground, thin above. Returns the fog amount in [0,1].+float heightFog(vec3 ro, vec3 rd, float t, float a, float b) {+ float base = a * exp(-ro.y * b);+ float amount = (abs(rd.y) < 1e-4) ? base * t+ : base * (1.0 - exp(-t * rd.y * b)) / (rd.y * b);+ return 1.0 - exp(-max(amount, 0.0));+}++// ---- shader-skills library: post ----+// Subpixel offset in [-0.5, 0.5)^2 for sample i of a supersampling loop (R2 low-discrepancy sequence). Better coverage than a regular grid for any sample count.+vec2 aaOffset(int i) {+ return fract(0.5 + float(i) * vec2(0.7548776662, 0.5698402910)) - 0.5;+}+// 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 ----+// 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 ----+const float PARCEL = 3.6;+const vec3 CITY_SUN = normalize(vec3(-0.6,0.6,0.4));+const int AA = 1; // set 4 for stills++vec4 cityProfile(vec2 id) {+ vec4 b = buildingProfile(id,vec2(2.8,13.0),vec2(0.75,1.13));+ if (length(id)<0.5) b=vec4(18.0,1.15,1.15,2.0);+ return b;+}++vec2 map(vec3 p) {+ vec2 id=domRepeatId(p.xz,vec2(PARCEL));+ vec2 local=p.xz-id*PARCEL;+ vec2 res=vec2(p.y,0.0);+ for(int z=-1;z<=1;z++) for(int x=-1;x<=1;x++) {+ vec2 cell=id+vec2(float(x),float(z));+ vec4 b=cityProfile(cell);+ vec3 q=p-vec3(cell.x*PARCEL,0.0,cell.y*PARCEL);+ float body=sdRoundBox(q-vec3(0.0,b.x*0.38,0.0),vec3(b.y,b.x*0.38,b.z)-0.035,0.035);+ float upper=sdRoundBox(q-vec3(0.0,b.x*0.83,0.0),vec3(b.y*0.72,b.x*0.17,b.z*0.72)-0.025,0.025);+ float podium=sdBox(q-vec3(0.0,0.35,0.0),vec3(b.y+0.15,0.35,b.z+0.15));+ float d=min(podium,min(body,upper));+ if(b.w>0.5) d=min(d,sdBox(q-vec3(0.0,b.x+0.22,0.0),vec3(b.y*0.45,0.22,b.z*0.5)));+ if(b.w>1.5) d=min(d,sdCapsule(q,vec3(0.0,b.x,0.0),vec3(0.0,b.x+1.1,0.0),0.035));+ if(d<res.x)res=vec2(d,1.0);+ }+ float unvisited=min(1.5*PARCEL-abs(local.x),1.5*PARCEL-abs(local.y));+ res.x=min(res.x,unvisited);+ return res;+}++vec3 citySky(vec3 rd) {+ float h=smoothstep(-0.12,0.7,rd.y);+ vec3 c=mix(vec3(0.10,0.12,0.19),vec3(0.012,0.028,0.07),h);+ c+=vec3(0.12,0.055,0.025)*pow(max(dot(rd,CITY_SUN),0.0),12.0);+ return c;+}++vec3 renderCity(vec2 coord) {+ vec2 uv=(2.0*coord-iResolution.xy)/iResolution.y;+ float orbit=0.5+0.035*iTime;+ vec3 ro=vec3(32.0*sin(orbit),17.0,32.0*cos(orbit));+ vec3 rd=cameraRay(cameraMatrix(ro,vec3(0.0,6.0,0.0),0.0),uv,1.85);+ vec3 sky=citySky(rd);+ vec3 hit=raymarch(ro,rd,0.05,110.0,0.95);+#if DEBUG_MODE == 4+ return debugHeat(hit.z/256.0);+#endif+ if(hit.x<0.0)return sky;+ vec3 p=ro+rd*hit.x;+ vec3 n=calcNormal(p,max(0.001,hit.x*0.00015));+ vec2 id=domRepeatId(p.xz,vec2(PARCEL));+ vec4 b=cityProfile(id);+ float variation=hash12(id);+ float fp=2.0*hit.x/(iResolution.y*1.85);+ fp/=max(abs(dot(n,rd)),0.15);+ vec3 albedo=mix(vec3(0.16,0.19,0.21),vec3(0.32,0.29,0.25),variation);+ float windows=0.0;+ vec3 emission=vec3(0.0);+ if(hit.y>0.5 && n.y<0.6) {+ vec2 facade=vec2(abs(n.x)>abs(n.z)?p.z:p.x,p.y);+ vec2 grid=facade/vec2(0.30,0.43);+ windows=facadeWindowMask(grid,vec2(0.62,0.65),vec2(fp*3.8,fp*2.5));+ float occupied=step(0.42,hash13(vec3(floor(grid+0.5),variation*100.0)));+ float keep=1.0-smoothstep(0.3,1.2,fp/0.30);+ occupied=mix(0.58,occupied,keep);+ vec3 glass=vec3(0.018,0.035,0.055)+citySky(reflect(rd,n))*0.3;+ albedo=mix(albedo,glass,windows);+ emission=windows*occupied*mix(vec3(0.6,0.22,0.055),vec3(1.2,0.74,0.33),variation)*0.8;+ } else if(hit.y<0.5) {+ albedo=vec3(0.045,0.05,0.06);+ vec2 streets=abs(domRepeat(p.xz,vec2(PARCEL)));+ float marking=(1.0-smoothstep(0.025,0.025+fp,abs(streets.x-PARCEL*0.5)))+ *filteredStripes(p.z*1.3,fp*1.3);+ albedo=mix(albedo,vec3(0.42,0.32,0.13),marking);+ }+ float ao=calcAO(p,n,0.18);+ float shadow=softShadow(p+n*0.015,CITY_SUN,0.02,20.0,10.0);+ vec3 col=shadePBR(n,-rd,CITY_SUN,albedo,0.4,0.15)*vec3(0.9,0.75,0.6)*shadow;+ col+=albedo*hemisphereLight(n,vec3(0.30,0.43,0.66),vec3(0.07,0.065,0.055))*ao;+ col+=emission;+#if DEBUG_MODE == 2+ return n*0.5+0.5;+#elif DEBUG_MODE == 3+ return hash33(vec3(id,0.0));+#elif DEBUG_MODE == 5+ return vec3(windows);+#endif+ float haze=heightFog(ro,rd,hit.x,0.006,0.055);+ return mix(col,citySky(normalize(vec3(rd.x,0.06,rd.z))),haze);+}++void mainImage(out vec4 fragColor,in vec2 fragCoord) {+ vec3 col=vec3(0.0);+ for(int i=0;i<AA;i++) {+ vec3 sampleColor=renderCity(fragCoord+(AA>1?aaOffset(i):vec2(0.0)));+#if DEBUG_MODE == 0+ sampleColor=tonemapAgX(sampleColor*1.05);+#endif+ col+=sampleColor/float(AA);+ }+#if DEBUG_MODE == 0+ col=linearToSrgb(col)+ditherTPDF(fragCoord,iFrame);+#endif+ fragColor=vec4(col,1.0);+}diff --git a/gallery/procedural-city.png b/gallery/procedural-city.pngnew file mode 100644index 0000000..0677257Binary files /dev/null and b/gallery/procedural-city.png differdiff --git a/skills/shader-art-coding/SKILL.md b/skills/shader-art-coding/SKILL.mdindex 5bf1b03..24914fe 100644--- a/skills/shader-art-coding/SKILL.md+++ b/skills/shader-art-coding/SKILL.md@@ -2,8 +2,8 @@name: shader-art-codingdescription: >-Writes, debugs, and art-directs procedural GLSL fragment shaders (Shadertoy mainImage, WebGL2 / GLSL ES 3.00):- SDF raymarching, 2D distance-field graphics, noise / fBm / domain warping, heightfield terrain, clouds and other- volumes, PBR lighting, color and tonemapping. Ships a verified GLSL building-block library with a bundler and+ SDF raymarching, procedural buildings/cities, 2D distance-field graphics, noise / fBm / domain warping, terrain,+ ocean/coastal water optics, clouds and other volumes, PBR lighting, color and tonemapping. Ships a verified GLSL building-block library with a bundler andchecker. Use when the user asks for a shader, Shadertoy, GLSL/.frag/.glsl code, a raymarcher, an SDF scene, aprocedural texture or generative visual, or wants a shader fixed, optimized, ported or explained. Not forHLSL/Unity ShaderLab or non-graphics GPU compute.@@ -78,6 +78,9 @@ Read only what the task needs:| `references/sdf-library-guide.md` | modeling: exactness tiers, blends, neighbor-checked repetition, deformation limits, WebGL pitfalls || `references/rendering-pipeline.md` | lighting rigs, shadows/AO, sky and fog, volumes, tonemapping, AA, performance || `references/noise-use-cases.md` | choosing Perlin/value/simplex/cellular noise, fBm/ridged/billow/warp/hybrid recipes, game use cases and primary-source code links |+| `references/procedural-buildings.md` | parcel IDs, building massing, setbacks/roofs, facade filtering, city repetition and game integration |+| `references/terrain-production.md` | terrain representations, designed valleys, slope/altitude materials, tracing limits, chunks and LOD |+| `references/water-quality.md` | high-quality ocean/coastal water, wave derivatives, Fresnel/refraction/absorption, foam, presets and engine-side upgrades || `references/shader-workflow.md` | planning a complex shader end to end; review checklist || `references/composition-and-debugging.md` | the image reads poorly, or something is visually wrong || `references/formula-cookbook.md` | multi-step recipes: modular cell lattices, terrain synthesis, organic composition |@@ -87,7 +90,8 @@ Read only what the task needs:Templates in `templates/` are complete, render-verified starting points (gallery in the repository README):`raymarch-sdf.glsl`, `terrain.glsl`, `ocean.glsl`, `volumetric-clouds.glsl`, `sdf-2d-poster.glsl`,-`pattern-swatches.glsl`, `noise-progression.glsl`, `noise-terrain-map.glsl`.+`pattern-swatches.glsl`, `noise-progression.glsl`, `noise-terrain-map.glsl`, `procedural-city.glsl`,+`alpine-valley.glsl`, `coastal-water.glsl`.## Output expectations@@ -98,6 +102,11 @@ When writing a shader:- Include `DEBUG_MODE` switches and name the art controls as constants at the top.- End with a short tuning guide: which constants control scale, softness, color, light and motion.- Say whether the shader was compile-checked, and how.+- For buildings/terrain/water, separate implemented features from engine-side upgrades. Do not call a heightfield+ a cave generator, a material window a modeled recess, or a procedural foam/caustic mask a fluid/light simulation.+- For quality requests, state the target and budget, expose presets/debug views, and inspect rendered output.+ Annotate important template presets with `// @variant QUALITY=3` (or another defined integer macro) so CI compiles+ and renders them. Preserve horizon/shore contact and temporal filtering before adding detail.When improving an existing shader:diff --git a/skills/shader-art-coding/glsl/architecture.glsl b/skills/shader-art-coding/glsl/architecture.glslnew file mode 100644index 0000000..5448f2e--- /dev/null+++ b/skills/shader-art-coding/glsl/architecture.glsl@@ -0,0 +1,30 @@+//! architecture: stable building parameters and filtered facade fields. These are massing/material helpers,+//! not a mesh generator or a full shape-grammar engine. Keep the generated footprint inside its parcel.++/// Stable building profile: vec4(height, half-width, half-depth, roof style 0/1/2) from an integer parcel ID.+/// Height and half-width ranges are ordered, positive world-space values. The same ID always gives the same profile.+/// @use city blocks, towers, deterministic chunk generation, architectural massing+/// @see Mueller et al., "Procedural Modeling of Buildings", SIGGRAPH 2006 (hierarchical massing principle)+vec4 buildingProfile(vec2 parcel, vec2 heightRange, vec2 halfWidthRange) {+ vec3 h = hash32(parcel);+ return vec4(mix(heightRange.x,heightRange.y,h.x*h.x),+ mix(halfWidthRange.x,halfWidthRange.y,h.y),+ mix(halfWidthRange.x,halfWidthRange.y,h.z),+ floor(3.0*hash12(parcel+vec2(83.0,19.0))));+}++/// Box-filtered rectangular windows centered on integer facade coordinates. fill is the opening fraction per+/// cell in [0,1]; footprint is the pixel's width/height in cell units. At large footprints it converges to fill.x*fill.y.+/// @use distant city facades, office windows, floor bands, architectural grids without moire+/// @range [0,1]+/// @see https://iquilezles.org/articles/filterableprocedurals/ (integrate a periodic pattern over a footprint)+float facadeWindowMask(vec2 uv, vec2 fill, vec2 footprint) {+ fill = clamp(fill,0.0,1.0);+ vec2 w = max(footprint,vec2(0.0001));+ vec2 a = uv + 0.5*fill + 0.5*w;+ vec2 b = uv + 0.5*fill - 0.5*w;+ vec2 ia = floor(a)*fill + min(fract(a),fill);+ vec2 ib = floor(b)*fill + min(fract(b),fill);+ vec2 coverage = clamp((ia-ib)/w,0.0,1.0);+ return coverage.x*coverage.y;+}diff --git a/skills/shader-art-coding/glsl/water.glsl b/skills/shader-art-coding/glsl/water.glslnew file mode 100644index 0000000..7ed57c0--- /dev/null+++ b/skills/shader-art-coding/glsl/water.glsl@@ -0,0 +1,53 @@+//! water: finite-depth wave dispersion, analytic wave derivatives, exact dielectric Fresnel and RGB attenuation.+//! Units must agree: wavelength/depth/path in meters, gravity in m/s^2, extinction in 1/m. No textures or scene state.++/// Angular frequency sqrt(g*k*tanh(k*depth)) for finite-depth gravity waves. Nonpositive inputs are clamped.+/// @use shallow coasts, ocean swell, lake waves with depth-dependent speed+/// @range nonnegative+/// @see MIT Marine Hydrodynamics lecture 20: https://ocw.mit.edu/courses/2-20-marine-hydrodynamics-13-021-spring-2005/5d48a5937971d973fd8ca90c051a83f8_lecture20.pdf+float waterDispersion(float k, float depth, float gravity) {+ k = max(k,0.0);+ float e = exp(-2.0*k*max(depth,0.0));+ return sqrt(max(gravity,0.0)*k*(1.0-e)/(1.0+e));+}++/// One sinusoidal wave: vec4(height, dh/dx, dh/dz, Laplacian). Direction is normalized internally; zero uses +X.+/// wavelength > 0, amplitude in meters. footprint filters waves below 2-6 pixels; derivatives hold it constant.+/// @use analytic water normals, layered swell/chop, curvature foam, finite-depth lake and coastal waves+/// @see Mark Finch, GPU Gems chapter 1, "Effective Water Simulation from Physical Models"+vec4 waterWaveD(vec2 xz, float time, vec2 direction, float wavelength, float amplitude, float depth, float footprint) {+ float dl = length(direction);+ vec2 dir = dl>0.000001 ? direction/dl : vec2(1.0,0.0);+ float lengthM = max(wavelength,0.0001);+ float k = TAU/lengthM;+ float keep = smoothstep(2.0,6.0,lengthM/max(footprint,0.000001));+ float phase = k*dot(dir,xz)-waterDispersion(k,depth,9.81)*time;+ float h = amplitude*keep*sin(phase);+ return vec4(h, amplitude*keep*k*cos(phase)*dir, -k*k*h);+}++/// Exact unpolarized dielectric Fresnel for a positive incident cosine and positive refractive indices.+/// Returns 1 for total internal reflection. Caller chooses etaIncident/etaTransmitted for the ray's side.+/// @use air-water interfaces (1.0,1.333), underwater views (1.333,1.0), glass+/// @range [0,1]+/// @see https://www.pbr-book.org/4ed/Reflection_Models/Specular_Reflection_and_Transmission+float fresnelDielectric(float cosIncident, float etaIncident, float etaTransmitted) {+ float ci = clamp(abs(cosIncident),0.0,1.0);+ float ei = max(etaIncident,0.000001), et = max(etaTransmitted,0.000001);+ if (abs(ei-et)<0.0000001) return 0.0;+ float sinT2 = (ei*ei)/(et*et)*max(0.0,1.0-ci*ci);+ if (sinT2>=1.0) return 1.0;+ float ct = sqrt(max(0.0,1.0-sinT2));+ float rs = (ei*ci-et*ct)/max(ei*ci+et*ct,0.000001);+ float rp = (et*ci-ei*ct)/max(et*ci+ei*ct,0.000001);+ return clamp(0.5*(rs*rs+rp*rp),0.0,1.0);+}++/// Beer-Lambert RGB transmittance exp(-extinction*pathLength). Negative extinction/path is clamped to zero.+/// Use the refracted optical path, not vertical water depth. Attenuation alone does not add scattered light.+/// @use depth-colored water, underwater visibility, tinted glass, homogeneous fog+/// @range [0,1]+/// @see https://www.pbr-book.org/4ed/Volume_Scattering/Transmittance+vec3 beerTransmittance(vec3 extinction, float pathLength) {+ return exp(-max(extinction,vec3(0.0))*max(pathLength,0.0));+}diff --git a/skills/shader-art-coding/references/library-index.md b/skills/shader-art-coding/references/library-index.mdindex 105e396..f166a01 100644--- a/skills/shader-art-coding/references/library-index.md+++ b/skills/shader-art-coding/references/library-index.md@@ -20,10 +20,12 @@ Tags: **exact** is a true Euclidean distance, safe for blending, AO, shadows and- [sdf2d](#sdf2d) - 2D signed distance primitives for posters, icons, UI, motion graphics, and as profiles for opExtrude / opRevolve- [operators](#operators) - combine distances (booleans, smooth blends, chamfers, stairs) and reshape them (round, onion, extrude, revolve, elongate)- [domain](#domain) - transform the point BEFORE evaluating a distance (repetition, mirroring, polar sectors, folds, twist, bend)+- [architecture](#architecture) - stable building parameters and filtered facade fields- [raymarch](#raymarch) - sphere tracing, normals, soft shadows and ambient occlusion for SDF scenes- [intersect](#intersect) - analytic ray-primitive intersections- [camera](#camera) - look-at frames, primary rays, field of view, thin-lens depth of field- [shading](#shading) - BRDF terms and practical lighting models+- [water](#water) - finite-depth wave dispersion, analytic wave derivatives, exact dielectric Fresnel and RGB attenuation- [color](#color) - transfer functions, perceptual color (Oklab / OkLCh), palettes, luminance, blackbody light colors- [tonemap](#tonemap) - map scene-linear HDR to display range- [volume](#volume) - participating media (fog, smoke, clouds, haze)@@ -194,6 +196,13 @@ domain: transform the point BEFORE evaluating a distance (repetition, mirroring,- `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.*+## architecture++architecture: stable building parameters and filtered facade fields. These are massing/material helpers, not a mesh generator or a full shape-grammar engine. Keep the generated footprint inside its parcel.++- `vec4 buildingProfile(vec2 parcel, vec2 heightRange, vec2 halfWidthRange)` - Stable building profile: vec4(height, half-width, half-depth, roof style 0/1/2) from an integer parcel ID. Height and half-width ranges are ordered, positive world-space values. The same ID always gives the same profile. *Use: city blocks, towers, deterministic chunk generation, architectural massing.*+- `float facadeWindowMask(vec2 uv, vec2 fill, vec2 footprint)` - Box-filtered rectangular windows centered on integer facade coordinates. fill is the opening fraction per cell in [0,1]; footprint is the pixel's width/height in cell units. At large footprints it converges to fill.x*fill.y. *Use: distant city facades, office windows, floor bands, architectural grids without moire.* Range [0,1].+## raymarchraymarch: sphere tracing, normals, soft shadows and ambient occlusion for SDF scenes. SCENE CONTRACT: your shader defines vec2 map(vec3 p) returning vec2(distance, materialId). Packing the material into a vec2 avoids structs (WebGL forbids ?: on structs) and works with every helper here. Loops start at ZERO, a zero the compiler cannot prove. That stops it inlining map() into every loop, which keeps compile times sane and avoids WebGL compiler crashes on large scenes.@@ -239,6 +248,15 @@ shading: BRDF terms and practical lighting models. Vectors are unit length: n =- `float translucency(vec3 n, vec3 v, vec3 l, float distortion, float power, float thickness)` - Fast translucency (Barre-Brisebois and Bouchard 2011): light passing through thin parts, seen from the back. distortion bends the light along the normal (0.2-0.5). thickness is 0 (thin) .. 1 (thick); see sdfThickness. *Use: leaves, ears, wax, jade, marble, backlit petals, jellyfish.*- `float rimLight(vec3 n, vec3 v, float power)` - Rim light from the viewing angle: strongest at silhouettes. *Use: character separation from background, fresnel-like glow, stylized outlines.*+## water++water: finite-depth wave dispersion, analytic wave derivatives, exact dielectric Fresnel and RGB attenuation. Units must agree: wavelength/depth/path in meters, gravity in m/s^2, extinction in 1/m. No textures or scene state.++- `float waterDispersion(float k, float depth, float gravity)` - Angular frequency sqrt(g*k*tanh(k*depth)) for finite-depth gravity waves. Nonpositive inputs are clamped. *Use: shallow coasts, ocean swell, lake waves with depth-dependent speed.* Range nonnegative.+- `vec4 waterWaveD(vec2 xz, float time, vec2 direction, float wavelength, float amplitude, float depth, float footprint)` - One sinusoidal wave: vec4(height, dh/dx, dh/dz, Laplacian). Direction is normalized internally; zero uses +X. wavelength > 0, amplitude in meters. footprint filters waves below 2-6 pixels; derivatives hold it constant. *Use: analytic water normals, layered swell/chop, curvature foam, finite-depth lake and coastal waves.*+- `float fresnelDielectric(float cosIncident, float etaIncident, float etaTransmitted)` - Exact unpolarized dielectric Fresnel for a positive incident cosine and positive refractive indices. Returns 1 for total internal reflection. Caller chooses etaIncident/etaTransmitted for the ray's side. *Use: air-water interfaces (1.0,1.333), underwater views (1.333,1.0), glass.* Range [0,1].+- `vec3 beerTransmittance(vec3 extinction, float pathLength)` - Beer-Lambert RGB transmittance exp(-extinction*pathLength). Negative extinction/path is clamped to zero. Use the refracted optical path, not vertical water depth. Attenuation alone does not add scattered light. *Use: depth-colored water, underwater visibility, tinted glass, homogeneous fog.* Range [0,1].+## colorcolor: transfer functions, perceptual color (Oklab / OkLCh), palettes, luminance, blackbody light colors. Light, shade and mix in LINEAR color. Picked hex colors, cosine palettes and Shadertoy textures are sRGB-encoded, so decode them with srgbToLinear before lighting. Encode once at the very end with linearToSrgb.diff --git a/skills/shader-art-coding/references/procedural-buildings.md b/skills/shader-art-coding/references/procedural-buildings.mdnew file mode 100644index 0000000..b36e89d--- /dev/null+++ b/skills/shader-art-coding/references/procedural-buildings.md@@ -0,0 +1,122 @@+# Procedural buildings and cities++Use this route for architectural massing, towers, streets, windows, roof details and stable per-parcel variation.+The complete starting point is `templates/procedural-city.glsl`. Library helpers are in `glsl/architecture.glsl`.+This shader renders implicit geometry; it does not export editable meshes or implement a full CGA rule engine.++## Contents++- [Construction order](#construction-order)+- [Stable parcels](#stable-parcels)+- [Filtered facade fields](#filtered-facade-fields)+- [Geometry and tracing](#geometry-and-tracing)+- [Materials, lighting and quality](#materials-lighting-and-quality)+- [Use cases and extensions](#use-cases-and-extensions)+- [Sources](#sources)++## Construction order++1. Establish a street grid and parcel IDs in world space.+2. Generate stable dimensions from the parcel ID; reserve roads and margins before adding detail.+3. Compose a podium, main mass, upper setback and roof. Different silhouettes matter more than random windows.+4. Shade the facade with floor/column coordinates; keep facade masks separate from structural distance.+5. Add material families, occupied windows, roof equipment, shadows, ambient occlusion and depth cues.+6. Filter windows and occupation randomness by the ray footprint. Check parcel IDs and march-cost views.++This is the massing hierarchy used in the template. It is inspired by grammar-based architecture, but it is a+fixed procedural recipe rather than an implementation of the full rule language in the cited research.++## Stable parcels++`buildingProfile` takes an integer ID and ordered ranges. It returns height, half-width, half-depth and a discrete+roof-style ID. Half-widths are not full facade widths. Keep the footprint plus podium margin below half the parcel+spacing; changing the seed inputs changes the city, while camera movement does not.++```glsl+vec4 architecturalParcelProfile(vec2 worldXZ) {+ vec2 parcel = domRepeatId(worldXZ, vec2(3.6));+ return buildingProfile(parcel, vec2(2.8, 13.0), vec2(0.75, 1.13));+}+```++For chunked worlds, derive the ID from global coordinates or a global integer chunk ID plus local cell ID. Do not+seed height from camera-relative coordinates. Keep random choices stable across LODs so roofs do not change shape+when the camera moves. The library test checks profile ranges and roof-style discreteness.++## Filtered facade fields++Choose coordinates on the dominant facade plane: X-facing walls use Z/Y, Z-facing walls use X/Y. Divide by window+spacing before calling the filter. `footprint` must also be expressed in these cell units. Supply an explicit+footprint in branches; do not call derivatives after a raymarch or inside material branches.++```glsl+float architecturalWindows(vec2 facadeMeters, vec2 footprintMeters) {+ vec2 spacing = vec2(0.30, 0.43);+ return facadeWindowMask(facadeMeters / spacing, vec2(0.62, 0.65), footprintMeters / spacing);+}+```++The filter integrates a periodic rectangular aperture. It tends toward opening area (`fill.x * fill.y`) when+windows are smaller than a pixel, rather than flickering. At grazing angles enlarge the footprint in the compressed+facade direction. The template uses an explicit ray-footprint estimate; a production renderer can propagate ray+differentials for a better anisotropic footprint.++Occupation randomness is separate from the geometric window mask. Near the camera, hash the building/floor/column+ID to choose lit rooms. In the distance, fade those binary choices toward average occupation. Adding unfiltered+random room brightness after filtering the window shape reintroduces flicker.++## Geometry and tracing++The scene uses tested `sdBox`, `sdRoundBox` and `sdCapsule` primitives. Podium and setbacks are actual surfaces;+windows are material fields. A dark rectangle is not a recessed window. For close architecture, model cavities,+frames, sills and balconies as geometry with appropriate distance bounds.++Per-cell dimensions can make the nearest surface belong to a neighboring cell. The template evaluates a 3×3 grid+around the query, then caps the march step by the horizontal distance to the boundary of the unvisited region.+That cap prevents skipping over a taller block outside the searched cells. It is a traversal bound, not visible+geometry. It stays positive at cell boundaries, so it cannot create a phantom hit there.++All modeled components fit their parcel. If balconies/bridges overhang farther, enlarge the searched neighborhood+and update its unvisited-region cap. For very large or sparse cities, a grid DDA/BVH and analytic ray-box tests are+usually more efficient than evaluating nine detailed buildings at every step.++## Materials, lighting and quality++| Layer | Template behavior | Upgrade for close/high-budget views |+|---|---|---|+| Building masses | Three stacked forms, three roof styles, a hero tower | More silhouette families and explicit grammar rules |+| Facades | Filtered material windows, stable occupied rooms | Frames, recesses, balconies, interiors/parallax volumes |+| Materials | Concrete/metal tint, dark glass approximation | Layered facade materials and reflected scene rays/probes |+| Lighting | PBR direct key, hemisphere fill, AO, soft shadows | Baked or dynamic GI, area lights and reflected emissive windows |+| Atmosphere | Analytic height fog | Physical sky/aerial perspective and volumetric shafts |+| Antialiasing | One sample by default | Set `AA = 4` for a still; tonemap each sample before averaging |++Warm windows are emissive color only. They do not illuminate neighboring buildings. Glass uses an artistic sky+term in its material, not traced interior transmission or full scene reflections. Keep these limits explicit when+using the template as a starting point for a product or architecture visualization.++`DEBUG_MODE` 2 shows normals, 3 parcel IDs, 4 step cost and 5 filtered window coverage. All are compiled/rendered+by the GPU harness, in addition to the beauty view. The numerical test checks periodicity and the filter's+large-footprint mean. Sweep the camera across a parcel boundary to inspect temporal stability.++## Use cases and extensions++- **Game skyline / background city:** keep masses simple, filter windows, fade distant detail and bake static+ lighting. Use instance meshes in an engine when geometry export, collisions or navigation are needed.+- **Hero skyscraper:** retain the mass/setback hierarchy, replace random repetition with intentional floor bands,+ model close recesses, and provide real reflected surroundings.+- **Residential district:** swap tower profiles for gabled roof primitives, smaller floor counts, larger setbacks+ and vegetation masks. Add a road/parcel generator if a non-grid layout is required.+- **Ancient/alien architecture:** combine `domPolar`, columns, arches and bounded decorative repetition. Keep the+ same separation between layout, structural distance, material masks and lighting.++## Sources++- [Müller et al., Procedural Modeling of Buildings, SIGGRAPH 2006](https://doi.org/10.1145/1141911.1141931):+ massing and hierarchical shape grammar concepts. The local shader is an original compact recipe, not their code.+- [Aliaga, Wonka et al., SIGGRAPH 2011 urban-modeling course](https://www.cs.purdue.edu/cgvlab/urban/sg_2011_course/contents.html):+ layout, building design, facades and the distinction between geometric generation and shading.+- [Quilez, filterable procedurals](https://iquilezles.org/articles/filterableprocedurals/): analytic footprint+ integration principle, reimplemented in `facadeWindowMask`.++The local implementation is MIT; no third-party shader source is copied.diff --git a/skills/shader-art-coding/references/subject-routing.md b/skills/shader-art-coding/references/subject-routing.mdindex 90a4559..de0aefc 100644--- a/skills/shader-art-coding/references/subject-routing.md+++ b/skills/shader-art-coding/references/subject-routing.md@@ -27,6 +27,9 @@ section with the formulas. The formula files use geometry-first names; this tabl| texture, material swatch, wallpaper | 2D procedural pattern | `pattern-swatches.glsl` || comparing noise families / learning noise | 2D scalar-field board | `noise-progression.glsl`; `noise-use-cases.md` || game heightmap, biome map, designed river | 2D height + separate masks | `noise-terrain-map.glsl`; `hybridTerrainHeight`; `noise-use-cases.md` |+| city, skyscraper, procedural building facade | SDF massing + filtered material fields | `procedural-city.glsl`; `procedural-buildings.md`; `buildingProfile`, `facadeWindowMask` |+| alpine valley, snow/rock biome, production terrain | designed heightfield + material masks | `alpine-valley.glsl`; `terrain-production.md` |+| clear coast, lagoon, shallow refractive water | water/land heightfields + secondary rays | `coastal-water.glsl`; `water-quality.md`; `waterWaveD`, `fresnelDielectric`, `beerTransmittance` |## Characters and creaturesdiff --git a/skills/shader-art-coding/references/terrain-production.md b/skills/shader-art-coding/references/terrain-production.mdnew file mode 100644index 0000000..cfcc7dd--- /dev/null+++ b/skills/shader-art-coding/references/terrain-production.md@@ -0,0 +1,115 @@+# Procedural terrain: silhouette to production++Use `templates/alpine-valley.glsl` for a designed valley with ridged/eroded detail, altitude/slope snow, rock strata,+grass and aerial depth. Use `terrain.glsl` for the existing physically based sky example; use+`noise-terrain-map.glsl` for a top-down height/river map. These are heightfields, not arbitrary 3D geology.++## Contents++- [Choose the representation](#choose-the-representation)+- [Build independent fields](#build-independent-fields)+- [Tracing and normals](#tracing-and-normals)+- [Materials and atmosphere](#materials-and-atmosphere)+- [Game integration and LOD](#game-integration-and-lod)+- [Quality checks](#quality-checks)+- [Sources](#sources)++## Choose the representation++| Need | Representation | Cost / limitation |+|---|---|---|+| Mountains, valleys, dunes, islands | Heightfield `y - h(xz)` | One height per horizontal point; no caves or overhangs |+| Caves, arches, undercuts | 3D density / SDF composition | More sampling and stricter distance bounds; meshing needs an extraction stage |+| Interactive terrain in a game | Chunked mesh/clipmap generated from fields | Requires LOD, seams, normals, colliders, streaming and stable coordinates |+| Real drainage/erosion | Separate simulation or constrained graph | A noise warp does not compute sediment transport or connected drainage |++The NVIDIA density-terrain source discusses a meshing pipeline. This repository's standalone examples raymarch+fields; they do not implement that chapter's marching-cubes extraction or GPU block streamer.++## Build independent fields++Choose the valley/canyon/island silhouette first. Add broad variation, then ridged or slope-damped detail. Reserve+river, road and settlement masks before adding high-frequency surface noise. Keep gameplay constraints independent+from aesthetic detail. A template's coordinate scale and altitude are artistic scene units unless explicitly+declared in meters/kilometers.++```glsl+vec2 terrainPlanningFields(vec2 world) {+ float corridor = 1.0 - exp(-0.085 * world.x * world.x);+ float relief = 0.8 + 1.4 * erodedFbm(world * 0.3, 6);+ float elevation = 0.18 + max(relief, 0.1) * corridor;+ return vec2(elevation, 1.0 - corridor);+}+```++The second channel is a planned lowland corridor. It is not guaranteed to drain downhill or connect to a river+outlet. See `noise-use-cases.md` for a deliberately designed river mask and the hybrid height helper.++`erodedFbm` damps detail using accumulated noise slope; it gives an eroded appearance without simulating erosion.+`ridgedFbm` emphasizes crests, while billow gives rounded lobes. Mix different roles rather than assigning all+octaves equal importance everywhere.++## Tracing and normals++`p.y - h(p.xz)` is a vertical gap, not a signed distance. A safe global conversion requires a bound `L` on the+height gradient: divide the gap by `sqrt(1 + L*L)`. An underestimated gradient bound can skip a thin ridge. The+alpine example uses an artistic scale of 0.12 for secondary shadows/AO. It is not a proven global Lipschitz bound+for arbitrary noise amplitudes or warp strengths. Its primary intersection uses distance-proportional sampling+with 320 iterations and ten bisection steps after a crossing. That eliminates the small-gap tracer's horizon+stalling, but a sufficiently narrow feature can still be missed between coarse samples.++For strict intersection guarantees, derive bounds for every composition or use a bracketed/refined heightfield+tracer with a sampling resolution matched to the smallest feature. For coarse-to-fine traversal, use min/max+height pyramids or hierarchical bounds. Do not increase displacement amplitude without updating traversal.++Normals should come from the same field and filtering as geometry. Analytic `gradientNoiseD` derivatives are+useful when every transform's chain rule is included. Otherwise use a finite-difference epsilon proportional to+the world-space pixel footprint; a fixed tiny epsilon makes distant snow/rock shimmer.++## Materials and atmosphere++| Field | Material use | Important control |+|---|---|---|+| Altitude | Snow line, tree line, sediment bands | World units; add a small low-frequency breakup |+| Upward normal | Snow accumulation, grass on flats, exposed rock on steep faces | Smooth transitions instead of binary masks |+| Slope / aspect | Wetness, sun-exposed versus sheltered terrain | Use the geometric normal and consistent sun direction |+| Surface grain | Rock color, roughness and fine detail | Fade frequencies that fall below a pixel |+| Planned corridor | Grass valley, river or road reservation | Carve/flatten geometry separately from painting a mask |+| Distance / height fog | Atmospheric depth between ridges | Match fog to the sky; avoid a separate grey horizon strip |++The alpine template uses analytic sky color and height fog for a compact reference. `terrain.glsl` demonstrates+the more expensive physical atmosphere. Snow is a material mask in both; neither simulates accumulation, melting+or wind transport. Rock strata affect color, not geological layers of separate geometry.++## Game integration and LOD++- Derive coordinates from stable global/chunk IDs. Camera-relative rendering can improve precision, but the+ procedural seed and phase must stay tied to the world.+- Sample the same boundary coordinates on neighboring chunks. Skirts alone hide gaps but do not make different+ height samples agree. Shared edge samples, transition meshes or geomorphing are needed for correct LOD seams.+- Evaluate geometric displacement at the mesh's resolvable scale. Put smaller detail into filtered normal or+ roughness fields. Generate colliders at a suitable gameplay resolution, not necessarily render resolution.+- Bake static expensive masks when appropriate. Update terrain, biome, water, foliage and collision data together+ when the base field changes. A rendered fragment shader is not an exported terrain asset.+- Heights alone do not guarantee navigability. Slope limits, road connectivity, playable areas and water outlets+ should be explicit constraints.++## Quality checks++The harness compiles and renders beauty plus elevation, normal, material and step-cost views. Inspect foreground,+silhouette, grazing views and multiple camera positions. No-NaN/nonblack rendering is a smoke test; it does not+prove intersection correctness or aesthetic quality. Inspect images after each field/lighting change.++For close views, add supersampling and shadow detail only after silhouettes and material separation read well.+For an engine, test across LOD transitions and chunk borders. For water/shore coupling, compare the actual surface+heights before choosing the visible material; sea-level altitude alone is insufficient when waves move.++## Sources++- [Ryan Geiss, GPU Gems 3 chapter 1](https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-1-generating-complex-procedural-terrains-using-gpu):+ density functions, caves/overhangs, GPU blocks and surface extraction; different from a simple heightfield.+- [Quilez, advanced noise](https://iquilezles.org/articles/morenoise/): derivative/slope-aware detail, credited+ by the existing `erodedFbm` implementation.+- [The Book of Shaders, fBm](https://thebookofshaders.com/13/): octave composition and ridged shaping.++The local shaders compose original MIT library functions; no external shader source is copied.diff --git a/skills/shader-art-coding/references/water-quality.md b/skills/shader-art-coding/references/water-quality.mdnew file mode 100644index 0000000..0322396--- /dev/null+++ b/skills/shader-art-coding/references/water-quality.md@@ -0,0 +1,162 @@+# High-quality water: surface, optics and integration++Use `templates/coastal-water.glsl` for shallow water with a visible seabed and shoreline. Use the existing+`ocean.glsl` for open-water swell, filtered microdetail, curvature foam and atmospheric sun glitter. Reusable+wave/optics functions are in `glsl/water.glsl`. Quality depends on the target scene, resolution and rendering budget;+there is no single shader that is highest quality in every setting.++## Contents++- [Choose a water target](#choose-a-water-target)+- [What the coastal example implements](#what-the-coastal-example-implements)+- [Wave geometry and normals](#wave-geometry-and-normals)+- [Optical paths](#optical-paths)+- [Filtering, foam and caustics](#filtering-foam-and-caustics)+- [Quality presets and debug views](#quality-presets-and-debug-views)+- [Production upgrades](#production-upgrades)+- [Validation and sources](#validation-and-sources)++## Choose a water target++| Target | Start from | Features that matter most |+|---|---|---|+| Clear coast / lagoon | `coastal-water.glsl` | Correct seabed intersections, refraction, depth absorption, shore contact |+| Open ocean | `ocean.glsl` | Wave spectrum, distance filtering, wide glints, whitecaps, atmosphere |+| Calm reflective lake | Coastal optics + low wave amplitudes | Reflected surroundings, low-frequency ripples, depth tint |+| River | Terrain corridor + flow-oriented waves | Surface slope, varying velocity, bank interaction, foam advection |+| Underwater view | Separate inside-medium camera path | Correct IOR direction, TIR, fog/scattering, shafts and surface underside |+| Film/export still | Quality 3 plus engine/path-tracer extensions | More samples, scene reflection/transmission, GI and coherent detail |++The coastal camera is above water. Changing its height to a negative value does not create a correct underwater+renderer: the medium, normal orientation, refraction ratio and absorption segments must be changed deliberately.++## What the coastal example implements++- An animated sum of sine waves with analytic height, horizontal derivatives and Laplacian.+- Gravity-wave dispersion at a fixed 3 m reference depth. This avoids an incorrect spatially varying phase term;+ it is not bathymetric wave refraction/shoaling or a breaking-wave solver.+- Primary intersection against the higher of water and terrain, so exposed land occludes the water.+- A refracted ray to the same procedural seabed used by the primary scene, with optical path-length attenuation.+- A reflected ray to exposed land in quality 2/3; sky reflection in every preset.+- Exact unpolarized air-water Fresnel, GGX sun glints and separate reflected/transmitted contributions.+- RGB Beer-Lambert attenuation and an artistic approximation to in-scattered water-body light.+- Filtered fine waves, increased unresolved-wave roughness, shoreline/curvature foam, and an artistic seabed+ caustic pattern. These last terms are not simulated spray, transported foam, or photon-traced caustics.+- A bounded ray budget with a distant mean-water-plane fallback; waves far below pixel size become a smooth+ rough reflection instead of a broken sky/water checker pattern.++The primary/secondary tracer takes a distance-dependent minimum step and refines detected crossings by ten+bisection steps. This avoids grazing-angle stalls; it is a sampled heightfield method, not a proof that an+arbitrarily narrow changed feature cannot be skipped. Keep displacement and trace resolution consistent.++Land in this small scene is an analytic island heightfield. It is included to exercise reflected/refracted+geometry and shore contact, not to claim a photoreal island asset or a coupled coastal simulation.++## Wave geometry and normals++`waterDispersion(k, depth, g)` evaluates `sqrt(g*k*tanh(k*depth))`. `waterWaveD` returns+`vec4(height, dh/dx, dh/dz, Laplacian)` for one wave. Wavelength/amplitude/depth are meters, time is seconds,+gravity is m/s², and input direction is normalized internally. A zero direction uses +X.++```glsl+vec4 coastalWaveSample(vec2 worldXZ, float time, float pixelFootprintMeters) {+ vec4 swell = waterWaveD(worldXZ, time, vec2(0.8,0.6), 4.5, 0.075, 3.0, pixelFootprintMeters);+ vec4 chop = waterWaveD(worldXZ, time, vec2(-0.3,0.9), 1.2, 0.018, 3.0, pixelFootprintMeters);+ return swell + chop;+}+```++Convert the summed slope to `normalize(vec3(-dh_dx, 1, -dh_dz))`. The analytic derivatives treat footprint as+constant locally. If amplitude, depth or direction varies with position, include the derivatives of that envelope+or phase, or use finite differences on the complete field. Applying spatial shoaling to height while ignoring it+in normals produces inconsistent glints.++Finite-depth dispersion alone does not solve shoaling, wave refraction around bathymetry, horizontal Gerstner+displacement or breaking. The existing ocean template uses a sharpened exp-sine profile rather than this sine+helper; those profiles should not be conflated.++## Optical paths++Use the refracted path to the bottom, not vertical water depth, for absorption. `EXTINCTION` is RGB extinction+per meter. Red attenuating faster than green/blue can give clear water its depth-dependent hue. The values in the+demo are artistic coefficients, not measured ocean-water data.++```glsl+vec3 coastalOpticalMix(vec3 reflectedLight, vec3 bottomLight, vec3 scatterColor,+ vec3 extinctionPerMeter, float refractedPath, float cosIncident) {+ float F = fresnelDielectric(cosIncident, 1.0, 1.333);+ vec3 T = beerTransmittance(extinctionPerMeter, refractedPath);+ vec3 transmittedLight = bottomLight * T + scatterColor * (1.0 - T);+ return reflectedLight * F + transmittedLight * (1.0 - F);+}+```++This is a compact radiance composition with approximate scattering, not a full participating-medium integrator.+The bottom's sunlight is also attenuated along its light path in the template. Environment reflection, direct sun+specular and foam remain separate so they can be inspected for double-counting and tuned deliberately.++For total internal reflection use `fresnelDielectric(cosIncident, 1.333, 1.0)` when the incident medium is water.+The helper returns 1 above the critical angle. Do not blindly use the above-air eta ratio for underwater rays.++## Filtering, foam and caustics++Remove geometric/normal waves as their wavelengths approach 2–6 pixel footprints. Add unresolved slope energy to+roughness rather than leaving subpixel normals active. The coastal example uses a compact roughness ramp; the+open-ocean example has more detailed directional footprint and lost-slope-variance tracking.++Shore foam compares moving surface height against the seabed and uses a patterned shallow band. Crest foam uses+negative Laplacian as an artistic coverage cue. Both are instantaneous fields. A production foam system should+advect, accumulate and decay foam, with separate spray if required.++The bright seabed pattern is filtered and attenuated by depth/light direction, but it is not generated from the+surface-to-bottom refraction Jacobian. For physically meaningful caustics, use photon mapping, refracted light+tracing or a controlled projected-caustic method that accounts for energy/area changes.++## Quality presets and debug views++| `QUALITY` | Samples / waves / primary iteration cap | Reflection |+|---|---|---|+| 1 | 1 / 8 / 180 | Sky only; still traces refraction to seabed |+| 2 (default) | 1 / 8 / 180 | Sky plus exposed-land ray |+| 3 | 4 / 12 / 240 | Sky plus exposed-land ray; more surface detail and AA |++These are budgets, not promised FPS. The harness renders all three presets on the current GPU and in CI.+Secondary rays use the same bounded iteration cap. Four samples are useful for a still but do not equal a+converged path-traced image. More waves change detail, not the underlying fluid model.++`DEBUG_MODE`: 1 optical path, 2 water normals, 3 foam, 4 primary cost, 5 Fresnel, 6 RGB transmittance. The quality+presets and every debug view are compile-checked and rendered through `@variant` annotations. Diagnostic masks+can be legitimately mostly black; the harness's no-NaN checks still matter.++## Production upgrades++| Goal | Add outside this standalone single-pass example |+|---|---|+| Large wind-driven ocean | Measured/specified spectral model, FFT cascades, stable patch blending and floating origin |+| Hero breaking surf | Coupled shallow-water/fluid simulation, displacement/velocity fields, foam transport and spray |+| Reliable scene reflections | Ray tracing or planar reflection plus SSR/probe fallbacks, rough-reflection filtering |+| Temporal stability | Jittered sampling, motion vectors, history rejection, TAA/accumulation and exposure control |+| Underwater realism | Medium-aware ray segments, multiple scattering approximations, shafts and surface underside |+| Interactive shores | Scene-depth intersections, object displacement, wetness/foam history and bathymetry coupling |+| Export-quality film | More samples and light bounces, spectral/volume treatment when needed, denoising and measured validation |++Pick improvements from the target and budget rather than turning every setting up. “Highest quality” needs a+reference image, target resolution/frame time and host renderer to be a measurable requirement. The skill should+state which of these features are actually implemented whenever proposing a production water solution.++## Validation and sources++GPU properties check wave derivatives against finite differences, Laplacian identity, dispersion limits, Fresnel+normal incidence/reciprocity/TIR, and attenuation bounds/zero path/composition over segments. Images are also+inspected for shore leaks, missing horizon samples, aliasing and reflected-land placement.++- [Mark Finch, GPU Gems chapter 1](https://developer.nvidia.com/gpugems/gpugems/part-i-natural-effects/chapter-1-effective-water-simulation-physical-models):+ wave sums, analytic normals, surface detail and Gerstner alternatives.+- [MIT Marine Hydrodynamics, lecture 20](https://ocw.mit.edu/courses/2-20-marine-hydrodynamics-13-021-spring-2005/5d48a5937971d973fd8ca90c051a83f8_lecture20.pdf):+ finite-depth gravity-wave dispersion and deep/shallow limits.+- [PBRT, specular reflection and transmission](https://www.pbr-book.org/4ed/Reflection_Models/Specular_Reflection_and_Transmission)+ and [transmittance](https://www.pbr-book.org/4ed/Volume_Scattering/Transmittance): dielectric Fresnel and Beer attenuation.+- [GPU Gems 2 chapter 19](https://developer.nvidia.com/gpugems/gpugems2/part-ii-shading-lighting-and-shadows/chapter-19-generic-refraction-simulation):+ scene-buffer refraction as an engine-side alternative; not the actual ray-to-heightfield method used here.++All shipped implementations are original MIT GLSL, with technique credits in `CREDITS.md`.diff --git a/skills/shader-art-coding/scripts/glsl_tools.py b/skills/shader-art-coding/scripts/glsl_tools.pyindex f2a7005..7187cb4 100644--- a/skills/shader-art-coding/scripts/glsl_tools.py+++ b/skills/shader-art-coding/scripts/glsl_tools.py@@ -30,8 +30,8 @@ INDEX_PATH = REF_DIR / "library-index.md"# Declaration order: a module may only depend on modules listed before it.MODULE_ORDER = [- "common", "hash", "noise", "pattern", "sdf3d", "sdf2d", "operators", "domain", "raymarch", "intersect",- "camera", "shading", "color", "tonemap", "volume", "atmosphere", "post", "debug",+ "common", "hash", "noise", "pattern", "sdf3d", "sdf2d", "operators", "domain", "architecture", "raymarch", "intersect",+ "camera", "shading", "water", "color", "tonemap", "volume", "atmosphere", "post", "debug",]SHADERTOY_PRELUDE = """#version 300 es@@ -286,9 +286,23 @@ def bundle_source(lib: Library, user_src: str, keep_docs: bool = True) -> str:# Keep user #defines (e.g. DEBUG_MODE, AA) at the very top so library code can see them.lines = user_src.splitlines()lead = 0- while lead < len(lines) and (lines[lead].startswith(("#", "//")) or not lines[lead].strip()):+ while lead < len(lines) and (lines[lead].lstrip().startswith(("#", "//")) or not lines[lead].strip()):lead += 1- directives = [i for i in range(lead) if lines[i].startswith("#")]+ # Never insert dependencies inside a conditional whose body starts with a declaration.+ # A quality-preset #if followed by a const used to hide the entire library on its false branch.+ directives = []+ depth = 0+ for i in range(lead):+ match = re.match(r"\s*#\s*(\w+)", lines[i])+ if not match:+ continue+ word = match.group(1)+ if word in ("if", "ifdef", "ifndef"):+ depth += 1+ elif word == "endif":+ depth -= 1+ if depth == 0:+ directives.append(i)cut = directives[-1] + 1 if directives else 0while cut < lead and lines[cut].strip() == "":cut += 1@@ -472,6 +486,17 @@ def library_units(lib: Library) -> dict[str, str]:return units+def template_variants(src: str) -> list[tuple[str, str]]:+ """Materialize explicitly annotated quality/debug presets; reject an annotation with no matching define."""+ variants = []+ for key, value in re.findall(r"//\s*@variant\s+(\w+)=(\d+)", src):+ variant, count = re.subn(rf"(^\s*#define\s+{re.escape(key)}\s+)\d+", rf"\g<1>{value}", src, flags=re.M)+ if count != 1:+ raise ValueError(f"@variant {key}={value} needs exactly one matching #define")+ variants.append((f"{key.lower()}-{value}", variant))+ return variants++def all_units(lib: Library) -> tuple[dict[str, str], list[Finding]]:"""Every compile unit the skill ships: library modules, reference snippets, templates."""findings: list[Finding] = []@@ -496,6 +521,8 @@ def all_units(lib: Library) -> tuple[dict[str, str], list[Finding]]:where = f"templates/{tpl.name}"findings += lint_shader(src, where, complete=True)units[where] = shader_unit(lib, src)+ for name, variant in template_variants(src):+ units[f"templates/{tpl.stem}--{name}"] = shader_unit(lib, variant)return units, findingsdiff --git a/skills/shader-art-coding/templates/alpine-valley.glsl b/skills/shader-art-coding/templates/alpine-valley.glslnew file mode 100644index 0000000..8f60a36--- /dev/null+++ b/skills/shader-art-coding/templates/alpine-valley.glsl@@ -0,0 +1,99 @@+// Alpine valley: designed lowland corridor, multiscale ridges, snow accumulation, strata and aerial depth.+// A heightfield cannot make overhangs. The controlled valley is not a drainage/erosion simulation.+// @render time=0.0+// @variant DEBUG_MODE=1+// @variant DEBUG_MODE=2+// @variant DEBUG_MODE=3+// @variant DEBUG_MODE=4+#define DEBUG_MODE 0 // 0 beauty | 1 elevation | 2 normal | 3 grass/rock/snow | 4 steps+const vec3 ALPINE_SUN=normalize(vec3(-0.65,0.42,-0.25));+const float SNOW_ALTITUDE=1.9;+const float FAR_DISTANCE=70.0;+const int ALPINE_TRACE_STEPS=320;++float alpineHeight(vec2 p) {+ float valley=1.0-exp(-0.085*p.x*p.x);+ float peaks=0.65+1.8*erodedFbm(p*vec2(0.30,0.25)+vec2(2.0,7.0),6)+ +0.35*ridgedFbm(p*0.2,4);+ float broad=0.5+0.5*fbm(p*0.12,4);+ float detail=0.06*fbm(p*1.8,3);+ return 0.18+(1.3+3.1*peaks+1.0*broad)*valley+detail;+}++vec2 map(vec3 p) {return vec2((p.y-alpineHeight(p.xz))*0.12,1.0);}++// Coarse-to-fine heightfield intersection. Distance-proportional sampling avoids the asymptotic+// slowdown of a small globally scaled gap near the horizon; crossings are refined by bisection.+vec3 traceAlpine(vec3 ro,vec3 rd) {+ float t=0.02,previous=0.0;+ for(int i=0;i<ALPINE_TRACE_STEPS;i++) {+ vec3 p=ro+rd*t;+ float gap=p.y-alpineHeight(p.xz);+ if(gap<0.0) {+ float lo=previous,hi=t;+ for(int j=0;j<10;j++) {+ float mid=0.5*(lo+hi);+ vec3 q=ro+rd*mid;+ if(q.y>alpineHeight(q.xz))lo=mid;else hi=mid;+ }+ return vec3(0.5*(lo+hi),1.0,float(i));+ }+ previous=t;+ t+=0.04+0.015*t;+ if(t>FAR_DISTANCE)break;+ }+ return vec3(-1.0,0.0,float(ALPINE_TRACE_STEPS));+}++vec3 alpineSky(vec3 rd) {+ vec3 c=simpleSky(rd,ALPINE_SUN);+ // A broad cloud mask in sky-direction space; it is not a cloud volume.+ float cloud=smoothstep(0.1,0.5,fbm(rd.xz/max(rd.y+0.45,0.15)*1.2,4));+ return mix(c,vec3(0.86,0.88,0.91),cloud*0.45*smoothstep(0.05,0.4,rd.y));+}++vec3 alpineRender(vec2 coord) {+ vec2 uv=(2.0*coord-iResolution.xy)/iResolution.y;+ vec3 ro=vec3(0.15,2.1,10.0-0.25*iTime);+ ro.y=max(ro.y,alpineHeight(ro.xz)+0.7);+ vec3 rd=cameraRay(cameraMatrix(ro,vec3(0.0,1.9,-15.0),0.0),uv,1.8);+ vec3 sky=alpineSky(rd);+ vec3 hit=traceAlpine(ro,rd);+#if DEBUG_MODE == 4+ return debugHeat(hit.z/float(ALPINE_TRACE_STEPS));+#endif+ if(hit.x<0.0)return sky;+ vec3 p=ro+rd*hit.x;+ float footprint=hit.x*2.0/(iResolution.y*1.8);+ vec3 n=calcNormal(p,max(0.002,footprint*0.5));+ float snow=smoothstep(SNOW_ALTITUDE-0.3,SNOW_ALTITUDE+0.4,p.y+0.22*fbm(p.xz*2.0,3))+ *smoothstep(0.35,0.75,n.y);+ float grass=smoothstep(0.6,0.9,n.y)*(1.0-smoothstep(1.4,2.5,p.y));+ float detailKeep=1.0-smoothstep(0.02,0.2,footprint);+ float grain=0.5+0.5*fbm(p.xz*18.0,3)*detailKeep;+ float strata=0.5+0.5*sin(p.y*35.0+fbm(p.xz*3.0,3)*2.0);+ vec3 rock=mix(vec3(0.16,0.15,0.14),vec3(0.32,0.29,0.25),grain)*(0.85+0.15*strata*detailKeep);+ vec3 albedo=mix(rock,mix(vec3(0.075,0.12,0.035),vec3(0.16,0.20,0.065),grain),grass);+ albedo=mix(albedo,vec3(0.78,0.84,0.9),snow);+ float shadow=softShadow(p+n*0.03,ALPINE_SUN,0.03,15.0,12.0);+ vec3 col=shadePBR(n,-rd,ALPINE_SUN,albedo,0.8,0.0)*vec3(3.4,3.0,2.5)*shadow;+ col+=albedo*hemisphereLight(n,vec3(0.4,0.58,0.85),vec3(0.16,0.13,0.095));+#if DEBUG_MODE == 1+ return vec3(p.y/6.0);+#elif DEBUG_MODE == 2+ return n*0.5+0.5;+#elif DEBUG_MODE == 3+ return vec3(grass,1.0-grass,snow);+#endif+ vec3 haze=alpineSky(normalize(vec3(rd.x,0.04,rd.z)));+ float fog=heightFog(ro,rd,hit.x,0.011,0.18);+ return mix(col,haze,fog);+}++void mainImage(out vec4 fragColor,in vec2 fragCoord) {+ vec3 col=alpineRender(fragCoord);+#if DEBUG_MODE == 0+ col=linearToSrgb(tonemapAgX(col*1.15))+ditherTPDF(fragCoord,iFrame);+#endif+ fragColor=vec4(col,1.0);+}diff --git a/skills/shader-art-coding/templates/coastal-water.glsl b/skills/shader-art-coding/templates/coastal-water.glslnew file mode 100644index 0000000..4e4fa67--- /dev/null+++ b/skills/shader-art-coding/templates/coastal-water.glsl@@ -0,0 +1,181 @@+// Coastal water: analytic finite-depth waves, refracted seabed, reflected land, exact interface Fresnel,+// RGB Beer-Lambert attenuation, scattered-light approximation, shore/crest foam, GGX glints and filtered ripples.+// Single-pass visual study, not fluid simulation: caustics are artistic; reflected waves/multiple scattering are omitted.+// @render time=5.0+// @variant QUALITY=1+// @variant QUALITY=3+// @variant DEBUG_MODE=1+// @variant DEBUG_MODE=2+// @variant DEBUG_MODE=3+// @variant DEBUG_MODE=4+// @variant DEBUG_MODE=5+// @variant DEBUG_MODE=6+#define QUALITY 2 // 1 interactive: sky reflection | 2 high: land reflection | 3 still: 4x AA, more waves/steps+#define DEBUG_MODE 0 // 0 beauty | 1 optical path | 2 normals | 3 foam | 4 primary steps | 5 Fresnel | 6 transmission+const int WATER_AA=QUALITY==3?4:1;+const int WATER_WAVES=QUALITY==3?12:8;+const int WATER_STEPS=QUALITY==3?240:180;+const vec3 COAST_SUN=normalize(vec3(-0.35,0.62,-0.55));+const vec3 EXTINCTION=vec3(0.42,0.085,0.045); // illustrative clear turquoise water, 1/m+const float WATER_IOR=1.333;+const float WATER_FAR=95.0;++float coastBed(vec2 p) {+ vec2 a=p-vec2(-7.0,-8.0),b=p-vec2(7.0,-19.0),c=p-vec2(-5.0,-1.0);+ float islands=5.7*exp(-0.055*dot(a,a))+5.0*exp(-0.07*dot(b,b))+1.1*exp(-0.15*dot(c,c));+ return -2.4+islands*(1.0+0.18*gradientNoise(p*0.75))+0.12*sin(p.x*1.7)*sin(p.y*1.2);+}++vec3 coastBedNormal(vec2 p,float eps) {+ vec2 d=vec2(coastBed(p+vec2(eps,0.0))-coastBed(p-vec2(eps,0.0)),+ coastBed(p+vec2(0.0,eps))-coastBed(p-vec2(0.0,eps)))/(2.0*eps);+ return normalize(vec3(-d.x,1.0,-d.y));+}++vec4 coastWaves(vec2 p,float footprint) {+ vec4 sum=vec4(0.0);+ for(int i=0;i<WATER_WAVES;i++) {+ float fi=float(i);+ float angle=0.7+fi*2.39996;+ float wavelength=4.5*pow(0.69,fi);+ float amp=0.075*pow(0.58,fi);+ // Fixed reference depth in phase avoids spatially varying frequency drifting out of phase along the shore.+ sum+=waterWaveD(p+vec2(fi*1.37,fi*0.79),iTime,vec2(cos(angle),sin(angle)),wavelength,amp,3.0,footprint);+ }+ return sum;+}++vec2 traceCoast(vec3 ro,vec3 rd,bool includeWater,int maxSteps) {+ float t=0.01,previous=0.0;+ float closing=max(0.05,abs(rd.y)+4.0*length(rd.xz));+ for(int i=0;i<WATER_STEPS;i++) {+ if(i>=maxSteps)break;+ vec3 p=ro+rd*t;+ float h=coastBed(p.xz);+ if(includeWater) {+ float geometryFootprint=2.0*t/(iResolution.y*1.75*max(abs(rd.y),0.1));+ h=max(h,coastWaves(p.xz,geometryFootprint).x);+ }+ float gap=p.y-h;+ if(gap<0.0) {+ float lo=previous,hi=t;+ for(int j=0;j<10;j++) {+ float mid=0.5*(lo+hi);+ vec3 q=ro+rd*mid;+ float surface=coastBed(q.xz);+ if(includeWater) {+ float fp=2.0*mid/(iResolution.y*1.75*max(abs(rd.y),0.1));+ surface=max(surface,coastWaves(q.xz,fp).x);+ }+ if(q.y>surface)lo=mid;else hi=mid;+ }+ return vec2(0.5*(lo+hi),float(i));+ }+ previous=t;+ t+=max(gap/closing,0.012+0.008*t);+ if(t>WATER_FAR)break;+ }+ if(includeWater && rd.y < -0.0001) return vec2(max(0.01,-ro.y/rd.y),float(maxSteps));+ return vec2(-1.0,float(maxSteps));+}++vec3 coastSky(vec3 rd) {+ vec3 c=mix(vec3(0.22,0.40,0.60),vec3(0.025,0.13,0.36),sqrt(max(rd.y,0.0)));+ float clouds=smoothstep(0.1,0.55,fbm(rd.xz/max(rd.y+0.4,0.15)*1.3,4));+ c=mix(c,vec3(0.95,0.97,1.0),clouds*0.18*smoothstep(0.03,0.3,rd.y));+ return c+vec3(9.0,8.0,6.0)*sunDisk(rd,COAST_SUN,0.012,0.002);+}++vec3 shadeCoastBed(vec3 p,vec3 n,bool submerged,float footprint) {+ float grain=0.5+0.5*fbm(p.xz*2.5,4)*(1.0-smoothstep(0.03,0.25,footprint));+ float rock=smoothstep(0.45,1.0,p.y)*(1.0-smoothstep(0.65,0.9,n.y));+ vec3 sand=mix(vec3(0.38,0.29,0.15),vec3(0.7,0.59,0.37),grain);+ vec3 albedo=mix(sand,vec3(0.17,0.15,0.12),rock);+ float vegetation=smoothstep(1.2,2.0,p.y)*smoothstep(0.5,0.82,n.y);+ albedo=mix(albedo,vec3(0.07,0.12,0.025),vegetation);+ vec3 direct=vec3(2.5,2.3,1.9)*max(dot(n,COAST_SUN),0.0);+ if(submerged) {+ direct*=beerTransmittance(EXTINCTION,max(-p.y,0.0)/COAST_SUN.y);+ float caustic=pow(max(0.0,sin(p.x*7.0+sin(p.z*4.0+iTime)*1.3)*sin(p.z*6.0+cos(p.x*4.0-iTime)*1.2)),9.0);+ float keep=1.0-smoothstep(0.02,0.12,footprint);+ direct*=1.0+caustic*keep*1.2; // projected artistic caustic pattern, not photon transport+ }+ return albedo*(direct+hemisphereLight(n,vec3(0.35,0.43,0.5),vec3(0.12,0.10,0.07)));+}++vec3 renderCoast(vec2 coord) {+ vec2 uv=(2.0*coord-iResolution.xy)/iResolution.y;+ vec3 ro=vec3(0.0,3.5,7.5);+ vec3 rd=cameraRay(cameraMatrix(ro,vec3(-0.8,-0.1,-6.0),0.0),uv,1.75);+ vec3 sky=coastSky(rd);+ vec2 hit=traceCoast(ro,rd,true,WATER_STEPS);+#if DEBUG_MODE == 4+ return debugHeat(hit.y/float(WATER_STEPS));+#endif+ if(hit.x<0.0)return sky;+ vec3 p=ro+rd*hit.x;+ float footprint=2.0*hit.x/(iResolution.y*1.75);+ float bed=coastBed(p.xz);+ vec3 col;+ if(bed>p.y-0.015) {+ vec3 n=coastBedNormal(p.xz,max(footprint,0.003));+ col=shadeCoastBed(p,n,false,footprint);+ } else {+ vec4 waves=coastWaves(p.xz,footprint/max(abs(rd.y),0.1));+ vec3 n=normalize(vec3(-waves.y,1.0,-waves.z));+ vec3 v=-rd;+ float F=fresnelDielectric(max(dot(n,v),0.0),1.0,WATER_IOR);+ vec3 refracted=refract(rd,n,1.0/WATER_IOR);+ vec2 bottomHit=traceCoast(p-n*0.006,refracted,false,WATER_STEPS);+ float path=bottomHit.x>0.0?bottomHit.x:30.0;+ vec3 bottomPoint=p-n*0.006+refracted*path;+ vec3 bottomColor=shadeCoastBed(bottomPoint,coastBedNormal(bottomPoint.xz,0.01),true,footprint);+ vec3 T=beerTransmittance(EXTINCTION,path);+ vec3 body=bottomColor*T+vec3(0.012,0.19,0.24)*(1.0-T); // approximate in-scattered body light+ vec3 reflected=reflect(rd,n);+ vec3 reflection=coastSky(normalize(vec3(reflected.x,max(reflected.y,0.01),reflected.z)));+#if QUALITY >= 2+ vec2 reflectedHit=traceCoast(p+n*0.015,reflected,false,WATER_STEPS);+ if(reflectedHit.x>0.0) {+ vec3 rp=p+n*0.015+reflected*reflectedHit.x;+ if(rp.y>0.02)reflection=shadeCoastBed(rp,coastBedNormal(rp.xz,0.015),false,footprint);+ }+#endif+ float unresolved=smoothstep(0.02,0.18,footprint);+ float rough=mix(0.075,0.20,unresolved);+ vec3 glint=specularGGX(n,v,COAST_SUN,rough,vec3(0.02037))*vec3(3.5,3.2,2.7);+ float shallow=1.0-smoothstep(0.08,0.5,max(p.y-bed,0.0));+ float shorePulse=0.5+0.5*sin((p.y-bed)*19.0-iTime*1.5+fbm(p.xz*2.0,3)*3.0);+ float foam=shallow*smoothstep(0.25,0.7,shorePulse)*0.8;+ foam+=0.12*smoothstep(0.18,0.6,-waves.w)*(1.0-unresolved);+ foam=clamp(foam,0.0,1.0);+ col=mix(body*(1.0-F)+reflection*F+glint,vec3(0.8,0.84,0.82),foam);+#if DEBUG_MODE == 1+ return vec3(path/12.0);+#elif DEBUG_MODE == 2+ return n*0.5+0.5;+#elif DEBUG_MODE == 3+ return vec3(foam);+#elif DEBUG_MODE == 5+ return vec3(F);+#elif DEBUG_MODE == 6+ return T;+#endif+ }+ return mix(col,coastSky(normalize(vec3(rd.x,0.025,rd.z))),1.0-exp(-hit.x*0.003));+}++void mainImage(out vec4 fragColor,in vec2 fragCoord) {+ vec3 col=vec3(0.0);+ for(int i=0;i<WATER_AA;i++) {+ vec3 c=renderCoast(fragCoord+(WATER_AA>1?aaOffset(i):vec2(0.0)));+#if DEBUG_MODE == 0+ c=tonemapAgX(c*1.05);+#endif+ col+=c/float(WATER_AA);+ }+#if DEBUG_MODE == 0+ col=linearToSrgb(col)+ditherTPDF(fragCoord,iFrame);+#endif+ fragColor=vec4(col,1.0);+}diff --git a/skills/shader-art-coding/templates/procedural-city.glsl b/skills/shader-art-coding/templates/procedural-city.glslnew file mode 100644index 0000000..a1a67fa--- /dev/null+++ b/skills/shader-art-coding/templates/procedural-city.glsl@@ -0,0 +1,115 @@+// Parcel -> mass -> setback -> roof -> facade. Original texture-free city at blue hour.+// 3x3 neighbor checks plus an unvisited-cell distance cap prevent taller remote blocks being skipped.+// Windows are filtered material fields; their emission is illustrative, not global illumination.+// @render time=4.0+// @variant DEBUG_MODE=2+// @variant DEBUG_MODE=3+// @variant DEBUG_MODE=4+// @variant DEBUG_MODE=5+#define DEBUG_MODE 0 // 0 beauty | 2 normals | 3 parcel IDs | 4 steps | 5 window mask+const float PARCEL = 3.6;+const vec3 CITY_SUN = normalize(vec3(-0.6,0.6,0.4));+const int AA = 1; // set 4 for stills++vec4 cityProfile(vec2 id) {+ vec4 b = buildingProfile(id,vec2(2.8,13.0),vec2(0.75,1.13));+ if (length(id)<0.5) b=vec4(18.0,1.15,1.15,2.0);+ return b;+}++vec2 map(vec3 p) {+ vec2 id=domRepeatId(p.xz,vec2(PARCEL));+ vec2 local=p.xz-id*PARCEL;+ vec2 res=vec2(p.y,0.0);+ for(int z=-1;z<=1;z++) for(int x=-1;x<=1;x++) {+ vec2 cell=id+vec2(float(x),float(z));+ vec4 b=cityProfile(cell);+ vec3 q=p-vec3(cell.x*PARCEL,0.0,cell.y*PARCEL);+ float body=sdRoundBox(q-vec3(0.0,b.x*0.38,0.0),vec3(b.y,b.x*0.38,b.z)-0.035,0.035);+ float upper=sdRoundBox(q-vec3(0.0,b.x*0.83,0.0),vec3(b.y*0.72,b.x*0.17,b.z*0.72)-0.025,0.025);+ float podium=sdBox(q-vec3(0.0,0.35,0.0),vec3(b.y+0.15,0.35,b.z+0.15));+ float d=min(podium,min(body,upper));+ if(b.w>0.5) d=min(d,sdBox(q-vec3(0.0,b.x+0.22,0.0),vec3(b.y*0.45,0.22,b.z*0.5)));+ if(b.w>1.5) d=min(d,sdCapsule(q,vec3(0.0,b.x,0.0),vec3(0.0,b.x+1.1,0.0),0.035));+ if(d<res.x)res=vec2(d,1.0);+ }+ float unvisited=min(1.5*PARCEL-abs(local.x),1.5*PARCEL-abs(local.y));+ res.x=min(res.x,unvisited);+ return res;+}++vec3 citySky(vec3 rd) {+ float h=smoothstep(-0.12,0.7,rd.y);+ vec3 c=mix(vec3(0.10,0.12,0.19),vec3(0.012,0.028,0.07),h);+ c+=vec3(0.12,0.055,0.025)*pow(max(dot(rd,CITY_SUN),0.0),12.0);+ return c;+}++vec3 renderCity(vec2 coord) {+ vec2 uv=(2.0*coord-iResolution.xy)/iResolution.y;+ float orbit=0.5+0.035*iTime;+ vec3 ro=vec3(32.0*sin(orbit),17.0,32.0*cos(orbit));+ vec3 rd=cameraRay(cameraMatrix(ro,vec3(0.0,6.0,0.0),0.0),uv,1.85);+ vec3 sky=citySky(rd);+ vec3 hit=raymarch(ro,rd,0.05,110.0,0.95);+#if DEBUG_MODE == 4+ return debugHeat(hit.z/256.0);+#endif+ if(hit.x<0.0)return sky;+ vec3 p=ro+rd*hit.x;+ vec3 n=calcNormal(p,max(0.001,hit.x*0.00015));+ vec2 id=domRepeatId(p.xz,vec2(PARCEL));+ vec4 b=cityProfile(id);+ float variation=hash12(id);+ float fp=2.0*hit.x/(iResolution.y*1.85);+ fp/=max(abs(dot(n,rd)),0.15);+ vec3 albedo=mix(vec3(0.16,0.19,0.21),vec3(0.32,0.29,0.25),variation);+ float windows=0.0;+ vec3 emission=vec3(0.0);+ if(hit.y>0.5 && n.y<0.6) {+ vec2 facade=vec2(abs(n.x)>abs(n.z)?p.z:p.x,p.y);+ vec2 grid=facade/vec2(0.30,0.43);+ windows=facadeWindowMask(grid,vec2(0.62,0.65),vec2(fp*3.8,fp*2.5));+ float occupied=step(0.42,hash13(vec3(floor(grid+0.5),variation*100.0)));+ float keep=1.0-smoothstep(0.3,1.2,fp/0.30);+ occupied=mix(0.58,occupied,keep);+ vec3 glass=vec3(0.018,0.035,0.055)+citySky(reflect(rd,n))*0.3;+ albedo=mix(albedo,glass,windows);+ emission=windows*occupied*mix(vec3(0.6,0.22,0.055),vec3(1.2,0.74,0.33),variation)*0.8;+ } else if(hit.y<0.5) {+ albedo=vec3(0.045,0.05,0.06);+ vec2 streets=abs(domRepeat(p.xz,vec2(PARCEL)));+ float marking=(1.0-smoothstep(0.025,0.025+fp,abs(streets.x-PARCEL*0.5)))+ *filteredStripes(p.z*1.3,fp*1.3);+ albedo=mix(albedo,vec3(0.42,0.32,0.13),marking);+ }+ float ao=calcAO(p,n,0.18);+ float shadow=softShadow(p+n*0.015,CITY_SUN,0.02,20.0,10.0);+ vec3 col=shadePBR(n,-rd,CITY_SUN,albedo,0.4,0.15)*vec3(0.9,0.75,0.6)*shadow;+ col+=albedo*hemisphereLight(n,vec3(0.30,0.43,0.66),vec3(0.07,0.065,0.055))*ao;+ col+=emission;+#if DEBUG_MODE == 2+ return n*0.5+0.5;+#elif DEBUG_MODE == 3+ return hash33(vec3(id,0.0));+#elif DEBUG_MODE == 5+ return vec3(windows);+#endif+ float haze=heightFog(ro,rd,hit.x,0.006,0.055);+ return mix(col,citySky(normalize(vec3(rd.x,0.06,rd.z))),haze);+}++void mainImage(out vec4 fragColor,in vec2 fragCoord) {+ vec3 col=vec3(0.0);+ for(int i=0;i<AA;i++) {+ vec3 sampleColor=renderCity(fragCoord+(AA>1?aaOffset(i):vec2(0.0)));+#if DEBUG_MODE == 0+ sampleColor=tonemapAgX(sampleColor*1.05);+#endif+ col+=sampleColor/float(AA);+ }+#if DEBUG_MODE == 0+ col=linearToSrgb(col)+ditherTPDF(fragCoord,iFrame);+#endif+ fragColor=vec4(col,1.0);+}diff --git a/tests/build_harness.py b/tests/build_harness.pyindex e1f5787..84ab8ca 100644--- a/tests/build_harness.py+++ b/tests/build_harness.py@@ -116,6 +116,13 @@ def build(save_gallery: bool = False) -> Path:m = re.search(r"//\s*@render\s+time=([\d.]+)", src)renders.append({"name": tpl.stem, "time": float(m.group(1)) if m else 2.0,"code": gt.SHADERTOY_PRELUDE + gt.bundle_source(lib, src, keep_docs=False) + gt.MAIN_COMPLETE})+ # Explicit template presets/debug views are compiled AND rendered in CI. Keep them out of the gallery;+ # they are diagnostic variants, not additional public examples.+ for variant_name, variant in gt.template_variants(src):+ name = f"{tpl.stem}--{variant_name}"+ code = gt.SHADERTOY_PRELUDE + gt.bundle_source(lib, variant, keep_docs=False) + gt.MAIN_COMPLETE+ renders.append({"name": name, "time": float(m.group(1)) if m else 2.0,+ "code": code, "diagnostic": True})data = {"units": units, "tests": tests, "renders": renders, "save": save_gallery,"lint": [str(f) for f in findings]}out_dir = ROOT / "build"diff --git a/tests/harness_template.html b/tests/harness_template.htmlindex 220d9cc..c78bc54 100644--- a/tests/harness_template.html+++ b/tests/harness_template.html@@ -131,7 +131,7 @@ async function main() {const url = canvas.toDataURL('image/png');const fig = document.createElement('figure'); fig.innerHTML = `<img src="${url}"><figcaption>${r.name} · ${ms.toFixed(0)} ms · mean ${stats.mean.toFixed(3)}</figcaption>`;div.appendChild(fig);- if (DATA.save) await fetch('/save?path=gallery/' + r.name + '.png', { method: 'POST', body: url });+ if (DATA.save && !r.diagnostic) await fetch('/save?path=gallery/' + r.name + '.png', { method: 'POST', body: url });results.renders.push({ name: r.name, ok, stats });line(ok ? 'ok' : 'bad', `${ok ? 'PASS' : 'FAIL'} ${r.name} nan=${stats.nanPct.toFixed(2)}% black=${stats.blackPct.toFixed(1)}% mean=${stats.mean.toFixed(3)} >1=${stats.overPct.toFixed(2)}%`);await sleep();diff --git a/tests/properties.py b/tests/properties.pyindex 3bb9d58..41303ea 100644--- a/tests/properties.py+++ b/tests/properties.py@@ -129,6 +129,61 @@ EXACT_ALLOWANCE = 0.01# Hand-written properties. Each body is the inside of `int runTest(vec4 a, vec4 b)`; return failure bits.PROPERTIES = [+ ("building profiles remain inside declared ranges", """+ vec2 id = floor((a.xy-0.5)*200.0);+ vec4 p = buildingProfile(id,vec2(3.0,16.0),vec2(0.6,1.2));+ int f=0;+ if (p.x<3.0 || p.x>16.0 || any(lessThan(p.yz,vec2(0.6))) || any(greaterThan(p.yz,vec2(1.2)))) f|=1;+ if (p.w<0.0 || p.w>2.0 || p.w!=floor(p.w)) f|=2;+ if (any(notEqual(p,buildingProfile(id,vec2(3.0,16.0),vec2(0.6,1.2))))) f|=4;+ return f;""", {}),+ ("facade filtering: range, periodicity, large-footprint mean", """+ vec2 uv=(a.xy-0.5)*10.0;+ vec2 fill=vec2(0.6,0.7);+ float m=facadeWindowMask(uv,fill,vec2(0.03));+ int f=0;+ if(isnan(m) || m<0.0 || m>1.0) f|=1;+ if(abs(m-facadeWindowMask(uv+vec2(2.0,-3.0),fill,vec2(0.03)))>0.001) f|=2;+ if(abs(facadeWindowMask(uv,fill,vec2(4.0))-0.42)>0.0001) f|=4;+ if(facadeWindowMask(uv,vec2(0.0),vec2(4.0))!=0.0 || abs(facadeWindowMask(uv,vec2(1.0),vec2(4.0))-1.0)>0.00001) f|=8;+ return f;""", {}),+ ("water wave derivatives and finite-depth dispersion", """+ vec2 p=(a.xy-0.5)*10.0;+ vec4 w=waterWaveD(p,1.7,vec2(0.8,0.6),4.0,0.2,2.0,0.001);+ float e=0.002;+ vec2 fd=vec2(waterWaveD(p+vec2(e,0.0),1.7,vec2(0.8,0.6),4.0,0.2,2.0,0.001).x-waterWaveD(p-vec2(e,0.0),1.7,vec2(0.8,0.6),4.0,0.2,2.0,0.001).x,+ waterWaveD(p+vec2(0.0,e),1.7,vec2(0.8,0.6),4.0,0.2,2.0,0.001).x-waterWaveD(p-vec2(0.0,e),1.7,vec2(0.8,0.6),4.0,0.2,2.0,0.001).x)/(2.0*e);+ int f=0;+ if(length(w.yz-fd)>0.001) f|=1;+ if(abs(w.w+(TAU/4.0)*(TAU/4.0)*w.x)>0.0001) f|=2;+ if(waterDispersion(2.0,0.5,9.81)>waterDispersion(2.0,5.0,9.81)) f|=4;+ if(abs(waterDispersion(2.0,100.0,9.81)-sqrt(19.62))>0.0001) f|=8;+ if(waterDispersion(0.0,2.0,9.81)!=0.0 || waterDispersion(2.0,0.0,9.81)!=0.0) f|=16;+ vec4 filteredWave=waterWaveD(p,1.7,vec2(0.0),4.0,0.2,2.0,3.0);+ if(any(isnan(filteredWave)) || any(notEqual(filteredWave,vec4(0.0)))) f|=32;+ return f;""", {}),+ ("dielectric Fresnel: bounds, normal incidence, reciprocity, TIR", """+ float ci=0.02+0.98*a.x;+ float eta=1.05+1.0*a.y;+ float fr=fresnelDielectric(ci,1.0,eta);+ float ct=sqrt(1.0-(1.0-ci*ci)/(eta*eta));+ int f=0;+ if(isnan(fr) || fr<0.0 || fr>1.0) f|=1;+ if(abs(fresnelDielectric(1.0,1.0,eta)-pow((eta-1.0)/(eta+1.0),2.0))>0.00001) f|=2;+ if(abs(fr-fresnelDielectric(ct,eta,1.0))>0.001) f|=4;+ if(fresnelDielectric(0.2,1.333,1.0)!=1.0) f|=8;+ if(fresnelDielectric(0.0,1.0,1.0)!=0.0 || fresnelDielectric(ci,1.0,1.0)!=0.0) f|=16;+ return f;""", {}),+ ("Beer transmittance: bounds, zero path, semigroup", """+ vec3 sigma=a.xyz*2.0;+ float d=b.x*5.0;+ vec3 t=beerTransmittance(sigma,d);+ int f=0;+ if(any(lessThan(t,vec3(0.0))) || any(greaterThan(t,vec3(1.0)))) f|=1;+ if(any(notEqual(beerTransmittance(sigma,0.0),vec3(1.0)))) f|=2;+ if(length(t-beerTransmittance(sigma,d*0.4)*beerTransmittance(sigma,d*0.6))>0.00001) f|=4;+ if(any(notEqual(beerTransmittance(-sigma,d),vec3(1.0)))) f|=8;+ return f;""", {}),("hash ranges and integer-input semantics", """vec2 cell = floor((a.xy - 0.5) * 2e5);int f = 0;diff --git a/tests/test_bundler.py b/tests/test_bundler.pynew file mode 100644index 0000000..12ca52e--- /dev/null+++ b/tests/test_bundler.py@@ -0,0 +1,58 @@+"""Regression coverage for dependency insertion around quality-preset preprocessor blocks."""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "skills/shader-art-coding/scripts"))+import glsl_tools as gt+++class ConditionalPreamble(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.lib = gt.Library()++ def test_open_conditional_does_not_hide_dependencies(self):+ source = """#define QUALITY 2+#if QUALITY == 3+const int AA = 4;+#else+const int AA = 1;+#endif+float scene(vec2 p) { return gradientNoise(p); }+"""+ result = gt.bundle_source(self.lib, source)+ self.assertLess(result.index("#define QUALITY"), result.index("float gradientNoise("))+ self.assertLess(result.index("float gradientNoise("), result.index("#if QUALITY"))+ self.assertIn("const int AA = 1;", result)++ def test_balanced_macro_block_stays_before_library(self):+ source = """#define QUALITY 2+#if QUALITY == 3+#define AA 4+#else+#define AA 1+#endif+float scene(vec2 p) { return gradientNoise(p); }+"""+ result = gt.bundle_source(self.lib, source)+ self.assertLess(result.index("#endif"), result.index("float gradientNoise("))++ def test_indented_open_conditional_is_safe(self):+ source = " #if QUALITY == 3\nconst int AA = 4;\n #endif\nfloat scene(vec2 p) { return gradientNoise(p); }"+ result = gt.bundle_source(self.lib, source)+ self.assertLess(result.index("float gradientNoise("), result.index("#if QUALITY"))++ def test_annotated_variant_changes_only_its_define(self):+ variants = gt.template_variants("// @variant QUALITY=3\n#define QUALITY 2 // budget\n#define DEBUG_MODE 0\n")+ self.assertEqual(variants[0][0], "quality-3")+ self.assertIn("#define QUALITY 3 // budget", variants[0][1])+ self.assertIn("#define DEBUG_MODE 0", variants[0][1])++ def test_missing_variant_define_is_rejected(self):+ with self.assertRaises(ValueError):+ gt.template_variants("// @variant QUALITY=3\n#define DEBUG_MODE 0\n")+++if __name__ == "__main__":+ unittest.main()