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.
GLSL Library Index
Generated by scripts/glsl_tools.py index. Do not edit by hand.
Call these functions by name in your shader, then run
python3 scripts/glsl_tools.py bundle your.glsl -o out.glsl to inline exactly what it uses.
Find candidates with python3 scripts/glsl_tools.py search <words>.
Tags: exact is a true Euclidean distance, safe for blending, AO, shadows and offsets. bound never overestimates, so it is safe to march, but less accurate for offsets. approx has an exact surface but may overestimate in places; read its note for a safe step scale.
Contents
- common - constants, rotation, remapping and shaping functions
- hash - integer hashes and float wrappers for lattice ids
- noise - value, gradient and simplex noise (2D/3D, analytic derivatives), fBm, turbulence and billow, domain warping, curl flow, Voronoi, dithering
- pattern - tilings and antialiased procedural patterns
- sdf3d - 3D signed distance primitives
- sdf2d - 2D signed distance primitives for posters, icons, UI, motion graphics, and as profiles for opExtrude / opRevolve
- operators - combine distances (booleans, smooth blends, chamfers, stairs) and reshape them (round, onion, extrude, revolve, elongate)
- domain - transform the point BEFORE evaluating a distance (repetition, mirroring, polar sectors, folds, twist, bend)
- architecture - stable building parameters and filtered facade fields
- raymarch - sphere tracing, normals, soft shadows and ambient occlusion for SDF scenes
- intersect - analytic ray-primitive intersections
- camera - look-at frames, primary rays, field of view, thin-lens depth of field
- shading - BRDF terms and practical lighting models
- water - finite-depth wave dispersion, analytic wave derivatives, exact dielectric Fresnel and RGB attenuation
- color - transfer functions, perceptual color (Oklab / OkLCh), palettes, luminance, blackbody light colors
- tonemap - map scene-linear HDR to display range
- volume - participating media (fog, smoke, clouds, haze)
- atmosphere - skies and sun
- post - antialiasing helpers, supersampling offsets, lens effects, grain and dithering, all single-pass
- debug - visualize intermediate fields
common
common: constants, rotation, remapping and shaping functions. Target: GLSL ES 3.00 (Shadertoy / WebGL2). Every function here is original and MIT licensed.
const float PI = 3.14159265358979;const float TAU = 6.28318530717959;float saturate(float x)/vec3 saturate(vec3 x)- Clamp to [0,1]. Use: masks, weights, colors.float dot2(vec2 v)/float dot2(vec3 v)- Squared length. Use: cheap distance comparisons, SDF internals.mat2 rot2(float a)- 2D rotation matrix.rot2(a) * vrotates v counter-clockwise by a radians. (cos, sin) is renormalized because GLSL ES leaves trig precision undefined: on SwiftShader and some mobile GPUs a raw cos/sin pair is far enough from unit length that rotations stop preserving distances. Use: spinning parts, posing limbs, rotating octaves, camera roll.float remap(float x, float a, float b, float c, float d)- Linear remap of x from [a,b] to [c,d] (unclamped). Use: converting ranges, rescaling noise.float linearstep(float a, float b, float x)- Linear ramp from 0 at a to 1 at b, clamped. Use: masks whose falloff should not ease in or out.float cubicPulse(float c, float w, float x)- Smooth bump: 1 at x == c, falling to 0 at |x - c| >= w (cubic). Use: stripes, rings, highlights at one height, pulses in time.float expImpulse(float x, float k)- Fast attack, exponential decay. Peaks at 1 when x == 1/k. Use: heartbeat motion, impacts, flashes, plucked-string envelopes.float gain(float x, float k)- Contrast curve on [0,1] that keeps 0, 0.5 and 1 fixed. k > 1 adds contrast, k < 1 flattens. Use: tightening masks, adjusting animation easing.float parabola(float x, float k)- 0 at x = 0 and x = 1, peak 1 at x = 0.5; k sharpens. Use: petal width along length, leaf profiles, arches.float almostIdentity(float x, float m, float n)- Returns x when x > m; smoothly bottoms out at n when x -> 0. Needs 2n < m. Use: avoiding hard zero in falloffs, soft floor on thickness.
hash
hash: integer hashes and float wrappers for lattice ids. Naming: hashNM returns N floats from M inputs (hash12 = 1 output, 2 inputs). Outputs are in [0,1). The float wrappers hash INTEGER-VALUED inputs (cell ids, pixel coords, frame numbers). Fractional parts are dropped. That is deliberate: negative float -> uint is undefined in GLSL, and round() can return -0.0, which has different bits from 0.0. Converting through int avoids both. To hash a continuous value, scale it first. Do not use fract(sin(dot(p, k)) * 43758.5453): its result changes across GPUs and degrades at large inputs. Integer mixers are from Jarzynski and Olano, "Hash Functions for GPU Rendering" (JCGT 2020): pcg3d and pcg4d sit on that study's quality/speed frontier, and 32-bit integer math is bit-exact on every GPU, unlike sin().
uint pcgHash(uint v)- PCG-style 1D integer hash. Use: seeding, per-instance randomness, building other hashes.uvec3 pcg3d(uvec3 v)- 3D integer hash, three decorrelated outputs. Use: 3D cell ids, voxel jitter, (pixel, frame) noise.uvec4 pcg4d(uvec4 v)- 4D integer hash, four decorrelated outputs (0 BigCrush failures in the JCGT study). Use: (pixel.x, pixel.y, frame, sample) streams for stochastic sampling, 4D cell ids.float uintToUnit(uint h)/vec2 uintToUnit(uvec2 h)/vec3 uintToUnit(uvec3 h)/vec4 uintToUnit(uvec4 h)- Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.float hash11(float p)- Random float in [0,1) for an integer-valued input. Use: per-cell randomness, stable random per instance id. Range [0,1).float hash12(vec2 p)- Random float in [0,1) for an integer-valued 2D input. Use: per-cell variation (color, height, rotation), sparse spots, star fields. Range [0,1).float hash13(vec3 p)- Random float in [0,1) for an integer-valued 3D input. Use: per-voxel randomness, per-pixel-per-frame noise via hash13(vec3(fragCoord, iFrame)). Range [0,1).vec2 hash22(vec2 p)- Random vec2 in [0,1)^2 for an integer-valued 2D input. Use: Voronoi feature points, 2D jitter, random gradients. Range [0,1)^2.vec3 hash33(vec3 p)- Random vec3 in [0,1)^3 for an integer-valued 3D input. Use: 3D Voronoi points, random colors per cell, random directions. Range [0,1)^3.vec4 hash44(vec4 p)- Random vec4 in [0,1)^4 for an integer-valued 4D input. Use: per-pixel, per-frame, per-sample random numbers: hash44(vec4(fragCoord, iFrame, sampleIndex)). Range [0,1)^4.vec3 hash32(vec2 p)- Random vec3 in [0,1)^3 for an integer-valued 2D input. Use: per-tile random color, per-cell (offset, rotation, scale) triples. Range [0,1)^3.
noise
noise: value, gradient and simplex noise (2D/3D, analytic derivatives), fBm, turbulence and billow, domain warping, curl flow, Voronoi, dithering. Every function here is texture-free and original. The math follows the cited articles. Ranges are approximate unless stated. Noise built on integer hashes stays stable at large coordinates until float precision runs out (|p| around 1e5). Re-center long animations with mod/fract on time.
vec2 quinticFade(vec2 f)/vec3 quinticFade(vec3 f)- Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise. Use: custom lattice noises, smooth cell interpolation.vec2 quinticFadeDeriv(vec2 f)/vec3 quinticFadeDeriv(vec3 f)- Derivative of quinticFade: 30 t^2 (t - 1)^2. Use: analytic noise derivatives.vec3 valueNoiseD(vec2 p)- 2D value noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Use: terrain base layers, cheap clouds, anything needing normals without finite differences. Range value in [0,1].float valueNoise(vec2 p)/float valueNoise(vec3 p)- 2D value noise. Use: soft blotches, low-frequency color variation. Range [0,1].vec2 latticeGradient(vec2 cell)- Unit gradient for a 2D lattice point.vec3 gradientNoiseD(vec2 p)/vec4 gradientNoiseD(vec3 p)- 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm. Use: fBm, terrain with analytic normals, curl flow, marble and wood distortions. Range value in about [-0.7,0.7].float gradientNoise(vec2 p)/float gradientNoise(vec3 p)- 2D gradient noise. Use: general-purpose smooth noise. Range about [-0.7,0.7].vec3 simplexNoiseD(vec2 p, float rotation)/vec3 simplexNoiseD(vec2 p)- 2D simplex noise with analytic gradient. Returns vec3(value, d/dx, d/dy). Sums three radial kernels (0.5 - r^2)^4 on a triangular lattice instead of blending four square-cell corners, so it has fewer axis-aligned artifacts than gradientNoise. rotation (radians) spins every lattice gradient: animating it gives flow noise that churns in place instead of sliding (Perlin and Neyret 2001). Scaled so |value| <= 1 exactly. Use: flowing water and lava (animate rotation), ripples with analytic normals, isotropic fBm, swirling fields. Range value in [-1,1].float simplexNoise(vec2 p)- 2D simplex noise. Use: isotropic smooth noise, fBm layers without grid alignment. Range [-1,1].float latticeGradDot(vec3 cell, vec3 corner, vec3 f)- Dot product of a hashed 3D gradient with the offset to its lattice corner.const int FBM_MAX_OCTAVES = 12;float fbm(vec2 p, int octaves, float lacunarity, float persistence)/float fbm(vec2 p, int octaves)/float fbm(vec3 p, int octaves, float lacunarity, float persistence)- Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher. Use: clouds, terrain, dirt, roughness breakup, warping input. Range about [-1,1].float erodedFbm(vec2 p, int octaves)- Terrain fBm where each octave is damped by the accumulated slope, so detail settles in valleys and steep slopes stay smooth. This gives an eroded look without simulation. Use: mountains, dunes, rocky ground. Range about [-0.5,1].float ridgedFbm(vec2 p, int octaves)- Ridged multifractal: inverted |noise| creates sharp crests; each octave is weighted by the previous one, so detail gathers along ridges. Use: mountain ridges, lightning-like veins, canyons, eroded rock, alien landscapes. Range about [0,1].float turbulence(vec2 p, int octaves)/float turbulence(vec3 p, int octaves)- Perlin's turbulence: fBm of |noise|. The absolute value folds every zero crossing into a sharp crease, at every scale. Use: fire, marble veins (sin(x + k * turbulence)), smoke wisps, electric glow, lava cracks, wind-torn clouds. Range [0,1].float billowFbm(vec2 p, int octaves)/float billowFbm(vec3 p, int octaves)- Billowy multifractal: |noise| per octave makes puffy rounded lobes split by sharp creases (the inverse of ridgedFbm). Each octave is weighted by the previous one, so detail gathers on the lobes while the creases stay clean. Use: cumulus and cauliflower tops, puffy smoke, foam clumps, rock piles, cotton, popcorn-like bumps. Range [0,1].float warpedFbm(vec2 p, float strength, int octaves, out vec2 q, out vec2 r)- Two-level domain warp f(p + sr), r = fbm(p + sq), q = fbm(p). Writes the intermediate warp vectors so they can drive color. Cost is 5 fBm calls. Use: marble, smoke, agate, alien skies, painterly backgrounds. Range about [-1,1].vec2 curlNoise(vec2 p)/vec3 curlNoise(vec3 p)- Divergence-free 2D flow field: the curl of scalar gradient noise. Particles advected by it swirl without bunching up. Use: smoke advection, flowing paint, hair/fur flow direction, wind.vec4 voronoi(vec2 p, float jitter)- Cellular (Worley/Voronoi) noise. Returns vec4(F1, F2, nearestCell.xy). F1 = distance to nearest feature point, F2 = second nearest. nearestCell is integer-valued, so hash it for per-cell randomness. jitter in [0,1] (0 = regular grid). Searches 3x3 cells. F2 can be slightly off at jitter 1. Use: cells, scales, stones, cracked mud (F2-F1), caustics, foam, sparkles. Range F1 in [0, ~1.2].vec3 voronoiBorder(vec2 p, float jitter)- Exact distance to Voronoi cell borders, found in two passes: nearest point, then nearest bisector. Returns vec3(borderDistance, vectorToNearestPoint). Unlike F2-F1, the border distance is a true distance, so lines have constant width. Use: cell walls, stained glass leading, cracked earth, giraffe and leaf-vein patterns, crackle glaze.float smoothVoronoi(vec2 p, float k)- Smooth Voronoi: a soft-min of distances to feature points. Cells become blobs with no creases. k controls smoothness (large = sharper; around 8-32). Searches 5x5 cells so low k has no seams. Use: organic cell clusters, bubbles, lumpy surfaces, skin pores.float hybridTerrainHeight(vec2 p, int octaves)- Bounded hybrid terrain recipe: broad gradient fBm, warped ridged detail and cellular breakup. This is an artistic composition, not Musgrave's named hybrid-multifractal algorithm. Coordinates are warped before all three fields are sampled; octaves is clamped to [1, FBM_MAX_OCTAVES]. Use: game heightmaps, rocky islands, biome elevation masks, alien terrain. Range [0,1].float interleavedGradientNoise(vec2 pixel)/float interleavedGradientNoise(vec2 pixel, int frame)- Interleaved gradient noise: cheap per-pixel noise whose 3x3 neighborhoods are nearly stratified. Not a hash. pixel must be integer pixel coordinates (floor(fragCoord)). The frame overload animates it for accumulation and TAA. Use: removing banding before 8-bit output, jittering ray start offsets, stochastic transparency. Range [0,1).float r2Dither(vec2 pixel)- R2 low-discrepancy dither mask (plastic-constant sequence), folded by a triangle wave for an even spread. Use: ordered dithering without textures, posterized and retro looks, sample offsets. Range [0,1).
pattern
pattern: tilings and antialiased procedural patterns. The filtered versions integrate the pattern over the pixel footprint (box filter), so floors and stripes stay clean in the distance with no supersampling. Filtering math follows https://iquilezles.org/articles/checkerfiltering/ and /filterableprocedurals/.
vec2 triangleWave(vec2 x)- Triangle wave, the integral of a square wave. Building block for box-filtered patterns. Use: writing new filtered patterns.float filteredChecker(vec2 p, vec2 w)- Box-filtered checkerboard with unit squares: 0 or 1 up close, fading to 0.5 where squares are smaller than a pixel. Compute the footprint before any branching: w = fwidth(p) (or max(abs(dFdx(p)), abs(dFdy(p)))). Use: floors, chessboards, test patterns, racing flags, tablecloths. Range [0,1].float filteredGrid(vec2 p, vec2 w, float n)- Box-filtered grid lines (unit cells, line width = 1/n of a cell). Returns 1 on lines, 0 inside cells. Use: blueprints, graph paper, tiles with grout, sci-fi floors, synthwave grids. Range [0,1].float filteredStripes(float x, float w)- Box-filtered stripes along x with period 1 and duty cycle 0.5. Returns 0..1. Use: awnings, candy, zebra (warp x first), barcodes, road markings. Range [0,1].vec4 hexGrid(vec2 p)- Hexagonal tiling with unit spacing between neighboring centers. Neighbors sit left/right, so hexes are pointy-top. Returns vec4(local offset from the hex center, integer-valued hex id). Use: honeycomb, scales, tiles, game boards, hex pixelation.float hexEdgeDistance(vec2 local)- Distance from a hexGrid local coordinate to its hexagon's edge (0.5 at the center, 0 on the edge). Use: hex borders, bevels, edge wear on tiles.float truchetArcs(vec2 p, float w)- Truchet tiling of quarter-circle arcs, randomly flipped per cell. Returns signed distance to arcs of half-width w. Use: maze-like ornaments, pipes, Celtic-style weaves, procedural circuitry.
sdf3d
sdf3d: 3D signed distance primitives. Each one is centered at the origin unless noted. Move or rotate the point before calling (sdBox(p - center, size)), never the result. Exactness tags: @exact true Euclidean distance inside and outside (safe for smooth blending, AO, soft shadows, offsets) @bound never overestimates (Lipschitz <= 1), so raymarching is safe, but offsets and blends are less accurate @approx exact zero set but may overestimate in places (see the function's note for the safe stepScale) Formulas follow Inigo Quilez's distance-function catalog (https://iquilezles.org/articles/distfunctions/). Implementations here are original and checked by tests/ (sign, Lipschitz bound, eikonal).
float sdSphere(vec3 p, float r)exact - Sphere of radius r. Use: heads, eyes, fruit, planets, bubbles, joints.float sdBox(vec3 p, vec3 b)exact - Axis-aligned box with half-extents b. Use: buildings, crates, bricks, pedestals, furniture.float sdRoundBox(vec3 p, vec3 b, float r)exact - Box with rounded edges. The outer size stays b; r is the edge radius (r <= min(b)). Use: toys, product shots, soft architecture, dice, phone-like slabs.float sdBoxFrame(vec3 p, vec3 b, float e)exact - Wireframe box: edges of a box with half-extents b and edge thickness e. Use: scaffolding, cages, display frames, sci-fi structures.float sdTorus(vec3 p, vec2 t)exact - Torus in the XZ plane. t.x = major radius, t.y = tube radius. Use: rings, donuts, tires, halos, lifebuoys.float sdCappedTorus(vec3 p, vec2 sc, float ra, float rb)exact - Partial torus (arc) in the XY plane, symmetric about +Y. sc = vec2(sin, cos) of the half-aperture angle, ra = major radius, rb = tube radius. Use: horns, handles, eyebrows, arches, croissant shapes, magnets.float sdLink(vec3 p, float le, float r1, float r2)exact - Chain link: a torus stretched along Y by le. r1 = major radius, r2 = tube radius. Use: chains, rings, jewelry, fences.float sdPlane(vec3 p, vec3 n, float h)exact - Infinite plane through the origin offset by h along unit normal n: dot(p, n) + h. Use: ground, walls, water surface, clipping half-spaces.float sdCapsule(vec3 p, vec3 a, vec3 b, float r)exact - Capsule: segment a-b swept by radius r. Use: limbs, fingers, branches, hair strands, pills, bones.float sdVerticalCapsule(vec3 p, float h, float r)exact - Vertical capsule from y = 0 to y = h, radius r. Use: upright limbs, posts, bottles, candles.float sdCylinder(vec3 p, float h, float r)exact - Vertical capped cylinder from y = -h to y = +h, radius r. Use: columns, cans, coins, logs, wheels (rotate first).float sdCappedCone(vec3 p, float h, float r1, float r2)exact - Capped cone (frustum) from y = -h (radius r1) to y = +h (radius r2). Set r2 = 0 for a pointed cone. Exact everywhere, including the base cap. Points below the base are outside. Use: trees, roofs, spikes, lampshades, volcanoes, party hats, vases.float sdCone(vec3 p, float h, float r)exact - Pointed cone with its base disk (radius r) at y = 0 and apex at y = h. Use: evergreen trees, spikes, horns, mountains, wizard hats.float sdRoundCone(vec3 p, float r1, float r2, float h)exact - Round cone: sphere r1 at y = 0 smoothly hulled with sphere r2 at y = h. Use: limbs, fingers, tree trunks, carrots, teardrops, tentacle segments.float sdEllipsoid(vec3 p, vec3 r)approx - Ellipsoid with semi-axes r. A fast approximation: the zero set is exact and the field is a bound outside for aspect ratios up to about 2:1. Inside, and for more stretched ellipsoids, the gradient exceeds 1 (measured: 2.5 at 4:1). March with stepScale 0.7-0.8 there, or build long shapes from sdCapsule / sdRoundCone instead. Use: heads, bodies, eggs, pebbles, leaves (flat), muscles, clouds of blobs.float sdCutHollowSphere(vec3 p, float r, float h, float t)exact - Hollow spherical cap (bowl) of radius r, cut by the plane y = h, with shell thickness t. The opening faces +Y. Use: bowls, cups, helmets, shells, satellite dishes, eye sockets.float sdHexPrism(vec3 p, vec2 h)exact - Hexagonal prism along Z. h.x = inradius of the hexagon, h.y = half-length. Use: pencils, bolts, crystals, basalt columns, honeycomb cells.float sdOctahedron(vec3 p, float s)bound - Regular octahedron with "radius" s (vertex distance from center). Bound version. Use: gems, crystals, diamonds, abstract motifs.float sdGyroid(vec3 p, float scale, float t)bound - Gyroid sheet with cell scalescaleand half-thickness t. The infinite triply-periodic surface sin x cos y + sin y cos z + sin z cos x = 0. Intersect with a bounding shape. Use: lattices, coral, bone interiors, sponges, sci-fi infill, organic architecture.float sdCutSphere(vec3 p, float r, float h)exact - Sphere of radius r cut by the plane y = h, keeping the cap ABOVE the plane. h = 0 gives a dome on the ground; negative h keeps more than half. Needs |h| < r. Use: domes, mushroom caps, half-buried rocks, igloos, bread loaves.float sdDeathStar(vec3 p, float ra, float rb, float d)exact - Sphere ra at the origin with sphere rb at (d, 0, 0) carved out, exact including the crease rim. A plain opSubtract of two spheres is only a bound. Use: eye sockets, craters, bitten fruit, nostrils, scooped shapes.float sdQuadraticBezier(vec3 pos, vec3 A, vec3 B, vec3 C)exact - Unsigned distance to a 3D quadratic Bezier curve A-B-C; subtract a radius for a tube. Solves the closest-point cubic analytically. Falls back to a segment when the curve is straight. Use: hair strands, tentacles, stems, whiskers, horns, cables, curved tubes.
sdf2d
sdf2d: 2D signed distance primitives for posters, icons, UI, motion graphics, and as profiles for opExtrude / opRevolve. Centered at the origin unless noted. Negative inside. Formulas follow Inigo Quilez's 2D distance catalog (https://iquilezles.org/articles/distfunctions2d/). Implementations are original and tested (sign, Lipschitz, brute-force distance for curves). Tags: @exact true distance, @bound never overestimates, @approx exact zero set but may overestimate in places.
float sdCircle(vec2 p, float r)exact - Circle of radius r. Use: dots, eyes, suns, bubbles, rings (with opOnion).float sdBox(vec2 p, vec2 b)exact - Axis-aligned rectangle with half-extents b. Use: panels, bars, windows, buttons, building silhouettes.float sdRoundedBox(vec2 p, vec2 b, vec4 r)exact - Rectangle with half-extents b and per-corner radii r = (top-right, bottom-right, top-left, bottom-left). Use: UI cards, buttons, speech bubbles, tags, rounded windows.float sdSegment(vec2 p, vec2 a, vec2 b)exact - Unsigned distance to segment a-b. Subtract a width to get a stroke. Use: lines, strokes, stems, rays, hands of a clock, rain streaks.float sdUnevenCapsule(vec2 p, float r1, float r2, float h)exact - Tapered capsule: circle r1 at origin hulled with circle r2 at (0, h). Use: petals, tails, teardrops, brush dabs, fingers, flames.float sdArc(vec2 p, vec2 sc, float ra, float rb)exact - Circular arc symmetric about +Y. sc = vec2(sin, cos) of the half-aperture, ra = radius, rb = stroke half-width. Use: smiles, eyebrows, rainbows, gauges, progress rings, horseshoes.float sdEquilateralTriangle(vec2 p, float r)exact - Equilateral triangle with circumradius-like size r, pointing up. Use: play icons, warning signs, mountains, arrows, tri-patterns.float sdTriangle(vec2 p, vec2 p0, vec2 p1, vec2 p2)exact - Arbitrary triangle p0, p1, p2 (any winding). Use: shards, low-poly art, arrowheads, beaks, teeth.float sdRegularPolygon(vec2 p, float r, int n)exact - Regular n-gon with circumradius r, one vertex pointing up. Use: badges, hexagonal tiles, pentagons, stop signs, gems (2D).float sdStar(vec2 p, float r, int n, float m)exact - Star with n points and outer radius r. m in [2, n] sets the inner angle: m = 2 is the spikiest and m = n is a regular n-gon. Use: stars, sparkles, badges, flowers (with opRound), sheriff badges.float sdVesica(vec2 p, float r, float d)exact - Vesica (lens): intersection of two circles of radius r whose centers sit at (+-d, 0). Points along Y. Needs d < r. Use: leaves, petals, eyes, fish bodies, almond shapes, gothic arches.float sdMoon(vec2 p, float d, float ra, float rb)exact - Crescent: disk ra at origin minus disk rb at (d, 0). Use: moons, claws, bananas (bent), shadows on spheres, logos.float sdHeart(vec2 p)exact - Heart with its bottom tip at the origin, about 1 unit tall. Use: hearts, valentines, health icons, leaves (squashed).float sdRhombus(vec2 p, vec2 b)exact - Rhombus with half-diagonals b. Use: diamonds, kites, card suits, argyle, harlequin patterns.float sdEllipse(vec2 p, vec2 r)approx - Ellipse with semi-axes r. A fast approximation: exact zero set, a bound outside up to about 2:1 aspect, gradient above 1 inside and for flatter ellipses. Fine for fills and strokes; avoid for exact offsets. Use: eyes, pupils, ovals, shadows under objects, planet rings (with opOnion).float sdQuadraticBezier(vec2 pos, vec2 A, vec2 B, vec2 C)exact - Unsigned distance to a quadratic Bezier curve A-B-C. Solves the closest-point cubic analytically. Falls back to a segment when the curve degenerates to a line. Float error in the cubic solve is about 1e-4. Use: brush strokes, hair, calligraphy, tendrils, eyelashes, smooth paths, font-like curves.float sdPie(vec2 p, vec2 sc, float r)exact - Pie slice (circular sector) of radius r, symmetric about +Y. sc = vec2(sin, cos) of the half-aperture, which may go up to pi (a full disk); past pi/2 the slice is concave. Use: pie charts, pac-man, fans, radar sweeps, pizza slices, clock wedges, 2D spotlight cones.float sdHorseshoe(vec2 p, vec2 sc, float r, float legLength, float w)exact - Horseshoe: an arc of radius r over the top (half-aperture given by sc = vec2(sin, cos), as in sdArc) whose ends run on as straight legs of length legLength along the arc's tangent, stroked with half-width w and round ends. The legs must not cross the Y axis (keep legLength * |cos(aperture)| below r * sin(aperture)). Use: horseshoes, magnets, U-bends, arches with posts, croquet hoops, handles, headphones (2D).float sdParabolaSegment(vec2 p, float w, float h)exact - Parabolic arch: the region under y = h (1 - x^2 / w^2) and above y = 0, so half-width w at the base and height h. The closest point on the curve is the largest root of a depressed cubic, solved in closed form. Use: arches, bridges, tunnels, domes, bullets, gothic windows, tents, fountain jets, bell curves.float sdEgg(vec2 p, float ra, float rb)exact - Egg built from four tangent arcs (Moss-style): a bottom half-disk of radius ra centered at the origin, a top cap of radius rb, and two side arcs of radius 2 ra joining them. rb = ra is a disk; smaller rb makes a pointier egg. Spans y from -ra to sqrt((2 ra - rb)^2 - ra^2) + rb. Needs 0 < rb <= ra. Use: eggs, droplets, pebbles, seeds, cartoon heads and bodies, onion domes (flip y), Easter eggs.
operators
operators: combine distances (booleans, smooth blends, chamfers, stairs) and reshape them (round, onion, extrude, revolve, elongate). Arguments a, b are distances already evaluated at the same point. Exactness: union (min) is exact outside but too deep inside; intersection and subtraction (max) are exact inside but underestimate outside. Smooth and decorative combinations are bounds. All stay Lipschitz <= 1, so raymarching is safe. When interior distances matter (inner-penumbra shadows, thickness, onion of a union), prefer an exact concave primitive (sdDeathStar, sdCutHollowSphere, 2D sdMoon/sdArc + extrude/revolve). Smooth unions are not associative: blend in a fixed order (torso, then limbs, then details). Smooth blend semantics in this library: k is the blend width in distance units. Shapes start blending when |a - b| < k.
float opUnion(float a, float b)bound - Union of two shapes. Use: combining parts.float opSubtract(float a, float b)bound - Shape a with shape b cut out of it. Use: holes, windows, carving, bites.float opIntersect(float a, float b)bound - Region inside both shapes. Use: clipping, lens shapes, trimming with half-spaces.float smin(float a, float b, float k)bound - Smooth union (polynomial, C1). Blends where |a - b| < k, with a max bulge of k/4. Use: organic joins (neck to head, limbs to torso), melting shapes, blobby forms.float smax(float a, float b, float k)bound - Smooth intersection, the mirror of smin. Use: soft clipping, rounded intersections, pillowy cuts.float smoothSubtract(float a, float b, float k)bound - Smooth subtraction: a with b carved out, with filleted edges. Use: eye sockets, nostrils, soft grooves, scooped bowls, worn edges.float sminCubic(float a, float b, float k)bound - Smooth union with a C2 (cubic) transition, so specular highlights and normals have no visible seam. Blends where |a - b| < k, with a max bulge of k/6. Use: close-up organic surfaces, glossy blends, fluids.vec2 sminBlend(float a, float b, float k)bound - Smooth union that also returns the blend weight. Returns vec2(distance, weight), where weight is 1 when the result is fully a and 0 when fully b. Use the weight to mix material colors across the blend. Use: skin-to-cloth transitions, color bleeding across blended parts, gradient-colored blobs.float opChamferUnion(float a, float b, float r)bound - Union with a 45-degree chamfer of size r at the seam. Use: machined parts, architecture, sci-fi panels, bevelled joins.float opStairsUnion(float a, float b, float r, float n)bound - Union with n stair steps of total size r at the seam. Use: terraces, stepped pyramids, ziggurats, layered rock, rice paddies.float opEngrave(float a, float b, float r)bound - Engrave a groove of depth r into a, following the zero set of b. Use: panel lines, carved text paths, seams, grout lines on a surface.float opRound(float d, float r)exact - Round a shape by r. Grows it outward; shrink the inner shape by r first to keep its size. Use: softening any primitive, pebbles from boxes, inflated look.float opOnion(float d, float t)exact - Hollow shell of thickness 2t around the surface. Apply repeatedly for concentric layers. Use: shells, pipes, rings, onion layers, outlines in 2D.float opExtrude(vec3 p, float d2, float h)exact - Extrude a 2D distance d2 (evaluated at p.xy) along Z by half-length h. Use: 3D text and logos, cookie cutters, coins from 2D shapes, extruded profiles.vec2 opRevolve(vec3 p, float o)exact - Revolve around Y. Returns the 2D point to evaluate a profile at. Offset o moves the profile away from the axis. Use: vases, bottles, chess pieces, lathe-turned objects, tori with custom profiles.vec4 opElongate(vec3 p, vec3 h)exact - Elongate: stretch a shape by inserting a straight section of half-size h, keeping exact distances inside too. Returns vec4(q, w). Evaluate the original shape at q.xyz and add w: sdSphere(e.xyz, r) + e.w is a capsule. Use: pills from spheres, long rounded boxes, stretched characters, stadium shapes.
domain
domain: transform the point BEFORE evaluating a distance (repetition, mirroring, polar sectors, folds, twist, bend). Rigid transforms (repeat, mirror, rotate, fold) keep distances exact. Twist and bend stretch space, so their results are only bounds after scaling (see each function). Repetition uses floor(x + 0.5) instead of round(): GLSL leaves round(0.5) implementation-defined, and round can return -0.0.
float domRepeatId(float p, float s)/vec2 domRepeatId(vec2 p, vec2 s)/vec3 domRepeatId(vec3 p, vec3 s)- Cell index for repetition with period s (integer-valued; use with hash functions). Use: per-instance variation: hash12(domRepeatId(p.xz, s)).float domRepeat(float p, float s)/vec2 domRepeat(vec2 p, vec2 s)/vec3 domRepeat(vec3 p, vec3 s)- 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). Use: forests, columns, tiles, crowds, star fields, city blocks.vec2 domRepeatLimited(vec2 p, vec2 s, vec2 lim)/vec3 domRepeatLimited(vec3 p, vec3 s, vec3 lim)- Repetition limited to cells -lim..+lim on each axis (2*lim + 1 copies). Use: rows of windows, fence posts, a finite grid of buttons, colonnades.vec2 domRepeatMirror(vec2 p, vec2 s)- Mirrored repetition: every other cell is flipped, so shapes touching the cell border join seamlessly. Use: tiled ornaments, symmetric wallpaper, seamless pipes and rails.vec2 domPolar(vec2 p, float n)- Polar repetition into n sectors around the origin. Returns the point rotated into the sector centered on +X. Single evaluation: exact for shapes symmetric about their sector's center line. For asymmetric or per-sector-varying shapes, evaluate this sector and its neighbor and take the min (see references/sdf-library-guide.md). Use: petals, spokes, gears, clock marks, radial ornaments, columns around a tower.float domPolarId(vec2 p, float n)- Sector index in [0, n) for domPolar. Use: varying each petal, spoke or column.vec2 domPolarPair(vec2 p, float n)- Neighbor-checked polar repetition: ids (in [0, n)) of the sector holding p and of the adjacent sector p leans toward. Evaluate the shape in both with domPolarSector and take the min. Use it when sectors vary (per-id length, tilt, color) or are asymmetric. It covers shapes of similar size that stay inside their own sector; a shape that reaches across its neighbor needs a wider search. Use: varied petals, tilted fan blades, gear teeth of mixed sizes, uneven clock marks, radial crowds.vec2 domPolarSector(vec2 p, float id, float n)- Rotate p into the frame of polar sector id (its center line on +X). domPolarSector(p, domPolarId(p, n), n) equals domPolar(p, n). Use: the second half of domPolarPair: evaluate a sector's shape by id.vec3 domFold(vec3 p, vec3 n)- Fold space across the plane through the origin with unit normal n. Points behind the plane are reflected. Use: kaleidoscopes, symmetric creatures, KIFS fractals, mirrored architecture.vec3 domTwist(vec3 p, float k)- Twist around Y: rotate XZ by k * y. Divide the resulting distance by L = a/2 + sqrt(1 + a*a/4), a = k * R, where R is the shape's max distance from the Y axis. Without that, the march overshoots. Use: twisted columns, drills, licorice, DNA-like spirals, towels.vec3 domBend(vec3 p, float k)- Bend in XY: rotate XY by k * x. Divide the resulting distance by about 1 + k * R (R = max |p.xy| of the shape). Use: bent beams, arches from boxes, bananas, curved horns.
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].
raymarch
raymarch: 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.
#define ZERO (min(iFrame, 0))const int RAYMARCH_MAX_STEPS = 256;vec3 raymarch(vec3 ro, vec3 rd, float tmin, float tmax, float stepScale)- 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). Use: every SDF raymarcher.vec3 calcNormal(vec3 p, float eps)- 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. Use: shading any SDF hit.float softShadow(vec3 ro, vec3 rd, float tmin, float tmax, float k)- 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). Use: sun shadows, contact shadows, penumbrae.float calcAO(vec3 p, vec3 n, float scale)- 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). Use: crevices, contact darkening, grounding objects on floors.float sdfThickness(vec3 p, vec3 n, float maxDepth)- Thickness behind a surface point, estimated by sampling the SDF inside along -n (an "inverse AO"). Returns 0 (thin, light passes through) .. 1 (thick). maxDepth is the deepest sample in scene units. Use: translucency, subsurface tint, wax and jade, glowing thin edges.
intersect
intersect: analytic ray-primitive intersections. Rays are ro + t * rd with unit rd. Use them for bounding volumes (clip the raymarch range to where the scene can be), exact floors and water planes, glass spheres and eyeballs, and cheap reflections. Formulas follow https://iquilezles.org/articles/intersectors/.
float iPlane(vec3 ro, vec3 rd, vec3 n, float h)- Ray vs plane dot(p, n) + h = 0 (unit n). Returns t, which is negative when the plane is behind the ray or parallel to it. Use: floors, water, mirrors, clipping marches to a ground plane.vec2 iSphere(vec3 ro, vec3 rd, vec3 c, float r)- Ray vs sphere centered at c with radius r. Returns vec2(tNear, tFar), or vec2(-1) on a miss. Uses the precision-friendly form that measures from the closest point on the ray. Use: bounding spheres, glass balls, eyeballs, planets, bubbles.vec2 iBox(vec3 ro, vec3 rd, vec3 b)- Ray vs axis-aligned box centered at the origin with half-extents b (slab method). Returns vec2(tNear, tFar), or vec2(-1) on a miss. Works when the ray starts inside (tNear < 0 < tFar). Use: bounding boxes for raymarching, glass cubes, rooms.
camera
camera: look-at frames, primary rays, field of view, thin-lens depth of field. Convention: uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y, so uv.y spans [-1, 1] and aspect is kept.
mat3 cameraMatrix(vec3 ro, vec3 ta, float roll)- Camera-to-world matrix looking from ro toward ta, with roll in radians. Columns are (right, up, forward). Use: every 3D shader.float fovToFocal(float fovDegrees)- Focal length (the z of the view-space ray) for a vertical field of view in degrees. Use: matching a reference photo, wide (90) vs telephoto (20) framing.vec3 cameraRay(mat3 cam, vec2 uv, float focal)- Primary ray direction for screen point uv. focal is about 1.5-2.5 for natural framing (see fovToFocal). Use: every 3D shader.void thinLensRay(mat3 cam, vec2 uv, float focal, float aperture, float focusDist, vec2 xi, inout vec3 ro, out vec3 rd)- Thin-lens depth of field. Moves the ray origin over a lens disk of radius aperture, and re-aims it so that points at distance focusDist stay sharp. xi is a pair of uniform random numbers in [0,1) (e.g. hash22 of the pixel and frame). Average many samples (AA loop or multipass accumulation). Use: macro shots, product renders, cinematic focus pulls, bokeh.void orthoRay(mat3 cam, vec2 uv, float size, inout vec3 ro, out vec3 rd)- Orthographic ray: parallel rays from a plane of half-heightsizecentered on ro. Use: isometric scenes, technical illustrations, flat diorama looks.
shading
shading: BRDF terms and practical lighting models. Vectors are unit length: n = normal, v = toward the viewer (-rd), l = toward the light. Units are "artist units" with pi folded in: a light of color C lights a white Lambert surface facing it to C. Every function here returns radiance per unit light color, already including NoL. Physically based terms follow Filament (https://google.github.io/filament/Filament.md.html).
vec3 fresnelSchlick(float u, vec3 f0)- 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. Use: reflections that strengthen at grazing angles, rim brightening, water and glass.float distributionGGX(float NoH, float alpha)- GGX / Trowbridge-Reitz normal distribution. alpha = roughness^2. Use: specular highlight shape (inside specularGGX).float visibilitySmithGGX(float NoV, float NoL, float alpha)- Height-correlated Smith visibility. Already contains the 1 / (4 NoL NoV) term. Use: specular shadowing-masking (inside specularGGX).vec3 specularGGX(vec3 n, vec3 v, vec3 l, float roughness, vec3 f0)- Microfacet specular for one light: pi * D * V * F * NoL (artist units). roughness is perceptual, in [0,1]. Use: glossy plastic, metal, wet surfaces, car paint, ceramics.vec3 shadePBR(vec3 n, vec3 v, vec3 l, vec3 albedo, float roughness, float metallic)- 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. Use: hero objects, product renders, anything that needs believable materials.vec3 envBRDFApprox(vec3 f0, float NoV, float roughness)- Split-sum environment specular without a lookup texture (Karis 2014, after Lazarov). Multiply by the sky or environment color in the reflection direction. Use: sky reflections on glossy surfaces, ambient specular.float wrapDiffuse(vec3 n, vec3 l, float w)- Energy-conserving wrap diffuse: light wraps past the terminator by w (0 = Lambert, 0.5 = soft). Use: skin, foliage, cloth, soft stylized shading, fur.vec3 hemisphereLight(vec3 n, vec3 skyColor, vec3 groundColor)- Hemisphere light: sky color from above blended to ground color from below. Use: ambient fill, outdoor sky light, studio fill.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(gktanh(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].
color
color: 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.
vec3 srgbToLinear(vec3 c)- Exact sRGB decode (EOTF): encoded [0,1] -> linear. Use: decoding picked colors, palettes used as albedo, and texture samples.vec3 linearToSrgb(vec3 c)- 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). Use: final output.float luminance(vec3 c)- Relative luminance of linear Rec.709 / sRGB color. Use: desaturation, brightness masks, luminance-based effects.vec3 saturation(vec3 c, float s)- Scale saturation around luminance: 0 = grey, 1 = unchanged, > 1 = more saturated. Use: grading, fading distant objects, stylization.vec3 linearSrgbToOklab(vec3 c)- Linear sRGB -> Oklab (L in [0,1], a/b around [-0.4, 0.4]). Matrices from Bjorn Ottosson (public domain / MIT). Use: perceptual gradients, even-lightness palettes, hue and chroma edits.vec3 oklabToLinearSrgb(vec3 lab)- Oklab -> linear sRGB. The result can fall outside [0,1] for saturated colors, so clamp after tonemapping. Use: converting perceptual edits back for lighting or output.vec3 mixOklab(vec3 a, vec3 b, float t)- Mix two linear colors in Oklab. Avoids the muddy mid-tones of RGB lerps and the hue detours of HSV. Use: gradients, sky ramps, color transitions over time, blending materials.vec3 oklchToLinearSrgb(vec3 lch)- OkLCh (lightness, chroma, hue in radians) -> linear sRGB. Hue sweeps keep lightness constant. L about 0.4-0.9, C about 0.05-0.2 stays mostly in gamut. Use: harmonious palettes, rainbow ramps with even brightness, per-instance hue variation.vec3 cosinePalette(float t, vec3 a, vec3 b, vec3 c, vec3 d)- Cosine palette a + b * cos(2 pi (c t + d)). Output is display-like (sRGB-ish), so decode it for albedo. Integer c values loop seamlessly over t in [0,1]. Use: quick gradients, heat maps, psychedelic color cycling, per-id colors.vec3 blackbody(float kelvin)- Approximate linear sRGB color of a blackbody at temperature kelvin (1000-15000 K), normalized to max channel 1. Uses the Krystek (1985) Planckian-locus fit -> XYZ -> sRGB. Use: fire, embers, lava, stars, incandescent lamps, sunset light, molten metal.
tonemap
tonemap: map scene-linear HDR to display range. Every function here takes linear input (after exposure) and returns LINEAR [0,1]. Then apply linearToSrgb exactly once. Recommended chain: col *= exposure; col = tonemapAgX(col); col = linearToSrgb(col); add dither. Choosing: AgX (default) for 3D scenes, glows, fire, suns and volumes; its highlights roll off to white without hue skews. tonemapNeutral for 2D, product shots and palette-faithful work. ACES for the saturated filmic look.
vec3 tonemapAgX(vec3 c)- 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). Use: default tonemapper for 3D, emissive glows, fire, neon, skies, clouds.vec3 tonemapAgXPunchy(vec3 c)- AgX with the "punchy" look (more contrast and saturation) for stylized art. Use: stylized 3D, saturated sunsets, toy-like renders.vec3 tonemapNeutral(vec3 c)- Khronos PBR Neutral: leaves [0, ~0.76] almost untouched and compresses only highlights, preserving hue. Use: 2D art, palette-faithful scenes, product renders, UI glow.vec3 tonemapACES(vec3 c)- Stephen Hill's ACES fit (RRT + ODT, sRGB primaries). Contrasty and saturated; blues drift purple when very bright. Darker than AgX at the same exposure: multiply the input by about 1.6 to compensate. Use: the classic "filmic game" look.vec3 tonemapReinhard(vec3 c, float white)- Extended Reinhard on luminance: mapswhiteto 1 and preserves hue. Simple and predictable. Use: quick previews, soft low-contrast looks.
volume
volume: participating media (fog, smoke, clouds, haze). mu = dot(rd, l): the cosine between the view ray and the direction TOWARD the light, so forward scattering peaks when looking at the light. Integration follows Hillaire (Frostbite, SIGGRAPH 2015/2016); cloud tricks follow Schneider (Horizon Zero Dawn, 2015).
float phaseIsotropic()- Isotropic phase function (scatters equally in all directions). Use: dusty fog, thick smoke interiors.float phaseRayleigh(float mu)- Rayleigh phase function. Use: sky scattering by air molecules (blue sky).float phaseHG(float mu, float g)- Henyey-Greenstein phase function. g in (-1, 1): > 0 forward (silver linings), < 0 backward. Use: clouds (g ~ 0.6-0.85), fog glow around lights, underwater light shafts.float phaseDualHG(float mu, float gF, float gB, float w)- Two-lobe Henyey-Greenstein: a forward lobe gF and a backward lobe gB, mixed by w (weight of the forward lobe). Keeps the silver lining while clouds lit from behind the camera still show detail. Use: clouds, smoke lit from varying angles.float phaseCornetteShanks(float mu, float g)- Cornette-Shanks phase (a better-normalized Mie approximation). g = 0.8 for atmospheric haze. Use: sun halo in hazy skies, aerosols.float beerPowder(float d)- Beer-Powder lighting term for clouds: 2 e^-d (1 - e^-2d), where d is optical depth toward the sun. Darkens cloud edges that face the light like powdered sugar. Not energy-conserving; use it on the direct term only. Use: cumulus clouds, puffy smoke.void volumeStep(inout vec3 radiance, inout vec3 transmittance, vec3 sigmaT, vec3 inScatter, float ds)- One energy-conserving step of volume integration. sigmaT is extinction per unit length (RGB for tinted media), inScatter is in-scattered radiance at this point (including sigmaS, phase and light), ds is step length. Accumulates into radiance and transmittance. Stable for dense media, unlike radiance += T * S * ds. Use: any raymarched volume: clouds, smoke, fog, fire, nebulae.float distanceFog(float t, float density)- Distance fog amount (0 = clear, 1 = fully fogged) for distance t. Use: depth cueing, haze, underwater murk.float heightFog(vec3 ro, vec3 rd, float t, float a, float b)- 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]. Use: valley mist, ground fog, layered haze in landscapes.
atmosphere
atmosphere: skies and sun. simpleSky is a cheap artistic gradient. atmosphereSky is physically based single scattering (Rayleigh + Mie + ozone) with constants from Hillaire, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique" (EGSR 2020). Distances are in kilometers to avoid float cancellation.
vec3 simpleSky(vec3 rd, vec3 sunDir)- 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). Use: quick backgrounds, reflections, fog color, stylized daylight.vec3 sunDisk(vec3 rd, vec3 sunDir, float angularRadius, float pixelAngle)- 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). Use: suns, moons (use a different tint), bright stars in skies.const float ATMOSPHERE_GROUND_KM = 6360.0;const float ATMOSPHERE_TOP_KM = 6460.0;vec3 atmosphereDensity(float h)- Densities (rayleigh, mie, ozone) at altitude h km above the ground. Use: custom atmosphere marches (aerial perspective, planet views).vec3 atmosphereExtinction(vec3 density)- Extinction per km for the given densities. Use: transmittance through air for sun color and aerial perspective.vec3 atmosphereSky(vec3 rd, vec3 sunDir, float viewHeightKm, float sunIntensity)- Physically based sky radiance along rd for a viewer viewHeightKm above the ground, with single scattering (16 view steps x 8 light steps). sunIntensity about 20. Sunsets come out somewhat dark because multiple scattering is ignored; add a small ambient term if needed. Use: realistic skies, sunsets, aerial perspective colors, planet-from-space views.
post
post: antialiasing helpers, supersampling offsets, lens effects, grain and dithering, all single-pass. Order of a finished frame: (per AA sample) exposure, vignette, grain -> tonemap -> average samples -> linearToSrgb -> dither. See references/rendering-pipeline.md.
float fillAA(float d)/float fillAA(float d, float px)- Antialiased fill of a 2D SDF: 1 inside, 0 outside, box-filtered across one pixel. Uses screen derivatives, so call it outside non-uniform branches and loops. For a fixed pixel size use fillAA(d, px). Use: 2D shapes, icons, text-like strokes, UI, masks with crisp edges.float strokeAA(float d, float hw, float px)- Antialiased stroke of half-width hw around the zero line of a 2D SDF. Use: outlines, line art, rings, wireframes, contour lines.vec2 aaOffset(int i)- 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. Use: AA loops: for (int i = 0; i < N; i++) { vec2 o = aaOffset(i); ... mainColor(fragCoord + o) }.float vignette(vec2 uv, float focal)- Natural (cos^4) vignette for a pinhole camera: uv is the screen point, focal the camera focal length. Wider lenses vignette more. Multiply HDR color before tonemapping. Use: photographic falloff, framing, cinematic looks.vec3 filmGrain(vec3 col, float amount, float n)- Signal-dependent film grain: noise grows with sqrt(intensity), as photon noise does. n should be zero-mean noise (e.g. hash13(vec3(fragCoord, iFrame)) * 2 - 1). Apply in linear HDR before tonemapping. Use: filmic texture, hiding banding, analog looks.vec3 ditherTPDF(vec2 fragCoord, int frame)- Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor. Use: removing banding in skies, fog, vignettes and dark gradients.
debug
debug: visualize intermediate fields. The pack's DEBUG_MODE convention: 0 final render | 1 distance field / contours | 2 normals | 3 material ids 4 step count / depth | 5 masks / density | 6 lighting terms Declare it as #define DEBUG_MODE 0 at the top of the shader. Shadertoy has no custom uniforms.
vec3 debugDistance(float d)- Distance field as contour bands: warm outside, cool inside, white zero line. Bands are 0.1 units apart. Use: checking SDF scale, smoothness, wrong signs, bad blends (kinked or bunched contours).vec3 debugNormal(vec3 n)- Normal as RGB. Use: spotting seams, flipped normals, noisy normals.vec3 debugIdColor(float id)- Distinct color per integer id. Use: material ids, cell ids, instance ids.vec3 debugHeat(float t)- Heat ramp for a value in [0,1]: black, blue, magenta, orange, yellow, white. Use: step counts (steps / maxSteps), depth, cost, any scalar mask.